diff --git a/.claude/skills/add-feature-key/SKILL.md b/.claude/skills/add-feature-key/SKILL.md index 5b37d6f5a..35a62187e 100644 --- a/.claude/skills/add-feature-key/SKILL.md +++ b/.claude/skills/add-feature-key/SKILL.md @@ -25,9 +25,8 @@ the socket; [ADR-0021](../../../docs/decisions/0021-feature-based-entitlement.md `platform_entitlement_cache` itself. - **Tenant-flag** keys read `tenant_feature_flags` (per-tenant rollout / opt-in). - **Killswitches** read `platform_killswitches`, a platform-scoped table with no - tenant column and no foreign key, through the L1 cache. Packet 9 ships that table - **unwritten** — read path only, no toggle — and Phase 03 owns the command that flips a - switch (Step 6). + tenant column and no foreign key, through the L1 cache. Their single writer is + `KillswitchToggle`, reached by the operator route (P03-9 Step 1). `IFeatureFlags` is the **only** module-facing read and it **composes** over the port rather than querying a table; the catalogue's `Source` descriptor says which half a key @@ -331,9 +330,11 @@ role and no `BYPASSRLS` moves it. Killswitches ship as **`platform_killswitches` the Tenancy migration chain with role-qualified policies like `platform_host_to_tenant`'s: `ENABLE` **and** `FORCE`, `FOR SELECT TO learnstack_app USING (true)`, every write reserved to -`learnstack_platform` through the audited `EnterPlatformAdminScope(reason)` path — which -is what makes `tenancy.killswitch.toggle` a MUST-class audit row with a real actor -([ADR-0045 § 5](../../../docs/decisions/0045-entitlement-and-feature-flag-socket.md)). +`learnstack_platform` through the audited, admission-gated `IPlatformAdminScope` path — +which is what makes `tenancy.killswitch.toggle` a MUST-class audit row that names the +operator in `metadata.operator` +([ADR-0045 § 5](../../../docs/decisions/0045-entitlement-and-feature-flag-socket.md), +[ADR-0101](../../../docs/decisions/0101-platform-operator-authority.md)). The overlay is read through the **L1 cache** and invalidated on toggle, under a second allowed platform `CacheKey` family — `platform:tenancy:killswitch`. `EnsureValid` admits @@ -343,31 +344,28 @@ the key's default (`true`, enabled) and logs at `Error`: a cache outage must not every gated path platform-wide. A flip is eventually consistent across instances, bounded by the TTL and the invalidation event. -**Packet 9 ships the table unwritten, and nothing in it flips a switch** +**The table has one writer: `KillswitchToggle`** +([ADR-0101 § 13](../../../docs/decisions/0101-platform-operator-authority.md)). Packet 9 +shipped the table, the policies, the overlay, the cache family and the three +`KillswitchKeys` with no writer, because every write needs an authenticated operator +holding the Platform permission and none existed ([ADR-0045 Amendment 1 § 4](../../../docs/decisions/0045-entitlement-and-feature-flag-socket.md#amendment-1--what-the-other-repository-already-shipped-2026-09-08)). -The table, the policies, the overlay, the cache family and the three `KillswitchKeys` -ship; no writer does. The reason is reachability rather than scheduling: every killswitch -write runs inside `EnterPlatformAdminScope(reason)`, the registered `IPlatformAdminGate` -is `DenyAllPlatformAdminGate`, and nothing can enter that scope until the Platform-scope -permission arrives with the registry in -[Phase 03](../../../docs/roadmap/phase-03-identity-admin.md). A toggle command shipped -now would be unreachable code with a permission key nothing registers. **Phase 03 owns -the toggle command, its permission and its runbook**; until it lands, -`tenancy.killswitch.toggle` carries `(planned)` in the Tenancy matrix beside the -`(off-path)` marker it keeps permanently +P03-9 Step 1 added the operator scheme, the gate and the writer: the operator calls +`PUT /api/platform/v1/killswitches/{key}`, the gate checks `platform.killswitch.write`, +and the writer flips the row and records the MUST result row on one transaction. No +other file may write the table (an architecture rule pins it), and a new key needs no +new command: declaring it in `KillswitchKeys.All` makes it flippable through the same +route. `tenancy.killswitch.toggle` keeps `(off-path)` in the Tenancy matrix permanently ([Audit Coverage § The join](../../../docs/standards/18-audit-coverage.md), [ADR-0044 Amendment 3](../../../docs/decisions/0044-audit-write-path.md#amendment-3--what-the-join-binds-to-and-the-types-the-ports-carry-2026-09-08)). -Every gated read honours a flipped switch the day one exists; what is absent is the -flipping. +Every gated read honours a flipped switch. -So a killswitch key added before Phase 03 is read-only, and its runbook lands with the -command that makes it flippable. The runbook entry — in `docs/runbooks/`, a directory -[Phase 11](../../../docs/roadmap/phase-11-production-hardening.md) owns — describes: +So a killswitch key added from now on is flippable the day it is declared, and its entry +in `docs/runbooks/killswitch.md` lands in the same change. The entry describes: - When to use it (the incident shape). -- How to flip it — the operator action through `EnterPlatformAdminScope(reason)`, never - a hand-written `UPDATE` as `learnstack_app`, which holds no write privilege on the - table. +- How to flip it — the operator request, never a hand-written `UPDATE` as + `learnstack_app`, which holds no write privilege on the table. - How to restore (revert + observability check). A flippable killswitch without a runbook is incomplete. @@ -482,11 +480,11 @@ public async Task RefreshAsync_AppliesAnEqualGenerationPush() - **Omitting the failure posture.** ADR-0034 puts it in the registry; a key that leaves it to the call site has no answer for the unresolved case, which is the one case the member exists for. -- **A killswitch without a runbook, once one can be flipped.** The runbook belongs with - the command Phase 03 lands, not with the key Packet 9 registers. CI does not enforce - its presence; review must. -- **Writing a killswitch toggle in Packet 9.** The table ships unwritten and - `DenyAllPlatformAdminGate` is registered, so the command would be unreachable code - gated by a permission nothing registers. +- **A killswitch without a runbook entry.** The key is flippable the moment it is + declared, so its entry in `docs/runbooks/killswitch.md` belongs in the same change. CI + does not enforce its presence; review must. +- **A second writer of `platform_killswitches`.** `KillswitchToggle` is the only one; an + architecture rule fails any other file that inserts, updates, deletes or truncates the + table. - **Removing a key without a deprecation cycle.** A rename / remove follows the same one-release-deprecation-warning rule as permissions. diff --git a/.claude/skills/local-dev-setup/SKILL.md b/.claude/skills/local-dev-setup/SKILL.md index a7c966e76..93fba8b7f 100644 --- a/.claude/skills/local-dev-setup/SKILL.md +++ b/.claude/skills/local-dev-setup/SKILL.md @@ -220,7 +220,10 @@ a fresh `postgres-data` volume `learnstack_migration` owns every table, `learnstack_app` is what the API connects as, and `learnstack_platform` / `learnstack_outbox_admin` hold audited bypasses. The four roles/passwords and baseline connection strings are in -`.env.example`, and their privileges are not interchangeable. The accepted +`.env.example`, and their privileges are not interchangeable. Two confined roles join +them: `learnstack_identity_ingress` (provider intake) and `learnstack_identity_rebind`, +the offline issuer-rebind tool's role, whose connection string is never a stack or host +setting ([runbook](../../../docs/runbooks/identity-issuer-rebind.md)). The accepted P03-2 application-role sources do not expand this role set. Running migrations as the runtime role would make it the table owner, which is the arrangement `FORCE ROW LEVEL SECURITY` exists to defeat. diff --git a/.claude/skills/seed-tenant/SKILL.md b/.claude/skills/seed-tenant/SKILL.md index 344c8268d..2d622909a 100644 --- a/.claude/skills/seed-tenant/SKILL.md +++ b/.claude/skills/seed-tenant/SKILL.md @@ -99,9 +99,13 @@ credential-free projection children receive process prerequisites without those runtime values. Proxy and trust prerequisites remain available; migration, platform, dispatcher and provider-admin credentials do not enter a Seeder child. -The direct tool reads its process environment; it does not load `.env`. Supply -`ConnectionStrings__Default`, `Identity__AuthorityId` and -`Authentication__Tenant__Issuer` from the selected private configuration. The +The direct tool reads its process environment; it does not load `.env`. It runs only +with `Deployment__Mode=Development` and exits 2 before reading any credential +otherwise: production tenants are onboarded through the operator surface +([runbook](../../../docs/runbooks/tenant-onboarding.md), ADR-0102 § 10). Supply +`Deployment__Mode=Development`, `ConnectionStrings__Default`, +`Identity__AuthorityId` and `Authentication__Tenant__Issuer` from the selected private +configuration. The authority must already be installed: `make seed` passes the stable pair through `make migrate`, whose deployment installer runs before content seeding. The Seeder never installs, rewrites or infers that anchor. A schema-only migration diff --git a/.env.example b/.env.example index f63e6eaa9..8944f3c8f 100644 --- a/.env.example +++ b/.env.example @@ -35,11 +35,12 @@ POSTGRES_USER=learnstack POSTGRES_PASSWORD=learnstack POSTGRES_DB=learnstack -# ─── The four database roles (ADR-0003 Amendment 3) ────────────────────── +# ─── The database roles (ADR-0003 Amendment 3, 14) ─────────────────────── # Read by infra/compose/postgres-init/02-create-roles.sql through psql's -# \getenv on first boot. Four roles and four separate login credentials; -# the role model is closed and a fifth role requires an ADR. Additional -# application-role sources do not create roles (ADR-0076/0077). +# \getenv on first boot. Four baseline roles, the confined fifth and sixth +# below, and one login credential each; the role model is closed and a further +# role requires an ADR. Additional application-role sources do not create +# roles (ADR-0076/0077). # An unset variable aborts initdb rather than creating a passwordless role. LEARNSTACK_MIGRATION_PW=learnstack-migration-dev LEARNSTACK_APP_PW=learnstack-app-dev @@ -47,6 +48,9 @@ LEARNSTACK_PLATFORM_PW=learnstack-platform-dev LEARNSTACK_OUTBOX_PW=learnstack-outbox-dev # ADR-0097 confined machine intake; no business/Platform/outbox access. LEARNSTACK_IDENTITY_INGRESS_PW=learnstack-identity-ingress-dev +# ADR-0104 offline issuer-rebind tool only; no API, worker, seeder or web host +# ever receives this credential or its connection string. +LEARNSTACK_IDENTITY_REBIND_PW=learnstack-identity-rebind-dev # ─── Baseline connection strings ──────────────────────────────────────── # Double underscore is the .NET environment spelling of `ConnectionStrings:X`. @@ -59,7 +63,8 @@ LEARNSTACK_IDENTITY_INGRESS_PW=learnstack-identity-ingress-dev # FORCE ROW LEVEL SECURITY exists to defeat. # Default — ordinary request/job business owners. NOBYPASSRLS. # PlatformAdmin — resolvable only by PlatformAdminScope. BYPASSRLS. -# OutboxDispatcher — API-owned OutboxProcessor only. Never Seeder or web. +# OutboxDispatcher — the API's dispatcher stores only: the OutboxProcessor, the DeliveryProcessor and +# the operator recovery lane behind them. Never Seeder or web. ConnectionStrings__Migration='Host=localhost;Port=5432;Database=learnstack;Username=learnstack_migration;Password=learnstack-migration-dev' ConnectionStrings__Default='Host=localhost;Port=5432;Database=learnstack;Username=learnstack_app;Password=learnstack-app-dev' ConnectionStrings__PlatformAdmin='Host=localhost;Port=5432;Database=learnstack;Username=learnstack_platform;Password=learnstack-platform-dev' @@ -103,6 +108,10 @@ Federation__ClientSecret=learnstack-federation-admin-dev-secret # Federation__Egress__AllowedHosts__0=idp.corp.internal:8443 # IdentityEvents__RealmId= # ConnectionStrings__IdentityIngress=Host=localhost;Port=5432;Database=learnstack;Username=learnstack_identity_ingress;Password= +# The sixth role's connection string exists ONLY in the environment of the offline +# rebind tool for the minutes it runs (docs/runbooks/identity-issuer-rebind.md). +# Never place it in this file, a compose service block or a host configuration: +# ConnectionStrings__IdentityRebind=Host=;Port=5432;Database=learnstack;Username=learnstack_identity_rebind;Password= # Optional native tenant BFF (ADR-0070). Explicit false keeps the anonymous demo # independent of Keycloak. For local watch mode, opt in with true and the issuer # below; production launch requires an HTTPS issuer and a trusting private CA. diff --git a/CLAUDE.md b/CLAUDE.md index 68deedb0f..71518c672 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -318,13 +318,13 @@ rules: `BYPASSRLS` moves. Killswitches live in the platform-scoped `platform_killswitches` ([ADR-0045](docs/decisions/0045-entitlement-and-feature-flag-socket.md)). - Packet 9 ships that table, its policies, the overlay and its cache family — - and **no writer**: every toggle runs inside `EnterPlatformAdminScope(reason)`, - whose registered gate is `DenyAllPlatformAdminGate`, so nothing can enter that - scope until the Platform-scope permission arrives, and - [Phase 03](docs/roadmap/phase-03-identity-admin.md) owns the toggle command, - its permission and its runbook - ([ADR-0045 Amendment 1](docs/decisions/0045-entitlement-and-feature-flag-socket.md)). + Packet 9 shipped that table, its policies, the overlay and its cache family; + the single writer is `KillswitchToggle`, which enters the platform scope only + with a `PlatformAdmission` the operator gate minted for an authenticated + operator holding `platform.killswitch.write` + ([ADR-0101](docs/decisions/0101-platform-operator-authority.md), + [runbook](docs/runbooks/killswitch.md)), and the architecture rules pin that no + other file writes the table. - **Read `platform_entitlement_cache` from a module, `IFeatureFlags` included.** The only sanctioned reader *and* writer is an `IEntitlementProvider` implementation; `IFeatureFlags` composes over the port, which is what makes @@ -347,9 +347,11 @@ rules: branches once, modules never. - Write `audit_log`, `platform_entitlement_cache`, or producer `outbox_messages` rows directly — use `IAuditStore`, `IEntitlementProvider.RefreshAsync`, `IOutbox`. - Only ADR-0046's confined dispatcher writes outbox status through fenced - parameterized SQL; its terminal UPDATE and narrow witness-bound audit INSERT - share one transaction. + Only ADR-0046's confined dispatcher and + [ADR-0103](docs/decisions/0103-operator-recovery-of-asynchronous-work.md)'s confined + operator recovery owner write outbox status through fenced parameterized SQL; each + terminal or recovery UPDATE and its narrow witness-bound audit INSERT share one + transaction. - Write `inbox_messages` or `event_deliveries` from a module or Seeder. ADR-0046's transport-owned acceptance, inbox/business owner and confined scheduler alone write their granted columns. diff --git a/README.md b/README.md index f55fda9ec..c3bb3aaa8 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ for identity, membership and authorization work; the | Area | Delivered now | Next milestone | |---|---|---| | **Tenancy** | Tenant provisioning, organizations, locales, typed settings/branding reads, host resolution and database isolation, plus bounded organization, default, locale and setting administration | Full organization and settings editors in [Phase 06](docs/roadmap/phase-06-renderer-admin-studio.md) | -| **Identity** | Global User binding, contextual Membership/Profile/Role foundations, live scoped authorization, bounded member directory and trusted denial evidence, protected Studio membership and Role administration, native new-user entry and scope switching, verified invitations with automatic email, and revision-pinned Membership custom values with personal consent | Provider event ingress, back-channel revocation, federation, platform authority and DSAR in [Phase 03](docs/roadmap/phase-03-identity-admin.md) | +| **Identity** | Global User binding, contextual Membership/Profile/Role foundations, live scoped authorization, bounded member directory and trusted denial evidence, protected Studio membership and Role administration, native new-user entry and scope switching, verified invitations with automatic email, revision-pinned Membership custom values with personal consent, authenticated provider-event ingress with a deduplicated tenant Audit mirror, back-channel session revocation, and confined tenant SAML/OIDC federation | Platform authority, operational recovery and DSAR in [Phase 03](docs/roadmap/phase-03-identity-admin.md) | | **Customization** | Content types, level taxonomies, exact-definition and generation-cached batched display readers, text-card metadata validation, finite Membership field definition authoring, create-only provisioning defaults and semantic built-in seed verification | Remaining authoring capabilities across [Phases 04–08a](docs/roadmap/README.md) | | **Audit** | Classified write path and transactional durability for business changes | Operational hardening in [Phase 11](docs/roadmap/phase-11-production-hardening.md) | | **Education** | Course and Lesson aggregates, translations, protected-content policy, scoped authoring commands, complete demo seeds and isolated public GET/HEAD reads | Full versioned curriculum in [Phase 05](docs/roadmap/phase-05-education-learning-content.md) | @@ -127,7 +127,9 @@ Continue with the manual HTTPS prerequisites below, then run `make demo`. It creates missing private configuration and restores dependencies without changing Git hooks. `make seed` converges application data and the development identity realm and its application-owned identity foundation without starting the API or -web. The argument-free direct .NET Seeder remains data-only. +web. The argument-free direct .NET Seeder remains data-only and runs only with +`Deployment__Mode=Development`; production tenants are onboarded through the operator +surface ([runbook](docs/runbooks/tenant-onboarding.md)). The seed provisions `demo-english` and `demo-yoga`, their organizations and host mappings, enabled locales, distinct branding, built-in and tenant-authored definitions, diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index 5290d0756..23fa98d4f 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -13,6 +13,13 @@ 2.12.0 or later. --> + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs new file mode 100644 index 000000000..539c2a556 --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/Program.cs @@ -0,0 +1,118 @@ +using System.Runtime.InteropServices; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using Microsoft.Extensions.Configuration; +using OpenTelemetry; +using OpenTelemetry.Metrics; + +namespace LearnStack.Tools.IdentityAuthorityRebind; + +/// +/// The controlled issuer rebind tool (ADR-0104). It takes every value from its environment and one line of standard +/// input, never an argument, and prints one fixed line to standard output. See +/// docs/runbooks/identity-issuer-rebind.md. +/// +internal static class Program +{ + private static readonly TimeSpan StandardInputWait = TimeSpan.FromSeconds(30); + + public static async Task Main(string[] args) + { + if (args.Length != 0) + { + return RebindTool.RefuseInput(Console.Out, RebindToolInput.Fields.Arguments); + } + + // The signals that end a run from outside: an interrupt, a terminate, and the hang-up an SSH session that + // drops sends. Each ends it the way the deadline does: through the token, so the run rolls back, the commit's + // outcome is still reconciled, and the one line is still printed. + using var deadline = new CancellationTokenSource(IdentityIssuerRebind.RunDeadline); + ConsoleCancelEventHandler interrupt = (_, signal) => + { + signal.Cancel = true; + Cancel(deadline); + }; + Console.CancelKeyPress += interrupt; + using var terminate = Register(PosixSignal.SIGTERM, deadline); + using var hangUp = Register(PosixSignal.SIGHUP, deadline); + + try + { + var configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build(); + if (!RebindToolInput.TryRead( + name => Environment.GetEnvironmentVariable(name), + () => ReadStandardInputLine(deadline.Token), + configuration, + out var input, + out var field)) + { + return deadline.IsCancellationRequested + ? RebindTool.Refuse(Console.Out, "cancelled") + : RebindTool.RefuseInput(Console.Out, field); + } + + using var meters = input!.OtlpEndpoint is null + ? null + : Sdk.CreateMeterProviderBuilder() + .AddMeter(IdentityRebindMetrics.MeterName, PlatformOperatorMetrics.MeterName) + .AddOtlpExporter() + .Build(); + using var client = KeycloakRealmContinuitySource.CreateClient(); + var realm = new KeycloakRealmContinuitySource(client, input.RealmClientId, input.RealmClientSecret); + var exit = await RebindTool.RunAsync(input, realm, Console.Out, deadline.Token); + meters?.ForceFlush(5000); + return exit; + } +#pragma warning disable CA1031 // The tool emits one fixed line, never an exception payload that could carry a credential. + catch (Exception) +#pragma warning restore CA1031 + { + return RebindTool.Refuse(Console.Out, "unexpected"); + } + finally + { + Console.CancelKeyPress -= interrupt; + } + } + + private static PosixSignalRegistration Register(PosixSignal signal, CancellationTokenSource deadline) => + PosixSignalRegistration.Create(signal, context => + { + context.Cancel = true; + Cancel(deadline); + }); + + /// A signal can arrive in the instant the run is ending; it must not fault the process then. + private static void Cancel(CancellationTokenSource source) + { + try + { + source.Cancel(); + } + catch (ObjectDisposedException) + { + } + } + + /// + /// The operator token's line when it is piped: bounded in time and ended by a signal, so a pipe that is never + /// closed refuses the run instead of holding it before its deadline exists. + /// + private static string? ReadStandardInputLine(CancellationToken cancellationToken) + { + if (!Console.IsInputRedirected) + { + return null; + } + + var read = Task.Run(Console.In.ReadLine, CancellationToken.None); + try + { + return read.Wait(StandardInputWait, cancellationToken) ? read.Result : null; + } + catch (OperationCanceledException) + { + return null; + } + } +} diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs new file mode 100644 index 000000000..b57bc2c18 --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindTool.cs @@ -0,0 +1,201 @@ +using System.Text; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Npgsql; + +namespace LearnStack.Tools.IdentityAuthorityRebind; + +/// +/// The offline controlled issuer rebind (ADR-0104): validate the human, admit the act, run it, and say how it ended in +/// one fixed line that carries counts and classes and never an identifier. +/// +/// +/// +/// Exit codes: 0 the issuer was changed or already was; 2 refused with the state unchanged (a retry +/// repeats the whole proof); 3 the commit's outcome could not be read back, so the operator reads the stored +/// issuer before anything else. +/// +/// +/// The operator token is validated by the same the API scheme is +/// configured from, and the grant is read per act from PlatformOperator:Grants, never from a claim. The +/// tool is the second caller of the witness minter's closed census: it mints nothing itself. +/// +/// +internal static class RebindTool +{ + internal const int Applied = 0; + internal const int Refused = 2; + internal const int Unknown = 3; + + internal static async Task RunAsync( + RebindToolInput input, INewRealmContinuitySource realm, TextWriter output, CancellationToken cancellationToken) + { + // One handle for every outcome from here on, so an operator can quote it whatever the run answered. + var correlation = "rebind-" + Guid.NewGuid().ToString("N"); + PlatformOperatorSettings? settings; + try + { + settings = PlatformOperatorSettings.FromConfiguration(input.Configuration, input.Mode); + } + catch (InvalidOperationException) + { + return Refuse(output, "operator_configuration_invalid", correlation); + } + + if (settings is null) + { + return Refuse(output, "operator_issuer_not_configured", correlation); + } + + try + { + return await RunAdmittedAsync(input, realm, output, settings, correlation, cancellationToken); + } + catch (OperationCanceledException) + { + // The deadline or an interrupt ended the run before the database was touched, or the database half has + // already rolled back and reported it. + return Refuse(output, "cancelled", correlation); + } +#pragma warning disable CA1031 // The tool emits one fixed line, never an exception payload that could carry a credential. + catch (Exception failure) when (failure is not OutOfMemoryException) +#pragma warning restore CA1031 + { + // Nothing the run can throw reaches here after its commit: the database half reports an unknown commit as + // such. So the state is unchanged, and the correlation finds the intent row if one was written. + return Refuse(output, "unexpected", correlation); + } + } + + private static async Task RunAdmittedAsync( + RebindToolInput input, + INewRealmContinuitySource realm, + TextWriter output, + PlatformOperatorSettings settings, + string correlation, + CancellationToken cancellationToken) + { + var clock = new SystemClock(); + using var backchannel = new PlatformOperatorBackchannel(); + var health = new PlatformOperatorMetadataHealth(clock); + var manager = PlatformOperatorValidation.CreateConfigurationManager(settings, backchannel, health, NullLoggerFactory.Instance); + var validation = await new PlatformOperatorTokenValidator(settings, manager, health, clock).ValidateAsync( + input.OperatorToken, PlatformOperatorSettings.RebindToolExecutor, correlation, cancellationToken); + if (!validation.IsValid) + { + return Refuse(output, "operator_token_" + validation.Cause, correlation); + } + + using var services = new ServiceCollection() + .AddLogging() + .AddSingleton(clock) + .AddOptions() + .Bind(input.Configuration.GetSection(PlatformOperatorGrantOptions.SectionName)).Services + .AddSingleton>(new PlatformOperatorGrantOptionsValidator(input.Mode)) + .AddSingleton() + .AddSingleton() + .BuildServiceProvider(); + var admitted = await services.GetRequiredService().AdmitAsync( + validation.Witness!, PlatformOperations.IdentityAuthorityRebind, input.Ticket, cancellationToken); + if (!admitted.IsAdmitted) + { + return Refuse(output, "operator_" + Cause(admitted.Refusal), correlation); + } + + await using var store = StoreScope(); + var outcome = await new IdentityIssuerRebind(store.ServiceProvider.GetRequiredService(), clock) + .RunAsync(input.ConnectionString, input.Target, admitted.Admission!, realm, cancellationToken: cancellationToken); + output.WriteLine(Line(outcome, correlation)); + return outcome.Result switch + { + IdentityRebindResult.Applied or IdentityRebindResult.AlreadyApplied => Applied, + IdentityRebindResult.Unknown => Unknown, + _ => Refused, + }; + } + + /// The closed audit-store graph the rebind rows are written through, on the role's own connection. + private static AsyncServiceScope StoreScope() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new IdentityAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The rebind rows are written on the tool's own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService() + .CreateAsyncScope(); + + /// One line: the outcome class, the correlation id that finds the audit rows, and counts. + internal static string Line(IdentityRebindOutcome outcome, string correlation) + { + var line = new StringBuilder("rebind: outcome=").Append(IdentityRebindMetrics.Label(outcome)) + .Append(" correlation=").Append(correlation); + if (outcome.Detail != IdentityRebindDetail.None) + { + line.Append(" detail=").Append(IdentityRebindDetails.Token(outcome.Detail)); + } + + if (outcome.LiveSessions is { } sessions) + { + line.Append(" sessions=").Append(sessions); + } + + if (outcome.Continuity is { } counts) + { + line.Append(" active=").Append(counts.StoredActive).Append(" closing=").Append(counts.StoredClosing) + .Append(" closed=").Append(counts.StoredClosed).Append(" reported=").Append(counts.Enumerated) + .Append(" unkeyable=").Append(counts.Unkeyable).Append(" missing_active=").Append(counts.MissingActive) + .Append(" reappearing_closed=").Append(counts.ReappearingClosed) + .Append(" unbootstrapped=").Append(counts.Unbootstrapped); + } + + return line.ToString(); + } + + /// + /// Refuses before the database half began, under a closed reason. The reason is also the label the run is counted + /// under, once the process exports meters; the line is what an operator keeps either way. + /// + internal static int Refuse(TextWriter output, string reason, string? correlation = null) + { + var label = "refused_" + reason; + IdentityRebindMetrics.RecordToolRefusal(label); + output.WriteLine("rebind: outcome=" + label + (correlation is null ? string.Empty : " correlation=" + correlation)); + return Refused; + } + + /// Refuses an input before anything was read from it: the setting's closed name, never its value. + internal static int RefuseInput(TextWriter output, string field) + { + IdentityRebindMetrics.RecordToolRefusal("refused_input"); + output.WriteLine("rebind: outcome=refused_input detail=" + field); + return Refused; + } + + private static string Cause(PlatformRefusal refusal) => refusal switch + { + PlatformRefusal.InvalidWitness => "invalid_witness", + PlatformRefusal.UnknownOperation => "unknown_operation", + PlatformRefusal.InvalidTicket => "invalid_ticket", + PlatformRefusal.MissingPermission => "missing_permission", + _ => "not_admitted", + }; +} diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs new file mode 100644 index 000000000..5f3d7db17 --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs @@ -0,0 +1,145 @@ +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.Extensions.Configuration; +using Npgsql; + +namespace LearnStack.Tools.IdentityAuthorityRebind; + +/// What the operator hands the tool, read from the process environment and one line of standard input. +/// +/// Nothing is an argument: an argument is visible to every user of the host and survives in shell history. The +/// operator token comes from LEARNSTACK_OPERATOR_TOKEN or, when that is unset, the first line of standard +/// input. The realm credential is a view-users client the operator creates for the run and deletes after it. +/// +internal sealed record RebindToolInput( + string ConnectionString, + IdentityAuthorityRegistration Target, + string OperatorToken, + string? Ticket, + string RealmClientId, + string RealmClientSecret, + DeploymentMode Mode, + IConfiguration Configuration, + string? OtlpEndpoint) +{ + internal const string ConnectionStringKey = "ConnectionStrings__IdentityRebind"; + internal const string TokenKey = "LEARNSTACK_OPERATOR_TOKEN"; + internal const string TicketKey = "LEARNSTACK_REBIND_TICKET"; + internal const string RealmClientIdKey = "LEARNSTACK_REBIND_REALM_CLIENT_ID"; + internal const string RealmClientSecretKey = "LEARNSTACK_REBIND_REALM_CLIENT_SECRET"; + internal const string AuthorityKey = "Identity__AuthorityId"; + internal const string IssuerKey = "Authentication__Tenant__Issuer"; + internal const string ModeKey = "Deployment__Mode"; + + /// + /// The closed names a refused input is reported under: the setting that was unusable, never its value. The + /// connection string covers a missing value, one that does not parse and one that names another role. + /// + internal static class Fields + { + internal const string Arguments = "arguments"; + internal const string ConnectionString = "connection_string"; + internal const string OperatorToken = "operator_token"; + internal const string RealmClient = "realm_client"; + internal const string AuthorityId = "authority_id"; + internal const string Issuer = "issuer"; + internal const string DeploymentMode = "deployment_mode"; + + /// Every name, so the runbook and a test can hold the set closed. + internal static readonly string[] All = + [Arguments, ConnectionString, OperatorToken, RealmClient, AuthorityId, Issuer, DeploymentMode]; + } + + /// + /// Reads and validates the input. False means nothing was usable; then names the first + /// setting that was not, and no value is reported. + /// + internal static bool TryRead( + Func environment, + Func standardInput, + IConfiguration configuration, + out RebindToolInput? input, + out string field) + { + input = null; + field = Fields.ConnectionString; + var connection = environment(ConnectionStringKey); + if (string.IsNullOrWhiteSpace(connection)) + { + return false; + } + + var token = environment(TokenKey); + if (string.IsNullOrWhiteSpace(token)) + { + token = standardInput(); + } + + field = Fields.OperatorToken; + if (string.IsNullOrWhiteSpace(token) || token.Length > PlatformOperatorTokenValidator.MaximumTokenCharacters) + { + return false; + } + + var clientId = environment(RealmClientIdKey); + var clientSecret = environment(RealmClientSecretKey); + field = Fields.RealmClient; + if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret)) + { + return false; + } + + field = Fields.AuthorityId; + if (!Guid.TryParseExact(environment(AuthorityKey), "D", out var authority) || authority == Guid.Empty) + { + return false; + } + + field = Fields.Issuer; + var newIssuer = environment(IssuerKey); + if (string.IsNullOrEmpty(newIssuer)) + { + return false; + } + + // The mode is explicit, as it is for the API and read the way the API reads it: it decides whether a loopback + // operator issuer and the demo operator's grant are admitted, so a tool that guessed it could admit what the + // API refuses. + field = Fields.DeploymentMode; + if (!DeploymentModeParser.TryParse(environment(ModeKey), out var mode)) + { + return false; + } + + try + { + field = Fields.ConnectionString; + if (new NpgsqlConnectionStringBuilder(connection).Username != IdentityIssuerRebind.RoleName) + { + return false; + } + + field = Fields.Issuer; + var target = new IdentityAuthorityRegistration(IdentityAuthorityId.From(authority), newIssuer); + if (mode != DeploymentMode.Development && new Uri(newIssuer).Scheme != Uri.UriSchemeHttps) + { + // Loopback HTTP is a Development transport only: a stored issuer no other mode's API accepts would be + // an outage, and the realm credential would travel in clear. + return false; + } + + var ticket = environment(TicketKey); + input = new RebindToolInput( + connection, target, token.Trim(), string.IsNullOrWhiteSpace(ticket) ? null : ticket, + clientId, clientSecret, mode, configuration, environment("OTEL_EXPORTER_OTLP_ENDPOINT")); + field = string.Empty; + return true; + } + catch (Exception failure) when (failure is ArgumentException or UriFormatException) + { + return false; + } + } +} diff --git a/backend/src/LearnStack.Tools.Seeder/Program.cs b/backend/src/LearnStack.Tools.Seeder/Program.cs index 14406dbab..73b1931e5 100644 --- a/backend/src/LearnStack.Tools.Seeder/Program.cs +++ b/backend/src/LearnStack.Tools.Seeder/Program.cs @@ -39,6 +39,17 @@ return 2; } +// The seed capability is a development capability (ADR-0102 § 10). Production tenants are onboarded +// through the operator surface, so a seeder started anywhere but a Development deployment refuses +// before it reads a credential or opens a connection. +if (!string.Equals(Environment.GetEnvironmentVariable("Deployment__Mode"), "Development", StringComparison.Ordinal)) +{ + Console.Error.WriteLine( + "seed: the seeder runs only when Deployment__Mode is Development. Production tenants are " + + "onboarded through the operator surface (docs/runbooks/tenant-onboarding.md)."); + return 2; +} + // The seeder is a host without an HTTP surface, and it exists so the two demo tenants are // written by the same commands a request writes them with — ADR-0042 requires that: a // seeder inserting the tenant and its default organization itself would be a second copy diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs new file mode 100644 index 000000000..b30d813c8 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs @@ -0,0 +1,52 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Contracts.OperatorActs; + +/// The one limit the operator administrator acts and their routes share. +public static class OperatorSubjectLimits +{ + /// The longest provider subject an operator may name. + public const int MaximumProviderSubjectLength = 255; +} + +/// +/// Creates one finite Role template in an operator-named Tenant (ADR-0102 § 2, § 6). +/// +/// +/// Reachable only through the operator source. Naming the same role again with the same template is +/// the same act; a tenant that already has any Membership refuses, because a template is a +/// pristine-prefix operation. +/// +public sealed record OperatorInitializeRoleCommand(Guid RoleId, BuiltInRoleKey BuiltInKey, PermissionScope CapabilityScope) + : IRequest>; + +/// +/// Creates the first tenant-wide administrator of a Tenant that has never had a Membership +/// (ADR-0102 § 5, § 7). +/// +/// The new Membership's id, supplied so a retry is exact. +/// The administrator Role template the operator initialized. +/// +/// The person's sub at the identity authority's issuer. The person must already have signed in +/// once at the tenant's host, so a User exists; an email address is never an identifier. +/// +public sealed record OperatorCreateFirstAdminCommand( + Guid MembershipId, + Guid RoleId, + [property: PiiSensitive] string ProviderSubject) : IRequest>; + +/// +/// Creates a replacement tenant-wide administrator for a Tenant that has Membership history but no +/// active administrator (ADR-0102 § 8). +/// +/// +/// The only act that may add an administrator to a tenant with history, and only while none is active. +/// +public sealed record OperatorRecoverAdminCommand( + Guid MembershipId, + Guid RoleId, + [property: PiiSensitive] string ProviderSubject) : IRequest>; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs index d587189f0..fd690df56 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs @@ -29,6 +29,12 @@ public interface IMembershipWriteStore : IAggregateWriteStoreRetains the exact scoped root after the complete User/tenant plan; reread before mutation. Task LockAsync(MembershipId membershipId, CancellationToken cancellationToken = default); Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default); + + /// + /// Whether the tenant has an Active, undeleted, tenant-wide Membership holding a tenant administrator + /// Role (ADR-0102 § 8). The recovery predicate; read under the ordered locks. + /// + Task HasActiveTenantAdministratorAsync(CancellationToken cancellationToken = default); Task ValidateGraphAsync(CancellationToken cancellationToken = default); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs new file mode 100644 index 000000000..5c7e65a10 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs @@ -0,0 +1,18 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Application.Abstractions; + +/// +/// Resolves an operator-supplied provider subject to the Active User it names, under the stored +/// identity authority (ADR-0102 § 5). +/// +/// +/// A confined single-act resolver: the request supplies only the provider subject, never the authority +/// or the derived key, and an unknown or non-Active subject answers null. The operator creates no +/// User and an email address is never an identifier. +/// +public interface IOperatorSubjectResolver +{ + /// The Active user for , or null. + Task ResolveActiveUserAsync(string providerSubject, CancellationToken cancellationToken = default); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs index 4696fa924..c8f8c9493 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs @@ -3,6 +3,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Invitations; using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Memberships; using LearnStack.Modules.Identity.Application.Contracts.Roles; using LearnStack.Modules.Identity.Application.Contracts.Entry; @@ -40,6 +41,9 @@ public void Describe(IAuditCatalogBuilder builder) builder.MustAudit("identity.membership.create_first_seed_admin", OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.membership.create_seed", OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.membership_profile.set_seed_profile", OperationType.Update, typeof(Membership)); + builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); + builder.MustAudit("identity.membership.create_first_admin", OperationType.SecurityEvent, typeof(Membership)); + builder.MustAudit("identity.membership.recover_admin", OperationType.SecurityEvent, typeof(Membership)); builder.Off(); builder.Off(); builder.MustAudit(IdentityOperationPolicySource.MembershipDirectoryOperation, OperationType.ReadSensitive, typeof(Membership)); @@ -84,5 +88,9 @@ public void Describe(IAuditCatalogBuilder builder) builder.Off(); builder.DeclareOffPath("identity.user.create", OperationType.SecurityEvent, OperationClass.Must, typeof(User)); builder.DeclareOffPath("identity.authorization.deny", OperationType.SecurityEvent, OperationClass.Must); + // The controlled issuer rebind (ADR-0104 § 8): an intent row on its own short transaction and a result + // row with the change, both from the offline tool's role and neither through the pipeline. + builder.DeclareOffPath("identity.authority.rebind_attempt", OperationType.SecurityEvent, OperationClass.Must, typeof(IdentityAuthority)); + builder.DeclareOffPath("identity.authority.rebind", OperationType.SecurityEvent, OperationClass.Must, typeof(IdentityAuthority)); } } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs index d219221ec..2051c3594 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs @@ -2,6 +2,7 @@ using LearnStack.Modules.Identity.Application.Contracts.CustomFields; using LearnStack.Modules.Identity.Application.Contracts.Invitations; using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Roles; using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Federation; @@ -124,6 +125,9 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("identity.membership_profile.set_seed_profile", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("identity.role.verify_seed", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("identity.membership.verify_seed", AuthorizationSourceKind.Seed), + OperationPolicy.ForTrusted("identity.operator.initialize_role", AuthorizationSourceKind.PlatformOperator), + OperationPolicy.ForTrusted("identity.operator.create_first_admin", AuthorizationSourceKind.PlatformOperator), + OperationPolicy.ForTrusted("identity.operator.recover_admin", AuthorizationSourceKind.PlatformOperator), ]; private static OperationPolicy Federation(string id) => diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs new file mode 100644 index 000000000..9b3450cce --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs @@ -0,0 +1,253 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.Modules.Identity.Application.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.OperatorActs; + +/// The operator acts' answers: a refusal an operator can act on, in the shapes the API already uses. +internal static class OperatorIdentityFailures +{ + internal static Result NotFound() => Result.Fail(new Error(new LocalizedMessage("lockey_not_found"))); + + internal static Result Unavailable() => Result.Fail(new Error(new LocalizedMessage("lockey_dependency_unavailable"))); + + /// + /// What a refused storage write answers, in the vocabulary the sibling Identity handlers already use: a + /// lost race or a lock that timed out is retryable, a missing plan is unavailable, and the rest is the + /// foundation refusing the graph. + /// + internal static Result Storage(IdentityFoundationStorageException failure) => failure.Failure switch + { + IdentityFoundationStorageFailure.Conflict => Result.Fail(new Error(new LocalizedMessage("lockey_concurrency_conflict"))), + IdentityFoundationStorageFailure.Plan => Unavailable(), + _ => Rule("$", "lockey_identity_foundation_refused"), + }; + + /// + /// A 409 with the reason on the field it concerns. The top-level code stays + /// business_rule_violation because the status map is closed and a module-specific code would + /// answer 500. + /// + internal static Result Rule(string field, string reason) => Result.Fail(new Error( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage(reason)], + })); +} + +/// +/// Creates one finite Role template for an operator (ADR-0102 § 2, § 6): under the tenant's ordered +/// lock, before any Membership exists, once. +/// +internal sealed class OperatorInitializeRoleCommandHandler( + IRoleWriteStore store, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock) : IRequestHandler> +{ + public async Task> Handle(OperatorInitializeRoleCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!context.IsResolved || context.OrganizationId is not null || !SeedFoundationGate.ValidRoot(request.RoleId)) + return OperatorIdentityFailures.Rule("RoleId", "lockey_validation_failed"); + if (IdentityFoundationManifest.Version1.FindTemplate(request.BuiltInKey, request.CapabilityScope) is null) + return OperatorIdentityFailures.Rule("BuiltInKey", "lockey_role_template_unknown"); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + + var plan = new IdentityMutationLockPlan([], context.TenantId, IdentityTenantLockMode.Exclusive); + var admission = await guard.AdmitAsync(request, plan, cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + try + { + var id = RoleId.From(request.RoleId); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + + // The same template named again is the same act, so a reply lost on the wire costs nothing. + if (await store.FindAsync(id, cancellationToken) is { } existing) + { + // The act is identified by the Role's id, tenant, key, scope and creator. Its grants are not part of + // that: once an administrator exists the template may be edited, and a retry of the original act + // must still find its Role. + if (existing.TenantId != context.TenantId || existing.BuiltInKey != request.BuiltInKey + || existing.PermissionScope != request.CapabilityScope || existing.CreatedBy != UserId.SystemActor) + return OperatorIdentityFailures.Rule("RoleId", "lockey_identifier_taken"); + guard.MarkReplayed(); + return Result.Ok(request.RoleId); + } + + if (await store.HasMembershipHistoryAsync(cancellationToken)) + return OperatorIdentityFailures.Rule("$", "lockey_tenant_has_memberships"); + if (guard.RequireCurrent(admission.Value) is { IsFailure: true } changed) + return Result.Fail(changed.Error); + + var role = Role.Create( + id, context.TenantId, request.BuiltInKey, request.CapabilityScope, clock.UtcNow, UserId.SystemActor); + if (role.IsFailure) return Result.Fail(role.Error); + await store.AddAsync(role.Value, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + return Result.Ok(request.RoleId); + } + catch (IdentityFoundationStorageException failure) + { + return OperatorIdentityFailures.Storage(failure); + } + catch (IdentityMutationLockException) + { + return OperatorIdentityFailures.Unavailable(); + } + } +} + +/// +/// The shared core of the two administrator acts: name the person, take the ordered locks, judge the +/// act's own predicate under them, create the Membership (ADR-0102 § 5, § 7, § 8). +/// +internal static class OperatorAdministratorCreation +{ + internal static async Task> CreateAsync( + object request, + Guid membershipId, + Guid roleId, + string providerSubject, + bool firstAdmin, + IMembershipWriteStore store, + IRoleReadStore roles, + IOperatorSubjectResolver subjects, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock, + CancellationToken cancellationToken) + { + if (!context.IsResolved || context.OrganizationId is not null || !SeedFoundationGate.ValidRoot(membershipId) + || !SeedFoundationGate.ValidRoot(roleId) || string.IsNullOrWhiteSpace(providerSubject) || providerSubject.Length > OperatorSubjectLimits.MaximumProviderSubjectLength) + return OperatorIdentityFailures.Rule("MembershipId", "lockey_validation_failed"); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + + // The confined resolver is reachable only from inside a live operator act, so the check is made before + // it is called and not left to the lock plan that needs its answer. + if (guard.RequireLiveAct(request) is { IsFailure: true } notLive) + return Result.Fail(notLive.Error); + + // The person first: naming a person who has not signed in refuses before any lock or write. + if (await subjects.ResolveActiveUserAsync(providerSubject, cancellationToken) is not { } userId + || !SeedFoundationGate.ValidUser(userId)) + return OperatorIdentityFailures.Rule("ProviderSubject", "lockey_bootstrap_required"); + + // The User fence before the tenant fence, as every Membership admission takes them. + var plan = new IdentityMutationLockPlan([userId], context.TenantId, IdentityTenantLockMode.Exclusive); + var admission = await guard.AdmitAsync(request, plan, cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + try + { + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken)) + return OperatorIdentityFailures.NotFound(); + var id = MembershipId.From(membershipId); + + // The same act named again finds its Membership, so a reply lost on the wire costs nothing. This is + // asked before the Role's present state is judged: the new administrator may have edited the + // template since, and a retry of the original act must not be refused for that. + if (await store.FindAsync(id, cancellationToken) is { } existing) + { + if (existing.TenantId != context.TenantId || existing.UserId != userId + || existing.OrganizationId is not null || existing.Status != MembershipStatus.Active + || !existing.RoleAssignments.Any(assignment => assignment.RoleId.Value == roleId)) + return OperatorIdentityFailures.Rule("MembershipId", "lockey_identifier_taken"); + guard.MarkReplayed(); + return Result.Ok(membershipId); + } + + var role = await roles.ReadAsync(RoleId.From(roleId), cancellationToken); + if (!IsAdministratorRole(role, context.TenantId, firstAdmin)) + return OperatorIdentityFailures.Rule("RoleId", "lockey_role_not_initialized"); + + // The act's own predicate, under the locks. The first administrator refuses any Membership + // history, so it is not a way to add an administrator to a tenant that has had members; the + // recovery refuses while an active tenant-wide administrator exists. + if (firstAdmin ? await store.HasMembershipHistoryAsync(cancellationToken) + : await store.HasActiveTenantAdministratorAsync(cancellationToken)) + { + return OperatorIdentityFailures.Rule( + "$", firstAdmin ? "lockey_tenant_has_memberships" : "lockey_administrator_exists"); + } + + if (guard.RequireCurrent(admission.Value) is { IsFailure: true } changed) + return Result.Fail(changed.Error); + var membership = Membership.Create( + id, context.TenantId, null, userId, role!, clock.UtcNow, UserId.SystemActor); + if (membership.IsFailure) return Result.Fail(membership.Error); + await store.AddAsync(membership.Value, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + return Result.Ok(membershipId); + } + catch (IdentityFoundationStorageException failure) + { + return OperatorIdentityFailures.Storage(failure); + } + catch (IdentityMutationLockException) + { + return OperatorIdentityFailures.Unavailable(); + } + } + + // The first administrator takes the pristine template the operator initialized; a recovery takes any + // current tenant administrator Role of the tenant, because the Role may have been edited since. + private static bool IsAdministratorRole(Role? role, TenantId tenant, bool firstAdmin) => firstAdmin + ? SeedMembershipCreation.IsDeclaredRole(role, tenant, PermissionScope.Tenant, firstAdmin: true) + : role is not null && role.TenantId == tenant && role.PermissionScope == PermissionScope.Tenant + && role.IsTenantAdministrator; +} + +/// Creates the first tenant-wide administrator of a tenant that has never had a Membership. +internal sealed class OperatorCreateFirstAdminCommandHandler( + IMembershipWriteStore store, + IRoleReadStore roles, + IOperatorSubjectResolver subjects, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock) : IRequestHandler> +{ + public Task> Handle(OperatorCreateFirstAdminCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + return OperatorAdministratorCreation.CreateAsync( + request, request.MembershipId, request.RoleId, request.ProviderSubject, true, + store, roles, subjects, context, lifecycle, guard, clock, cancellationToken); + } +} + +/// Creates a replacement administrator for a tenant that has none active. +internal sealed class OperatorRecoverAdminCommandHandler( + IMembershipWriteStore store, + IRoleReadStore roles, + IOperatorSubjectResolver subjects, + ITenantContext context, + IIdentityScopeLifecycleReader lifecycle, + OperatorActGuard guard, + IClock clock) : IRequestHandler> +{ + public Task> Handle(OperatorRecoverAdminCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + return OperatorAdministratorCreation.CreateAsync( + request, request.MembershipId, request.RoleId, request.ProviderSubject, false, + store, roles, subjects, context, lifecycle, guard, clock, cancellationToken); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs index 488a24711..72b50b9ac 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs @@ -92,7 +92,7 @@ internal static async Task> CreateAsync(object request, Guid member } } - private static bool IsDeclaredRole(Role? role, TenantId tenant, PermissionScope scope, bool firstAdmin) => + internal static bool IsDeclaredRole(Role? role, TenantId tenant, PermissionScope scope, bool firstAdmin) => role is { Version: 0, UpdatedAt: null, UpdatedBy: null } && role.TenantId == tenant && role.CreatedBy == UserId.SystemActor && role.CreatedAt != default && role.AdoptedReleaseVersion == 1 diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs index 5831489e7..ab892c2da 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.Bootstrap.cs @@ -57,6 +57,7 @@ public async Task BootstrapAsync(GlobalIdentitySubject } catch (NpgsqlException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } catch (UserBindingStorageException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } + catch (IdentityAuthorityChangedException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } catch (TimeoutException) { result = IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); } finally { cleanupSucceeded = await DisposeOwnerAsync(frame); } return cleanupSucceeded ? result : IdentityBootstrapResult.Refused(IdentityCreationRefusal.Unavailable); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs index 44760de4a..5fc6b4124 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs @@ -114,6 +114,7 @@ private async Task CreateAsync(GlobalIdentitySubject subj catch (NpgsqlException) { result = StorageFailure(owner); } catch (AuditWriteFailedException) { result = StorageFailure(owner); } catch (UserBindingStorageException) { result = StorageFailure(owner); } + catch (IdentityAuthorityChangedException) { result = StorageFailure(owner); } catch (IOException) { result = StorageFailure(owner); } catch (TimeoutException) { result = StorageFailure(owner); } finally { cleanupSucceeded = await DisposeOwnerAsync(owner); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs new file mode 100644 index 000000000..b00b60293 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/INewRealmContinuitySource.cs @@ -0,0 +1,60 @@ +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// +/// What the tool read from the new realm: its discovery issuer, the size of its published key set, and the users it +/// reports (ADR-0104 § 6). +/// +/// The issuer of the new realm's discovery document. +/// How many signing keys its key set publishes. +/// Whether the enumeration reached the end of the realm, not merely a page. +/// The sub of every user the realm reported. +public sealed record NewRealmSnapshot( + string DiscoveredIssuer, int SigningKeyCount, bool Complete, IReadOnlyCollection Subjects); + +/// +/// The read-only view of the new realm the continuity proof needs. The tool implements it over the realm's own +/// endpoints with an operator-supplied view-users credential; a test implements it over a fixed list. +/// +/// +/// An implementation reads, and refuses by throwing ; it never writes and +/// never returns a partial enumeration as complete. +/// +public interface INewRealmContinuitySource +{ + /// Reads the discovery document, the key set and every user of the realm behind . + Task ReadAsync(string issuer, CancellationToken cancellationToken = default); +} + +/// Where in the read of the new realm a refusal happened: a step, never a value. +public enum NewRealmStep +{ + /// Not attributed to one step. + Unspecified = 0, + + /// The discovery document, or the issuer's own path. + Discovery, + + /// The published key set. + KeySet, + + /// The read-only client's token. + Token, + + /// The administration API's user count. + UserCount, + + /// The administration API's user list. + UserList, +} + +/// +/// The new realm could not be read completely. A fixed message: no address, credential or body is retained, only the +/// step that refused. +/// +/// The step of the read that refused. +public sealed class NewRealmUnavailableException(NewRealmStep step = NewRealmStep.Unspecified) + : Exception("The new realm could not be read completely.") +{ + /// The step of the read that refused. + public NewRealmStep Step { get; } = step; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs index 6dc5add40..0b4b1b8df 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs @@ -1,4 +1,5 @@ using LearnStack.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identity; using System.Data; using Npgsql; @@ -36,6 +37,13 @@ private async Task QualifyCoreAsync(CancellationToken cancellationToken) await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken); await using (var readOnly = new NpgsqlCommand("SET TRANSACTION READ ONLY", connection, transaction)) await readOnly.ExecuteNonQueryAsync(cancellationToken); + // Shared and first (ADR-0104 § 5): a start that overlaps a controlled issuer rebind waits for it here, + // and the next statement takes a fresh READ COMMITTED snapshot, so it compares against the new value. + await using (var rebind = new NpgsqlCommand("SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)", connection, transaction)) + { + rebind.Parameters.AddWithValue("key", IdentityAdvisoryLockKey.ForAuthorityRebind()); + await rebind.ExecuteNonQueryAsync(cancellationToken); + } string database; await using (var command = new NpgsqlCommand( "SELECT current_user, authority_id, issuer, current_database() FROM public.identity_authority WHERE id = 1", connection, transaction)) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs index 892df9d56..d431a42e3 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs @@ -43,6 +43,7 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); @@ -58,6 +59,8 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo services.TryAddScoped(); services.TryAddSingleton(FederationOperationBudgets.Default); services.TryAddSingleton(); + // The operator's port (Amendment 10) is its own: the tenant runner never holds it, and it too fails closed. + services.TryAddSingleton(); services.TryAddSingleton(); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetFederationConnectionQuery))); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnMembershipProfileQuery))); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs new file mode 100644 index 000000000..2a02cb8ef --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityIssuerRebind.cs @@ -0,0 +1,618 @@ +using System.Data; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Time; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// +/// The controlled issuer rebind (ADR-0104): the database half the offline tool drives, on the confined role +/// learnstack_identity_rebind and nothing else. +/// +/// +/// +/// Order, and why. One direct, non-pooled transaction takes the exclusive rebind advisory lock as its first +/// statement, so a start or a creation waits for it. Under that lock the tool reads the stored authority; a run whose +/// target already equals the stored issuer ends there, writing nothing, not even a row. Otherwise the intent row +/// commits on its own short transaction, so an aborted attempt is on record, and only then the freeze check, the +/// continuity proof, the issuer update and the result row run on the main transaction, which commits them together +/// or not at all. +/// +/// +/// Every refusal leaves the state unchanged and a retry repeats the whole proof. An unknown COMMIT is +/// reconciled by reading the issuer on a fresh connection: the target means it applied, the old value means it did +/// not, anything else is reported as unknown. +/// +/// +public sealed class IdentityIssuerRebind(IAuditStore audit, IClock clock) +{ + /// The only database role the tool may use. + public const string RoleName = "learnstack_identity_rebind"; + + /// The runtime roles whose sessions freeze the rebind: the platform role runs in the same hosts. + private static readonly string[] RuntimeRoles = + ["learnstack_app", "learnstack_outbox_admin", "learnstack_identity_ingress", "learnstack_platform"]; + + private const string AdvisoryLock = "SELECT pg_catalog.pg_advisory_xact_lock(@key)"; + + /// The longest the tool waits for the exclusive lock when none is asked for. + public static readonly TimeSpan DefaultLockWait = TimeSpan.FromSeconds(30); + + /// How long one run may take from its start, proof included; the tool's deadline. + public static readonly TimeSpan RunDeadline = TimeSpan.FromMinutes(10); + + /// The bound the server puts on any one statement of the run. + public static readonly TimeSpan StatementTimeout = TimeSpan.FromSeconds(120); + + /// + /// How long the server lets the main transaction sit idle before it ends it and frees the lock: the fence for a + /// tool that is hung rather than dead. It exceeds , so it never ends a run that is still + /// inside its own deadline. + /// + public static readonly TimeSpan IdleTransactionTimeout = TimeSpan.FromMinutes(15); + + /// Runs one rebind to and returns how it ended; it never throws for a refusal. + /// The rebind role's connection string; any other role is refused. + /// The stable authority and the new issuer. + /// The operator's admission for the rebind operation. + /// The read-only view of the new realm. + /// How long the first statement waits for the exclusive lock; when null. + /// The run's deadline. + public async Task RunAsync( + string connectionString, + IdentityAuthorityRegistration target, + PlatformAdmission admission, + INewRealmContinuitySource realm, + TimeSpan? lockWait = null, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionString); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(admission); + ArgumentNullException.ThrowIfNull(realm); + + var outcome = await RunCoreAsync(connectionString, target, admission, realm, lockWait ?? DefaultLockWait, cancellationToken); + IdentityRebindMetrics.Record(outcome); + return outcome; + } + + private async Task RunCoreAsync( + string connectionString, + IdentityAuthorityRegistration target, + PlatformAdmission admission, + INewRealmContinuitySource realm, + TimeSpan lockWait, + CancellationToken cancellationToken) + { + // The admission is the operator's authority: this operation only, fresh when the run begins (the proof + // may run longer than the admission's age, which bounds the start and not the work), and spent once. + if (!ReferenceEquals(admission.Operation, PlatformOperations.IdentityAuthorityRebind) + || string.IsNullOrEmpty(admission.Operator.CorrelationId) + || (clock.UtcNow - admission.IssuedAt).Duration() > PlatformAdmission.MaximumAge + || !admission.TryConsume()) + { + return Refused(IdentityRebindRefusal.NotAdmitted); + } + + var connection = TryNormalize(connectionString, lockWait); + if (connection is null) + { + return Refused(IdentityRebindRefusal.RoleInvalid, IdentityRebindDetail.RoleSession); + } + + NpgsqlConnection? main = null; + NpgsqlTransaction? transaction = null; + try + { + main = await OpenAsync(connection, cancellationToken); + var posture = await CheckPostureAsync(main, lockWait, cancellationToken); + if (posture != IdentityRebindDetail.None) + { + return Refused(IdentityRebindRefusal.RoleInvalid, posture); + } + + transaction = await main.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken); + await ExecuteAsync(main, transaction, AdvisoryLock, cancellationToken, + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + + var (storedAuthority, storedIssuer) = await ReadAuthorityAsync(main, transaction, cancellationToken); + if (storedAuthority == target.AuthorityId.Value + && string.Equals(storedIssuer, target.Issuer, StringComparison.Ordinal)) + { + await transaction.RollbackAsync(cancellationToken); + return new IdentityRebindOutcome(IdentityRebindResult.AlreadyApplied); + } + + if (!await TryWriteIntentAsync(connection, admission, storedAuthority, storedIssuer, target.Issuer, cancellationToken)) + { + return Refused(IdentityRebindRefusal.AuditFailed); + } + + if (storedAuthority != target.AuthorityId.Value) + { + return Refused(IdentityRebindRefusal.AuthorityMismatch); + } + + var sessions = await CountRuntimeSessionsAsync(main, transaction, cancellationToken); + if (sessions > 0) + { + return new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.LiveSessions, null, sessions); + } + + NewRealmSnapshot snapshot; + try + { + snapshot = await realm.ReadAsync(target.Issuer, cancellationToken); + } + catch (NewRealmUnavailableException failure) + { + return Refused(IdentityRebindRefusal.NewRealmUnavailable, RealmDetail(failure.Step)); + } + + if (!string.Equals(snapshot.DiscoveredIssuer, target.Issuer, StringComparison.Ordinal)) + { + return Refused(IdentityRebindRefusal.NewRealmIssuerMismatch); + } + + if (!snapshot.Complete || snapshot.SigningKeyCount < 1) + { + return Refused(IdentityRebindRefusal.NewRealmIncomplete); + } + + var stored = await ReadUsersAsync(main, transaction, storedAuthority, cancellationToken); + var continuity = IdentityRebindContinuity.Evaluate(target.AuthorityId, stored, snapshot.Subjects); + if (!continuity.Holds) + { + return new IdentityRebindOutcome( + IdentityRebindResult.Refused, IdentityRebindRefusal.ContinuityBroken, continuity, sessions); + } + + // The freeze is asked again at the last moment: the proof may have run for minutes, and a host that never + // qualifies against the authority (the outbox, the ingress poller, the platform role) is not held by the lock. + var late = await CountRuntimeSessionsAsync(main, transaction, cancellationToken); + if (late > 0) + { + return new IdentityRebindOutcome( + IdentityRebindResult.Refused, IdentityRebindRefusal.LiveSessions, continuity, late); + } + + await ChangeIssuerAsync(main, transaction, storedIssuer, target.Issuer, cancellationToken); + await audit.WriteIdentityRebindResultAsync( + Draft(admission, admission.Operation.AuditSlug, AuditOutcome.Success, storedAuthority, + storedIssuer, target.Issuer, continuity), + admission, main, transaction, cancellationToken); + + return await CommitAsync(transaction, connection, storedIssuer, target.Issuer, continuity, cancellationToken); + } + catch (AuditWriteFailedException) + { + return Refused(IdentityRebindRefusal.AuditFailed); + } + catch (PostgresException failure) when (failure.SqlState == PostgresErrorCodes.LockNotAvailable) + { + return Refused(IdentityRebindRefusal.RebindInProgress); + } + catch (Exception failure) when (failure is NpgsqlException or TimeoutException or StoredAuthorityException) + { + return Refused(IdentityRebindRefusal.DatabaseUnavailable, Classify(failure)); + } + catch (OperationCanceledException) + { + return Refused(IdentityRebindRefusal.Cancelled); + } + finally + { + // An uncommitted transaction rolls back here, and with it the lock. A failure to dispose never replaces + // the outcome of the run: an applied rebind must not be reported as an exception. + await DisposeQuietlyAsync(transaction); + await DisposeQuietlyAsync(main); + } + } + + private static async ValueTask DisposeQuietlyAsync(IAsyncDisposable? resource) + { + if (resource is null) + { + return; + } + + try + { + await resource.DisposeAsync(); + } +#pragma warning disable CA1031 // Cleanup never replaces the outcome of the run. + catch (Exception) +#pragma warning restore CA1031 + { + } + } + + private static async Task CommitAsync( + NpgsqlTransaction transaction, + string connection, + string oldIssuer, + string newIssuer, + IdentityRebindContinuityResult continuity, + CancellationToken cancellationToken) + { + try + { + await transaction.CommitAsync(cancellationToken); + return new IdentityRebindOutcome(IdentityRebindResult.Applied, Continuity: continuity); + } + catch (Exception failure) when (failure is not OutOfMemoryException) + { + // The server may have committed before the connection failed. Read the issuer on a fresh connection: + // the target means it applied, the old value means it did not, and anything else is not guessed at. + try + { + // The shared form of the lock, under the connection's own lock_timeout: it is granted only once the + // original transaction has ended, so the read cannot see the issuer before an in-flight COMMIT lands. + await using var reader = await OpenAsync(connection, CancellationToken.None); + await using var check = await reader.BeginTransactionAsync(IsolationLevel.ReadCommitted, CancellationToken.None); + await ExecuteAsync(reader, check, "SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)", CancellationToken.None, + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + await using var command = new NpgsqlCommand( + "SELECT issuer FROM public.identity_authority WHERE id = 1", reader, check); + var current = (string?)await command.ExecuteScalarAsync(CancellationToken.None); + if (string.Equals(current, newIssuer, StringComparison.Ordinal)) + { + return new IdentityRebindOutcome(IdentityRebindResult.Applied, Continuity: continuity); + } + + return string.Equals(current, oldIssuer, StringComparison.Ordinal) + ? new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.CommitFailed, continuity) + : new IdentityRebindOutcome(IdentityRebindResult.Unknown, Continuity: continuity); + } + catch (Exception reconcile) when (reconcile is not OutOfMemoryException) + { + // Whatever stopped the read, the commit's outcome is not known: never a refusal, which would say + // the state is unchanged. + return new IdentityRebindOutcome(IdentityRebindResult.Unknown, Continuity: continuity); + } + } + } + + /// Normalizes the connection string, or null when it is malformed or not the rebind role's. + private static string? TryNormalize(string connectionString, TimeSpan lockWait) + { + NpgsqlConnectionStringBuilder builder; + try + { + builder = new NpgsqlConnectionStringBuilder(connectionString); + } + catch (ArgumentException) + { + return null; + } + + if (!string.Equals(builder.Username, RoleName, StringComparison.Ordinal)) + { + return null; + } + + // A direct, never-pooled, never-multiplexed connection of its own, so the lock belongs to this transaction + // and no other session shares it. The first statement is the lock, so the wait is bounded here by the + // server and not by a statement; a transaction that idles longer than a proof could is the tool's fence. + builder.Pooling = false; + builder.Multiplexing = false; + builder.Enlist = false; + builder.IncludeErrorDetail = false; + builder.LogParameters = false; + builder.Timeout = 15; + builder.CommandTimeout = (int)StatementTimeout.TotalSeconds; + builder.ApplicationName = "learnstack-identity-rebind"; + + // The main connection sits idle in its transaction while the new realm is read, so the operating system probes + // it: a quiet connection survives a middlebox that cuts one. Npgsql's own KeepAlive is deliberately off: it + // sends a message on the idle connection, and every message the server receives restarts the idle-in- + // transaction clock, so a hung tool would never be ended by the fence below. + builder.TcpKeepAlive = true; + builder.TcpKeepAliveTime = 30; + builder.TcpKeepAliveInterval = 10; + builder.KeepAlive = 0; + builder.Options = FormattableString.Invariant( + $"-c lock_timeout={LockTimeoutMilliseconds(lockWait)} -c statement_timeout={(long)StatementTimeout.TotalMilliseconds} -c idle_in_transaction_session_timeout={(long)IdleTransactionTimeout.TotalMilliseconds}"); + return builder.ConnectionString; + } + + private static int LockTimeoutMilliseconds(TimeSpan lockWait) => (int)Math.Max(1, lockWait.TotalMilliseconds); + + private static async Task OpenAsync(string connectionString, CancellationToken cancellationToken) + { + var connection = new NpgsqlConnection(connectionString); + try + { + await connection.OpenAsync(cancellationToken); + return connection; + } + catch + { + await connection.DisposeAsync(); + throw; + } + } + + /// + /// The role is exactly what the migration granted: itself, no attribute that escalates, no membership either way, + /// owning nothing, no privilege on any other relation, and on the three it uses exactly the declared table and + /// column grants; and the server applied the session settings the run asked for. Returns the first check that + /// failed, or . + /// + /// + /// A relation that belongs to an extension (pg_stat_statements and its PUBLIC-readable views, PostGIS + /// catalogs) is not one the deployment's own schema put there and is not counted. Every other relation in + /// public counts, a privilege held through PUBLIC included, because the role is meant to reach nothing but + /// its three tables. + /// + private static async Task CheckPostureAsync( + NpgsqlConnection connection, TimeSpan lockWait, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + """ + SELECT (session_user::text = current_user::text AND current_user::text = @role) AS session_ok, + (r.rolcanlogin AND NOT r.rolinherit AND NOT r.rolbypassrls AND NOT r.rolsuper + AND NOT r.rolcreatedb AND NOT r.rolcreaterole AND NOT r.rolreplication) AS attributes_ok, + NOT EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid OR m.roleid = r.oid) AS no_membership, + (NOT (has_schema_privilege(r.oid, 'public', 'CREATE') + OR has_database_privilege(r.oid, current_database(), 'CREATE')) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class o WHERE o.relowner = r.oid) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_proc o WHERE o.proowner = r.oid) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace o WHERE o.nspowner = r.oid)) AS no_creation, + (SELECT count(*) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname NOT IN ('identity_authority', 'users', @audit) + AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d + WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e') + AND CASE + WHEN c.relkind IN ('r', 'p', 'v', 'm', 'f') + THEN has_any_column_privilege(r.oid, c.oid, 'SELECT,INSERT,UPDATE,REFERENCES') + OR has_table_privilege(r.oid, c.oid, 'DELETE,TRUNCATE,TRIGGER,MAINTAIN') + WHEN c.relkind = 'S' + THEN has_sequence_privilege(r.oid, c.oid, 'USAGE,SELECT,UPDATE') + ELSE false + END) AS stray_relations, + (SELECT count(*) FROM pg_catalog.pg_attribute a + JOIN pg_catalog.pg_class c ON c.oid = a.attrelid + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND a.attnum > 0 AND NOT a.attisdropped AND ( + (c.relname = 'users' + AND (has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT,UPDATE,REFERENCES') + OR has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT') + <> (a.attname IN ('authority_id', 'subject_key', 'provider_subject', 'status')))) + OR (c.relname = 'identity_authority' + AND (has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT,REFERENCES') + OR NOT has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT') + OR has_column_privilege(r.oid, c.oid, a.attnum, 'UPDATE') <> (a.attname = 'issuer'))) + OR (c.relname = @audit + AND (has_column_privilege(r.oid, c.oid, a.attnum, 'SELECT,UPDATE,REFERENCES') + OR NOT has_column_privilege(r.oid, c.oid, a.attnum, 'INSERT'))))) AS column_drift, + NOT (has_table_privilege(r.oid, 'public.users', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES,MAINTAIN') + OR has_table_privilege(r.oid, 'public.identity_authority', 'INSERT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES,MAINTAIN') + OR has_table_privilege(r.oid, to_regclass('public.' || quote_ident(@audit)), + 'SELECT,UPDATE,DELETE,TRUNCATE,TRIGGER,REFERENCES,MAINTAIN')) AS no_table_grants, + ((SELECT setting::bigint FROM pg_catalog.pg_settings WHERE name = 'lock_timeout') = @lock + AND (SELECT setting::bigint FROM pg_catalog.pg_settings WHERE name = 'statement_timeout') = @statement + AND (SELECT setting::bigint FROM pg_catalog.pg_settings WHERE name = 'idle_in_transaction_session_timeout') = @idle) AS settings_ok + FROM pg_catalog.pg_roles r WHERE r.rolname = current_user + """, connection); + command.Parameters.AddWithValue("role", RoleName); + command.Parameters.AddWithValue("audit", IdentityRebindAuditInstaller.Table); + command.Parameters.AddWithValue("lock", (long)LockTimeoutMilliseconds(lockWait)); + command.Parameters.AddWithValue("statement", (long)StatementTimeout.TotalMilliseconds); + command.Parameters.AddWithValue("idle", (long)IdleTransactionTimeout.TotalMilliseconds); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + return IdentityRebindDetail.RoleSession; + } + + // A check the catalog could not answer is a check that failed: a null never passes. + bool Flag(string column) => reader.GetOrdinal(column) is var at && !reader.IsDBNull(at) && reader.GetBoolean(at); + long Count(string column) => reader.GetOrdinal(column) is var at && !reader.IsDBNull(at) ? reader.GetInt64(at) : 1; + + if (!Flag("session_ok")) + { + return IdentityRebindDetail.RoleSession; + } + + if (!Flag("attributes_ok")) + { + return IdentityRebindDetail.RoleAttributes; + } + + if (!Flag("no_membership")) + { + return IdentityRebindDetail.RoleMembership; + } + + if (!Flag("no_creation") || Count("stray_relations") != 0 || Count("column_drift") != 0 || !Flag("no_table_grants")) + { + return IdentityRebindDetail.RoleGrants; + } + + return Flag("settings_ok") ? IdentityRebindDetail.None : IdentityRebindDetail.SessionSettings; + } + + private static async Task<(Guid Authority, string Issuer)> ReadAuthorityAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + "SELECT authority_id, issuer FROM public.identity_authority WHERE id = 1", connection, transaction); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) + { + throw new StoredAuthorityException("No identity authority is installed."); + } + + var result = (reader.GetGuid(0), reader.GetString(1)); + if (await reader.ReadAsync(cancellationToken)) + { + throw new StoredAuthorityException("The identity authority is not a singleton."); + } + + return result; + } + + /// + /// The intent row, on its own connection and its own short transaction so it commits whether or not the main + /// transaction does. It takes no lock the main transaction holds, because it reads nothing. + /// + private async Task TryWriteIntentAsync( + string connection, PlatformAdmission admission, Guid authority, string oldIssuer, string newIssuer, + CancellationToken cancellationToken) + { + try + { + await using var intent = await OpenAsync(connection, cancellationToken); + await using var transaction = await intent.BeginTransactionAsync(cancellationToken); + await audit.WriteIdentityRebindIntentAsync( + Draft(admission, admission.Operation.AttemptAuditSlug!, AuditOutcome.Indeterminate, authority, + oldIssuer, newIssuer, continuity: null), + admission, intent, transaction, cancellationToken); + await transaction.CommitAsync(cancellationToken); + return true; + } + catch (Exception failure) when (failure is AuditWriteFailedException or NpgsqlException or TimeoutException) + { + return false; + } + } + + private static async Task CountRuntimeSessionsAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, CancellationToken cancellationToken) + { + // The server serves pg_stat_activity from a snapshot it keeps for the rest of the transaction, so a second + // count in the same transaction would repeat the first. The snapshot is dropped before every count. + await ExecuteAsync(connection, transaction, "SELECT pg_catalog.pg_stat_clear_snapshot()", cancellationToken); + + // pg_stat_activity shows another role's session as a row with its role and database even where its query + // is hidden, which is all the freeze needs: a session of a runtime role, other than this one's own. + await using var command = new NpgsqlCommand( + """ + SELECT count(*) FROM pg_catalog.pg_stat_activity + WHERE datname = current_database() AND usename::text = ANY(@roles) AND pid <> pg_catalog.pg_backend_pid() + """, connection, transaction); + command.Parameters.AddWithValue("roles", RuntimeRoles); + return (int)(long)(await command.ExecuteScalarAsync(cancellationToken))!; + } + + private static async Task> ReadUsersAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, Guid authority, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + "SELECT subject_key, provider_subject, status FROM public.users WHERE authority_id = @authority", + connection, transaction); + command.Parameters.AddWithValue("authority", authority); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + var users = new List(); + while (await reader.ReadAsync(cancellationToken)) + { + if (!Enum.TryParse(reader.GetString(2), ignoreCase: false, out var status) || !Enum.IsDefined(status)) + { + throw new StoredAuthorityException("A stored user has a status this rebind does not know."); + } + + users.Add(new IdentityRebindStoredUser( + IdentitySubjectKey.FromBytes(reader.GetFieldValue(0)), + reader.IsDBNull(1) ? null : reader.GetString(1), + status)); + } + + return users; + } + + private static async Task ChangeIssuerAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, string oldIssuer, string newIssuer, + CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand( + "UPDATE public.identity_authority SET issuer = @new WHERE id = 1 AND issuer = @old", connection, transaction); + command.Parameters.AddWithValue("new", newIssuer); + command.Parameters.AddWithValue("old", oldIssuer); + if (await command.ExecuteNonQueryAsync(cancellationToken) != 1) + { + throw new StoredAuthorityException("The identity authority issuer did not change as read."); + } + } + + private static async Task ExecuteAsync( + NpgsqlConnection connection, NpgsqlTransaction transaction, string sql, CancellationToken cancellationToken, + params (string Name, object Value)[] parameters) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + foreach (var (name, value) in parameters) + { + command.Parameters.AddWithValue(name, value); + } + + await command.ExecuteNonQueryAsync(cancellationToken); + } + + private AuditEntryDraft Draft( + PlatformAdmission admission, string operation, AuditOutcome outcome, Guid authority, string oldIssuer, + string newIssuer, IdentityRebindContinuityResult? continuity) => new() + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "identity", + Operation = operation, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = nameof(IdentityAuthority), + EntityId = authority.ToString("D"), + Outcome = outcome, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = "{\"issuer\":" + AuditJson.Quote(oldIssuer) + "}", + AfterState = "{\"issuer\":" + AuditJson.Quote(newIssuer) + "}", + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = clock.UtcNow, + Metadata = "{\"operator\":" + PlatformOperatorAttribution.From(admission).ToOperatorJson(admission.Ticket) + + (continuity is null ? string.Empty : ",\"continuity\":" + ContinuityJson(continuity)) + "}", + }; + + private static string ContinuityJson(IdentityRebindContinuityResult counts) => + "{\"active\":" + counts.StoredActive + ",\"closing\":" + counts.StoredClosing + ",\"closed\":" + counts.StoredClosed + + ",\"reported\":" + counts.Enumerated + ",\"unkeyable\":" + counts.Unkeyable + + ",\"unbootstrapped\":" + counts.Unbootstrapped + "}"; + + private static IdentityRebindOutcome Refused( + IdentityRebindRefusal refusal, IdentityRebindDetail detail = IdentityRebindDetail.None) => + new(IdentityRebindResult.Refused, refusal, Detail: detail); + + private static IdentityRebindDetail RealmDetail(NewRealmStep step) => step switch + { + NewRealmStep.Discovery => IdentityRebindDetail.RealmDiscovery, + NewRealmStep.KeySet => IdentityRebindDetail.RealmKeySet, + NewRealmStep.Token => IdentityRebindDetail.RealmToken, + NewRealmStep.UserCount => IdentityRebindDetail.RealmUserCount, + NewRealmStep.UserList => IdentityRebindDetail.RealmUserList, + _ => IdentityRebindDetail.None, + }; + + /// The kind of database failure, from its SQLSTATE or its type and never from its text. + private static IdentityRebindDetail Classify(Exception failure) => failure switch + { + PostgresException { SqlState: PostgresErrorCodes.InvalidPassword or PostgresErrorCodes.InvalidAuthorizationSpecification } + => IdentityRebindDetail.DatabaseAuthentication, + PostgresException { SqlState: PostgresErrorCodes.InsufficientPrivilege } => IdentityRebindDetail.DatabasePermission, + PostgresException { SqlState: PostgresErrorCodes.QueryCanceled } or TimeoutException or NpgsqlException { InnerException: TimeoutException } + => IdentityRebindDetail.DatabaseTimeout, + NpgsqlException => IdentityRebindDetail.DatabaseConnection, + _ => IdentityRebindDetail.AuthorityState, + }; + + /// The stored authority or its users are not what the run read, or are not readable as a rebind needs. + private sealed class StoredAuthorityException(string message) : Exception(message); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs new file mode 100644 index 000000000..6f9cfd064 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindContinuity.cs @@ -0,0 +1,115 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// One stored user as the continuity proof reads it: only the four columns the rebind role may see. +public sealed record IdentityRebindStoredUser(IdentitySubjectKey SubjectKey, string? ProviderSubject, UserStatus Status); + +/// What the continuity proof counted. Counts and classes only; no subject, key or person is named. +/// Active users of the stored authority. +/// Closing users, which neither rule below judges unless only their key is retained. +/// Closed tombstones, which retain only a key. +/// Distinct subjects the new realm reported. +/// Reported subjects that cannot be a LearnStack subject (blank, over 255 characters or not storable text). +/// Active users whose exact subject the new realm does not report. +/// Retained keys of Closed (or key-only Closing) users that a reported subject would claim again. +/// Reported subjects that match no stored user, which is a person who has not signed in yet. +public sealed record IdentityRebindContinuityResult( + int StoredActive, + int StoredClosing, + int StoredClosed, + int Enumerated, + int Unkeyable, + int MissingActive, + int ReappearingClosed, + int Unbootstrapped) +{ + /// Whether continuity holds: no Active user is lost and no closed person can reappear. + public bool Holds => MissingActive == 0 && ReappearingClosed == 0; +} + +/// +/// The continuity proof of a controlled issuer rebind (ADR-0104 § 6) as a pure function of what the database +/// retains and what the new realm reports. +/// +/// +/// +/// Active rows retain the exact subject, so presence is a direct ordinal comparison. Closed rows retain only the +/// key, so absence needs the canonical encoding: the key of no reported subject may equal a retained Closed key, +/// which is what stops a tombstoned person from reappearing under the new issuer. A reported subject with no +/// stored key is allowed, because that person has not bootstrapped. +/// +/// +/// A Closing user is judged by neither rule while it retains its subject, because closure owns that transition; a +/// Closing user that retains only its key is judged like a Closed one. A reported subject that cannot be a +/// LearnStack subject is counted and cannot equal any stored one, since every stored subject was keyed under the +/// same rules. +/// +/// +public static class IdentityRebindContinuity +{ + /// Compares the stored users of with the complete set the new realm reported. + public static IdentityRebindContinuityResult Evaluate( + IdentityAuthorityId authority, + IReadOnlyCollection stored, + IReadOnlyCollection reported) + { + ArgumentNullException.ThrowIfNull(stored); + ArgumentNullException.ThrowIfNull(reported); + + var subjects = new HashSet(reported, StringComparer.Ordinal); + var reportedKeys = new HashSet(StringComparer.Ordinal); + var unkeyable = 0; + foreach (var subject in subjects) + { + try + { + reportedKeys.Add(IdentitySubjectKey.Compute(authority, subject).Hex); + } + catch (ArgumentException) + { + unkeyable++; + } + } + + int active = 0, closing = 0, closed = 0, missing = 0, reappearing = 0; + var storedKeys = new HashSet(StringComparer.Ordinal); + foreach (var user in stored) + { + storedKeys.Add(user.SubjectKey.Hex); + switch (user.Status) + { + case UserStatus.Active: + active++; + if (user.ProviderSubject is null || !subjects.Contains(user.ProviderSubject)) + { + missing++; + } + + break; + case UserStatus.Closing: + closing++; + if (user.ProviderSubject is null && reportedKeys.Contains(user.SubjectKey.Hex)) + { + reappearing++; + } + + break; + default: + closed++; + if (reportedKeys.Contains(user.SubjectKey.Hex)) + { + reappearing++; + } + + break; + } + } + + return new IdentityRebindContinuityResult( + active, closing, closed, subjects.Count, unkeyable, missing, reappearing, + reportedKeys.Count(key => !storedKeys.Contains(key))); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs new file mode 100644 index 000000000..2e3c41272 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityRebindOutcome.cs @@ -0,0 +1,216 @@ +using System.Diagnostics.Metrics; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// How a controlled issuer rebind ended (ADR-0104 § 9). +public enum IdentityRebindResult +{ + /// The issuer changed and its result row committed with it. + Applied = 1, + + /// The stored issuer already equalled the target; nothing was written, not even a row. + AlreadyApplied = 2, + + /// The state is unchanged; a retry repeats the whole proof. + Refused = 3, + + /// The commit's outcome could not be read back; the operator reads the stored issuer before anything else. + Unknown = 4, +} + +/// Why a rebind was refused: a closed set that reports a class and never a value. +public enum IdentityRebindRefusal +{ + None = 0, + NotAdmitted, + RoleInvalid, + RebindInProgress, + DatabaseUnavailable, + AuthorityMismatch, + LiveSessions, + NewRealmUnavailable, + NewRealmIssuerMismatch, + NewRealmIncomplete, + ContinuityBroken, + AuditFailed, + CommitFailed, + Cancelled, +} + +/// +/// Which check inside a refusal class failed: a closed set that names a step or a kind of failure, never a value, an +/// address or a credential, so the one printed line can tell an operator where to look. +/// +public enum IdentityRebindDetail +{ + None = 0, + + /// The connection is not the role's own session. + RoleSession, + + /// A role attribute escalates: superuser, bypass, creation, replication, login or inheritance. + RoleAttributes, + + /// The role belongs to a role or has a member. + RoleMembership, + + /// The role can create objects, or holds a privilege beyond the declared grants or lacks one of them. + RoleGrants, + + /// The server did not apply the session settings the run asked for, as a pooler's startup handling can. + SessionSettings, + + /// The database could not be reached. + DatabaseConnection, + + /// The database refused the role's credential. + DatabaseAuthentication, + + /// The database refused a statement for lack of a privilege. + DatabasePermission, + + /// A database call exceeded its time limit. + DatabaseTimeout, + + /// The stored authority is missing, is not one row, or changed under the run. + AuthorityState, + + /// The new realm's discovery document or issuer path was unreadable. + RealmDiscovery, + + /// The new realm's key set was unreadable. + RealmKeySet, + + /// The new realm refused the read-only client's token. + RealmToken, + + /// The new realm's user count was refused or out of bounds. + RealmUserCount, + + /// The new realm's user list was refused, unreadable or out of bounds. + RealmUserList, +} + +/// The closed spelling of in the printed line. +public static class IdentityRebindDetails +{ + /// The token of ; empty for . + public static string Token(IdentityRebindDetail detail) => detail switch + { + IdentityRebindDetail.RoleSession => "role_session", + IdentityRebindDetail.RoleAttributes => "role_attributes", + IdentityRebindDetail.RoleMembership => "role_membership", + IdentityRebindDetail.RoleGrants => "role_grants", + IdentityRebindDetail.SessionSettings => "session_settings", + IdentityRebindDetail.DatabaseConnection => "database_connection", + IdentityRebindDetail.DatabaseAuthentication => "database_authentication", + IdentityRebindDetail.DatabasePermission => "database_permission", + IdentityRebindDetail.DatabaseTimeout => "database_timeout", + IdentityRebindDetail.AuthorityState => "authority_state", + IdentityRebindDetail.RealmDiscovery => "realm_discovery", + IdentityRebindDetail.RealmKeySet => "realm_key_set", + IdentityRebindDetail.RealmToken => "realm_token", + IdentityRebindDetail.RealmUserCount => "realm_user_count", + IdentityRebindDetail.RealmUserList => "realm_user_list", + _ => string.Empty, + }; +} + +/// The end of one run and what it counted. +/// How the run ended. +/// The class of a refusal, or . +/// The continuity counts, when the proof ran. +/// How many sessions of a runtime role the freeze check saw, when it ran. +/// The check inside the class that failed, when the class has more than one. +public sealed record IdentityRebindOutcome( + IdentityRebindResult Result, + IdentityRebindRefusal Refusal = IdentityRebindRefusal.None, + IdentityRebindContinuityResult? Continuity = null, + int? LiveSessions = null, + IdentityRebindDetail Detail = IdentityRebindDetail.None); + +/// Counters of the rebind: runs by outcome, and the continuity proof's counts by class (ADR-0104 § 11). +/// +/// The labels are closed sets. The offline tool is a short-lived process, so it prints the same classes in its +/// outcome line and exports these only when an OTLP endpoint is configured for it. +/// +public static class IdentityRebindMetrics +{ + /// The meter name. + public const string MeterName = "learnstack.identity.rebind"; + + /// Runs by outcome: applied, already_applied, unknown, or a refusal class. + public const string RunCounterName = "learnstack_identity_rebind_runs_total"; + + /// Continuity counts by class. + public const string ContinuityCounterName = "learnstack_identity_rebind_continuity_total"; + + private static readonly Meter Meter = new(MeterName); + + private static readonly Counter Runs = + Meter.CreateCounter(RunCounterName, description: "Controlled issuer rebind runs by outcome."); + + private static readonly Counter Continuity = + Meter.CreateCounter(ContinuityCounterName, description: "Continuity proof counts by class."); + + /// + /// Records a run the tool ended before the database half began, under the label its printed line carries. The + /// labels are the closed set the runbook lists: the operator token's refusal causes and the grant gate's. + /// + public static void RecordToolRefusal(string label) + { + ArgumentException.ThrowIfNullOrWhiteSpace(label); + Runs.Add(1, new KeyValuePair("outcome", label)); + } + + /// Records one finished run. + public static void Record(IdentityRebindOutcome outcome) + { + ArgumentNullException.ThrowIfNull(outcome); + Runs.Add(1, new KeyValuePair("outcome", Label(outcome))); + if (outcome.Continuity is { } counts) + { + Add("active", counts.StoredActive); + Add("closing", counts.StoredClosing); + Add("closed", counts.StoredClosed); + Add("reported", counts.Enumerated); + Add("unkeyable", counts.Unkeyable); + Add("missing_active", counts.MissingActive); + Add("reappearing_closed", counts.ReappearingClosed); + Add("unbootstrapped", counts.Unbootstrapped); + } + } + + /// The closed outcome label of a run. + public static string Label(IdentityRebindOutcome outcome) => outcome.Result switch + { + IdentityRebindResult.Applied => "applied", + IdentityRebindResult.AlreadyApplied => "already_applied", + IdentityRebindResult.Unknown => "unknown", + _ => outcome.Refusal switch + { + IdentityRebindRefusal.NotAdmitted => "refused_not_admitted", + IdentityRebindRefusal.RoleInvalid => "refused_role_invalid", + IdentityRebindRefusal.RebindInProgress => "refused_rebind_in_progress", + IdentityRebindRefusal.DatabaseUnavailable => "refused_database_unavailable", + IdentityRebindRefusal.AuthorityMismatch => "refused_authority_mismatch", + IdentityRebindRefusal.LiveSessions => "refused_live_sessions", + IdentityRebindRefusal.NewRealmUnavailable => "refused_new_realm_unavailable", + IdentityRebindRefusal.NewRealmIssuerMismatch => "refused_new_realm_issuer_mismatch", + IdentityRebindRefusal.NewRealmIncomplete => "refused_new_realm_incomplete", + IdentityRebindRefusal.ContinuityBroken => "refused_continuity_broken", + IdentityRebindRefusal.AuditFailed => "refused_audit_failed", + IdentityRebindRefusal.CommitFailed => "refused_commit_failed", + IdentityRebindRefusal.Cancelled => "refused_cancelled", + _ => "refused", + }, + }; + + private static void Add(string name, int count) + { + if (count > 0) + { + Continuity.Add(count, new KeyValuePair("class", name)); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs new file mode 100644 index 000000000..9d55c16e4 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs @@ -0,0 +1,475 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using LearnStack.Infrastructure.Messaging; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Infrastructure.Federation; + +/// +/// The confined owner of the operator's federation report, remove and disable (ADR-0099 Amendment 10 and 11). It holds +/// the platform scope and the operator port and nothing of the tenant runner, so the rule that the tenant's provider +/// port is held only by the runner stands. +/// +/// +/// +/// The realm is read first, the rows second. A tenant writes its connection row before it creates the broker, so +/// a broker the realm listed already had a committed row when the row query runs; reading the rows first would call +/// a broker created in between an orphan. The scope is entered before either read, so the admission is spent fresh and +/// the entry row records the attempt even when the provider is down. +/// +/// +/// An act has two rows. The intent row is written at the scope handle's checkpoint and committed before the +/// provider call; the completion row records how the call ended and commits at the end. A crash between them leaves the +/// intent alone, which the next report resolves by showing the broker present or gone. A no-op (an absent broker on a +/// remove, a disabled broker on a disable) and a refusal before the intent write no tenant row: the entry row records +/// the call, and no tenant is known from nothing. +/// +/// +/// The completion is settled on its own budget. Once a change may have been sent, a caller that leaves or a +/// completion that cannot be written must not turn into "nothing changed": the completion row is written on a bounded +/// token detached from the request, as the tenant runner completes on one, and a completion that still fails after a change +/// answers . The intent row then stands alone, which the next report resolves. +/// +/// +/// The rows name the marker's tenant, never the platform sentinel, even when no tenants row exists for it. +/// They carry closed tokens only: no display name, issuer, configuration or secret, and no ticket, because a tenant can +/// read them. +/// +/// +public sealed class FederationBrokerOperations( + IPlatformAdminScope scope, IFederationOperator provider, TimeSpan? completionBudget = null) : IFederationBrokerOperations +{ + private const int MaximumLimit = CursorPagination.MaxLimit; + private const string EntityType = "FederationConnection"; + private const string RowQuery = "SELECT id, tenant_id, state, deleted_at IS NOT NULL FROM federation_connections WHERE id = ANY(@ids)"; + private static readonly TimeSpan ReportDeadline = TimeSpan.FromSeconds(10); + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + /// The completion's own budget, detached from the request; a test passes a shorter or longer one. + private readonly TimeSpan _completionBudget = completionBudget ?? TimeSpan.FromSeconds(3); + + /// + public Task ReportAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => + GuardAsync(_ => ReportCoreAsync(admission, cursor, limit, cancellationToken), cancellationToken); + + /// + public Task RemoveAsync( + PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + GuardAsync(progress => RemoveCoreAsync(admission, brokerAlias, progress, cancellationToken), cancellationToken); + + /// + public Task DisableAsync( + PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + GuardAsync(progress => DisableCoreAsync(admission, brokerAlias, progress, cancellationToken), cancellationToken); + + /// Whether a provider change may have landed, which decides what a failure further on may claim. + private sealed class ActProgress + { + internal bool ChangeMayHaveLanded { get; set; } + } + + /// + /// A failure after a change that landed or may have is the unknown outcome, with its cause kept for the route's log and + /// never "nothing changed"; before any change, a transient database fault is the unavailable owner, and never a raw 500. + /// What this guard does not catch (a refused credential, a missing grant before any change, a programmer error) is the + /// defect it is. + /// + private static async Task GuardAsync(Func> operation, CancellationToken cancellationToken) + { + var progress = new ActProgress(); + try + { + return await operation(progress); + } + catch (Exception failure) when (progress.ChangeMayHaveLanded && !IsFatal(failure)) + { + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: failure); + } + catch (Exception failure) when (!progress.ChangeMayHaveLanded + && OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) + { + throw new OperatorRecoveryUnavailableException(cause: failure); + } + } + + private static bool IsFatal(Exception failure) => failure is OutOfMemoryException or AccessViolationException or StackOverflowException; + + private async Task ReportCoreAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken) + { + RequireOperation(admission, PlatformOperations.FederationReport); + var offset = 0; + if (cursor is not null && !TryDecode(cursor, out offset)) + { + return FederationReportResult.Of(FederationReportOutcome.InvalidCursor); + } + + var size = Math.Clamp(limit, 1, MaximumLimit); + await using var handle = await scope.EnterAsync(admission, cancellationToken); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(ReportDeadline); + + // 1. The realm, before any row. + FederationBrokerPage page; + try + { + page = await provider.ListAsync(offset, size, deadline.Token); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return FederationReportResult.Of(FederationReportOutcome.Unavailable); + } + + if (page.Status != FederationOperatorStatus.Ok) + { + return FederationReportResult.Of(FederationReportOutcome.Unavailable); + } + + // 2. The rows, strictly later, by primary key and through the four granted columns only. + var rows = await ReadRowsAsync(handle, page.Owned.Select(facts => facts.Owner.ConnectionId).Distinct().ToArray(), cancellationToken); + var ignored = page.Ignored; + var candidates = new List<(FederationBrokerFacts Facts, Row? Row)>(); + foreach (var facts in page.Owned) + { + rows.TryGetValue(facts.Owner.ConnectionId, out var row); + if (row is not null && row.TenantId != facts.Owner.TenantId.Value) + { + // The marker and the row disagree about whose it is: never reported, never touched. + ignored++; + continue; + } + + candidates.Add((facts, row)); + } + + // 3. The mappers of what looks healthy, bounded, because an extra mapper is drift only a mapper read shows. + var mappers = await CountMappersAsync( + candidates.Where(item => IsLive(item.Row) && item.Facts is { Readable: true, Conforms: true }) + .Select(item => item.Facts.Owner).ToList(), + deadline.Token, cancellationToken); + + var items = new List(); + var unread = 0; + foreach (var (facts, row) in candidates) + { + mappers.TryGetValue(facts.Owner.Alias, out var count); + if (count is null && IsLive(row) && facts is { Readable: true, Conforms: true }) + { + // A mapper is drift only a mapper read shows: this broker is unknown, not clean, and the page says so. + unread++; + } + + var classes = ClassesOf(facts, row, count ?? 0); + if (classes.Count == 0) + { + continue; + } + + items.Add(new FederationBrokerReportItem( + facts.Owner.Alias, facts.Owner.TenantId.Value, facts.Owner.ConnectionId, classes, RowState(row), + facts.Protocol is { } protocol ? protocol.ToString().ToLowerInvariant() : null, facts.Enabled, count)); + } + + var next = page.Scanned == size ? Encode(offset + page.Scanned) : null; + return new FederationReportResult(FederationReportOutcome.Ok, items, next, page.Scanned, ignored, unread); + } + + private async Task RemoveCoreAsync( + PlatformAdmission admission, string brokerAlias, ActProgress progress, CancellationToken cancellationToken) + { + RequireOperation(admission, PlatformOperations.FederationRemove); + await using var handle = await scope.EnterAsync(admission, cancellationToken); + var inspection = await provider.InspectAsync(brokerAlias, cancellationToken); + switch (inspection.Status) + { + case FederationInspectionStatus.Unavailable: + return new FederationActResult(FederationActOutcome.Unavailable); + case FederationInspectionStatus.Absent: + // Deleting an absent broker is applied, and no tenant is known from nothing: no tenant row. + return new FederationActResult(FederationActOutcome.AlreadyApplied); + case FederationInspectionStatus.NotOwned: + return new FederationActResult(FederationActOutcome.NotOwned); + } + + var facts = inspection.Facts!; + var owner = facts.Owner; + var row = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); + if (row is not null && row.TenantId != owner.TenantId.Value) + { + return new FederationActResult(FederationActOutcome.NotOwned); + } + + if (RefusesRemoval(facts, row)) + { + // Amendment 10 item 3 and Amendment 12 item 1: a live row refuses a broker that reads or is still enabled. + return Known(FederationActOutcome.LiveConnection, owner); + } + + var classes = ClassesOf(facts, row, inspection.MapperCount); + await handle.WriteIntentAsync(Result(owner, classes, row, after: null), cancellationToken); + + // The row is read again immediately before the delete. A tombstone is terminal and a connection id is fresh, so + // this protects against a stale reading and not against a race, and is cheap enough to keep. + var again = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); + FederationActOutcome outcome; + string? cause = null; + Exception? failure = null; + if (RefusesRemoval(facts, again)) + { + outcome = FederationActOutcome.LiveConnection; + cause = "live_connection"; + } + else + { + // A live row is let through only for a broker that does not read and is disabled, which the adapter proves + // again at the delete. + (outcome, failure) = await ChangeAsync( + token => provider.RemoveAsync(owner, requireDisabledUnreadable: IsLive(again), token), progress, cancellationToken); + } + + (outcome, failure) = await CompleteAsync(handle, owner, classes, row, outcome, cause, failure, progress); + return Known(outcome, owner, failure); + } + + private async Task DisableCoreAsync( + PlatformAdmission admission, string brokerAlias, ActProgress progress, CancellationToken cancellationToken) + { + RequireOperation(admission, PlatformOperations.FederationDisable); + await using var handle = await scope.EnterAsync(admission, cancellationToken); + var inspection = await provider.InspectAsync(brokerAlias, cancellationToken); + switch (inspection.Status) + { + case FederationInspectionStatus.Unavailable: + return new FederationActResult(FederationActOutcome.Unavailable); + case FederationInspectionStatus.Absent: + return new FederationActResult(FederationActOutcome.NotFound); + case FederationInspectionStatus.NotOwned: + return new FederationActResult(FederationActOutcome.NotOwned); + } + + var facts = inspection.Facts!; + var owner = facts.Owner; + var row = (await ReadRowsAsync(handle, [owner.ConnectionId], cancellationToken)).GetValueOrDefault(owner.ConnectionId); + if (row is not null && row.TenantId != owner.TenantId.Value) + { + return new FederationActResult(FederationActOutcome.NotOwned); + } + + var classes = ClassesOf(facts, row, inspection.MapperCount); + if (classes.Count == 0) + { + // Nothing about a healthy broker with a live row needs an operator. + return Known(FederationActOutcome.NotApplicable, owner); + } + + if (!facts.Enabled) + { + return Known(FederationActOutcome.AlreadyApplied, owner); + } + + await handle.WriteIntentAsync(Result(owner, classes, row, after: null), cancellationToken); + var (outcome, failure) = await ChangeAsync(token => provider.DisableAsync(owner, token), progress, cancellationToken); + (outcome, failure) = await CompleteAsync(handle, owner, classes, row, outcome, cause: null, failure, progress); + return Known(outcome, owner, failure); + } + + /// + /// The provider's change. A caller that leaves, and any other failure after the change may have been sent, is an + /// unknown outcome with its cause kept: the adapter rethrows the caller's cancellation without saying which side of the + /// send it fell on, and an unexpected failure says nothing about whether the provider took the change. Either is + /// recorded in the completion row, never skipped. + /// + private static async Task<(FederationActOutcome Outcome, Exception? Failure)> ChangeAsync( + Func> change, ActProgress progress, CancellationToken cancellationToken) + { + FederationActOutcome outcome; + Exception? failure = null; + try + { + outcome = Map(await change(cancellationToken)); + } + catch (Exception caught) when (!IsFatal(caught)) + { + outcome = FederationActOutcome.Uncertain; + failure = caught; + } + + progress.ChangeMayHaveLanded = outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain; + return (outcome, failure); + } + + /// + /// Writes and commits the completion row on a bounded token detached from the request, and returns the outcome the + /// caller is to answer with the failure behind it. A completion that cannot be written is the audit failure it is when + /// nothing changed; after a change that landed or may have, the intent row stands alone and the answer is the unknown + /// outcome with the completion's failure as its cause, never "nothing changed, repeat it" and never a silent swallow. + /// + private async Task<(FederationActOutcome Outcome, Exception? Failure)> CompleteAsync( + IPlatformAdminScopeHandle handle, FederationBrokerOwner owner, IReadOnlyList classes, Row? row, + FederationActOutcome outcome, string? cause, Exception? failure, ActProgress progress) + { + var token = OutcomeToken(outcome); + // The account review is owed for any change that may have landed: the provider removes federated links with a + // broker, and nothing here reads them (ADR-0099 Amendment 10 item 7). A disable owes it too (Amendment 12 item 6). + var owed = outcome is FederationActOutcome.Applied or FederationActOutcome.Uncertain; + var after = JsonSerializer.Serialize(new AfterState(token, cause, owed), Json); + using var budget = new CancellationTokenSource(_completionBudget); + try + { + await handle.WriteResultAsync(Result(owner, classes, row, after), budget.Token); + await handle.CommitAsync(budget.Token); + return (outcome, failure); + } + catch (Exception lost) when (progress.ChangeMayHaveLanded && !IsFatal(lost)) + { + return (FederationActOutcome.Uncertain, lost); + } + } + + private static PlatformResult Result(FederationBrokerOwner owner, IReadOnlyList classes, Row? row, string? after) => new( + owner.TenantId, EntityType, owner.ConnectionId.ToString("D", CultureInfo.InvariantCulture), + JsonSerializer.Serialize(new BeforeState(classes, RowState(row)), Json), after); + + private static FederationActResult Known(FederationActOutcome outcome, FederationBrokerOwner owner, Exception? failure = null) => + new(outcome, owner.TenantId.Value, owner.ConnectionId, failure); + + private static FederationActOutcome Map(FederationOperatorOutcome outcome) => outcome switch + { + FederationOperatorOutcome.Applied => FederationActOutcome.Applied, + FederationOperatorOutcome.AlreadyApplied => FederationActOutcome.AlreadyApplied, + FederationOperatorOutcome.Refused => FederationActOutcome.Refused, + FederationOperatorOutcome.NotOwned => FederationActOutcome.NotOwned, + FederationOperatorOutcome.Unavailable => FederationActOutcome.Unavailable, + _ => FederationActOutcome.Uncertain, + }; + + private static string OutcomeToken(FederationActOutcome outcome) => outcome switch + { + FederationActOutcome.Applied => "applied", + FederationActOutcome.AlreadyApplied => "already_applied", + FederationActOutcome.NotOwned => "not_owned", + FederationActOutcome.LiveConnection => "refused", + FederationActOutcome.Refused => "refused", + FederationActOutcome.Unavailable => "unavailable", + _ => "uncertain", + }; + + /// The classes of one broker: orphan by row, then unreadable, then nonconforming by profile or mapper. + private static List ClassesOf(FederationBrokerFacts facts, Row? row, int mappers) + { + var classes = new List(3); + if (!IsLive(row)) + { + classes.Add("orphan"); + } + + if (!facts.Readable) + { + classes.Add("unreadable_owned"); + } + else if (!facts.Conforms || mappers > 0) + { + classes.Add("nonconforming"); + } + + return classes; + } + + /// + /// A live connection row refuses the removal of a broker that reads: the tenant's own Delete retires that pair. A broker + /// that does not read and is disabled is the exception (ADR-0099 Amendment 12 item 1 and Amendment 13 item 1), because + /// the tenant's Delete treats it as foreign and fails (Amendment 5 item 5), so nothing else could ever remove it. An + /// unreadable broker that is still enabled is refused: "unreadable" is a shape check, and the provider may still be + /// serving it, so the operator disables it first, which is reversible, and removes it after. + /// + private static bool RefusesRemoval(FederationBrokerFacts facts, Row? row) => IsLive(row) && (facts.Readable || facts.Enabled); + + private static bool IsLive(Row? row) => row is { Deleted: false } && !string.Equals(row.State, "Deleted", StringComparison.Ordinal); + + private static string RowState(Row? row) => row is null ? "absent" : IsLive(row) ? row.State : "deleted"; + + private static async Task> ReadRowsAsync( + IPlatformAdminScopeHandle handle, Guid[] ids, CancellationToken cancellationToken) + { + if (ids.Length == 0) + { + return []; + } + + var rows = await handle.QueryAsync( + RowQuery, [new PlatformSqlParameter("ids", ids)], + reader => new Row(reader.GetGuid(0), reader.GetGuid(1), reader.GetString(2), reader.GetBoolean(3)), cancellationToken); + return rows.ToDictionary(row => row.Id); + } + + /// + /// The mapper count of each owner, one after another, until the page's time runs out: the remainder is unknown, which + /// the report counts as and never as zero. A module runs one operation at a time (ADR-0040), and the provider's + /// own bulkhead would refuse a wider fan-out. + /// + private async Task> CountMappersAsync( + IReadOnlyList owners, CancellationToken deadline, CancellationToken caller) + { + var counts = new Dictionary(StringComparer.Ordinal); + foreach (var owner in owners) + { + try + { + counts[owner.Alias] = await provider.CountMappersAsync(owner, deadline); + } + catch (OperationCanceledException) when (!caller.IsCancellationRequested) + { + break; + } + } + + return counts; + } + + private static void RequireOperation(PlatformAdmission admission, PlatformOperation expected) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, expected)) + { + throw new ArgumentException("The admission is not for this federation operation.", nameof(admission)); + } + } + + private static string Encode(int offset) => + Convert.ToBase64String(Encoding.UTF8.GetBytes("v1~federation~" + offset.ToString(CultureInfo.InvariantCulture))) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static bool TryDecode(string cursor, out int offset) + { + offset = 0; + if (cursor.Length is 0 or > 64) + { + return false; + } + + try + { + var padded = cursor.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight((padded.Length + 3) / 4 * 4, '='); + var parts = Encoding.UTF8.GetString(Convert.FromBase64String(padded)).Split('~'); + return parts is ["v1", "federation", var number] + && int.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out offset) + && string.Equals(Encode(offset), cursor, StringComparison.Ordinal); + } + catch (FormatException) + { + return false; + } + } + + private sealed record Row(Guid Id, Guid TenantId, string State, bool Deleted); + + private sealed record BeforeState(IReadOnlyList Classes, string RowState); + + private sealed record AfterState(string Outcome, string? Cause, bool AccountReviewOwed); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs index 6cfb96e7d..feafd0261 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs @@ -2,6 +2,7 @@ using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Identity.Application.Abstractions; using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Errors; using Microsoft.EntityFrameworkCore; @@ -276,6 +277,24 @@ public Task LockAsync(MembershipId membershipId, CancellationToken cancellationT public Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default) => ContextualIdentityStorageControl.ReadAsync(() => db.Memberships.AnyAsync(cancellationToken)); + + public Task HasActiveTenantAdministratorAsync(CancellationToken cancellationToken = default) => + ContextualIdentityStorageControl.ReadAsync(async () => + { + // The administrator Roles first, judged by the domain's own definition (kernel grants + // included), then whether an Active tenant-wide Membership holds one of them. + var candidates = await db.Roles.AsNoTracking().Include(role => role.Grants) + .Where(role => role.BuiltInKey == BuiltInRoleKey.TenantAdmin && role.DeletedAt == null) + .ToListAsync(cancellationToken); + var administratorRoles = candidates.Where(role => role.IsTenantAdministrator).Select(role => role.Id).ToList(); + return administratorRoles.Count != 0 + && await db.Memberships.AnyAsync( + membership => membership.Status == MembershipStatus.Active && membership.DeletedAt == null + && membership.OrganizationId == null + && membership.RoleAssignments.Any(assignment => administratorRoles.Contains(assignment.RoleId)), + cancellationToken); + }); + public Task ValidateGraphAsync(CancellationToken cancellationToken = default) => control.ValidateGraphAsync(cancellationToken); public Task AddAsync(Membership aggregate, CancellationToken cancellationToken = default) { diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs new file mode 100644 index 000000000..f94983e3e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/FederationOperatorProjectionDdl.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The one grant the operator's federation report and sweep read through (ADR-0099 Amendment 10 item 5). +/// +/// +/// +/// learnstack_platform receives SELECT of four columns of federation_connections: the +/// connection's id, its tenant, its lifecycle state and its tombstone instant. That is everything the question +/// "does this broker still have a live row" needs, and nothing a tenant authored: no alias, display name, issuer, +/// provider configuration or secret reference is granted, so a statement that names one is refused by PostgreSQL +/// whatever the application does. The platform role is BYPASSRLS, so the grant, and not a policy, is the +/// bound; it holds no write privilege, and the table's guard trigger already admits only the application role to +/// write it. +/// +/// +/// The grant lives in the Identity chain because the table is created there, after the Platform chain has run. +/// +/// +internal static class FederationOperatorProjectionDdl +{ + internal static void Add(MigrationBuilder migration) => migration.Sql(""" + GRANT SELECT (id, tenant_id, state, deleted_at) ON public.federation_connections TO learnstack_platform; + """); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs new file mode 100644 index 000000000..08d70d60e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityAuthorityRebindDdl.cs @@ -0,0 +1,69 @@ +using LearnStack.Infrastructure.Audit; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The storage the offline issuer-rebind tool needs and nothing else (ADR-0104 § 2, § 7, § 8). +/// +/// +/// +/// learnstack_identity_rebind is a login role without BYPASSRLS that no runtime host +/// holds. It reads identity_authority, may change its issuer column and no other, reads +/// the four users columns the continuity proof compares, and inserts audit_log rows that +/// one policy arm limits to the platform sentinel, the identity module and the two rebind operations; that +/// grant and arm are installed by . +/// +/// +/// One permissive policy per command: the read policy gains the role, a third policy admits its +/// update, the users and audit_log isolation policies each gain one arm, and a second +/// permissive policy is never added. The trigger refuses any change of id or +/// authority_id for every role, so the stable key the subject keys hash cannot move; the issuer +/// grammar stays in the tool and in qualification, not in SQL. +/// +/// +internal static class IdentityAuthorityRebindDdl +{ + internal static void Add(MigrationBuilder migration) + { + migration.Sql(""" + DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'learnstack_identity_rebind') THEN + RAISE EXCEPTION 'The issuer-rebind storage requires the learnstack_identity_rebind role; apply infra/compose/postgres-init/02-create-roles.sql with LEARNSTACK_IDENTITY_REBIND_PW set, then migrate again.' USING ERRCODE='23514'; + END IF; + END $$; + + GRANT SELECT ON public.identity_authority TO learnstack_identity_rebind; + GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind; + GRANT SELECT (authority_id, subject_key, provider_subject, status) ON public.users TO learnstack_identity_rebind; + + ALTER POLICY identity_authority_read ON public.identity_authority + USING (current_user IN ('learnstack_app','learnstack_migration','learnstack_identity_rebind')); + CREATE POLICY identity_authority_rebind ON public.identity_authority FOR UPDATE + USING (current_user='learnstack_identity_rebind' AND id=1) + WITH CHECK (current_user='learnstack_identity_rebind' AND id=1); + + ALTER POLICY users_isolation ON public.users + USING ((current_user='learnstack_app' + AND authority_id::text=NULLIF(current_setting('app.identity_authority_id',true),'') + AND encode(subject_key,'hex')=NULLIF(current_setting('app.identity_subject_key',true),'')) + OR current_user='learnstack_migration' + OR current_user='learnstack_identity_rebind'); + + CREATE FUNCTION public.fn_identity_authority_immutable_key() RETURNS trigger + LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + BEGIN + IF NEW.id IS DISTINCT FROM OLD.id OR NEW.authority_id IS DISTINCT FROM OLD.authority_id THEN + RAISE EXCEPTION 'The identity authority key cannot change.' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_authority_immutable_key() FROM PUBLIC; + CREATE TRIGGER tg_identity_authority_immutable_key BEFORE UPDATE ON public.identity_authority + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_authority_immutable_key(); + """); + + // The audit_log grant and the one policy arm belong to the central audit installer: no module names the table. + IdentityRebindAuditInstaller.Install(migration); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs new file mode 100644 index 000000000..5b5ca5c1e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261119140000_add_operator_subject_resolver.cs @@ -0,0 +1,17 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +[DbContext(typeof(IdentityDbContext))] +[Migration("20261119140000_add_operator_subject_resolver")] +public sealed class add_operator_subject_resolver : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => OperatorSubjectResolverDdl.Add(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0102): like every recent Identity head, the resolver is retired by a reviewed forward + // migration, so a reversal cannot silently remove the confined lookup an operator act depends on. + throw new NotSupportedException("Operator subject resolution requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs new file mode 100644 index 000000000..dd093e2ce --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120090000_add_identity_authority_rebind.cs @@ -0,0 +1,17 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +[DbContext(typeof(IdentityDbContext))] +[Migration("20261120090000_add_identity_authority_rebind")] +public sealed class add_identity_authority_rebind : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => IdentityAuthorityRebindDdl.Add(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0104): like every recent Identity head, the rebind grants and the key trigger are + // retired by a reviewed forward migration, so a reversal cannot silently leave an issuer writable. + throw new NotSupportedException("The issuer-rebind storage requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs new file mode 100644 index 000000000..5d0fa2a68 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261120160000_grant_platform_federation_projection.cs @@ -0,0 +1,17 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +[DbContext(typeof(IdentityDbContext))] +[Migration("20261120160000_grant_platform_federation_projection")] +public sealed class grant_platform_federation_projection : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => FederationOperatorProjectionDdl.Add(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0099 Amendment 11): a grant a reviewed forward migration retires, so a reversal cannot + // silently leave the operator's report reading a table it no longer has the right to. + throw new NotSupportedException("The platform federation projection grant requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs new file mode 100644 index 000000000..ca8137e04 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs @@ -0,0 +1,46 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Microsoft.EntityFrameworkCore; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// Resolves an operator-named provider subject to its Active User through the confined definer +/// (ADR-0102 § 5), on the tenant transaction the act already owns. +/// +/// +/// The stored authority comes from the deployment's qualified registration and the key is derived +/// here, so the request supplies the provider subject and nothing else. A subject the key derivation +/// refuses, an unknown subject and a non-Active user all answer null. +/// +public sealed class OperatorSubjectResolver(IdentityDbContext db, IdentityAuthorityQualification qualification) + : IOperatorSubjectResolver +{ + /// + public async Task ResolveActiveUserAsync(string providerSubject, CancellationToken cancellationToken = default) + { + // An authority that is not qualified is a dependency that is not there, the same answer the sibling stores + // give a provider that is unreachable, and not an unclassified exception. + var registration = qualification.Current ?? throw new IdentityStorageProviderException(); + IdentitySubjectKey key; + try + { + key = IdentitySubjectKey.Compute(registration.AuthorityId, providerSubject); + } + catch (ArgumentException) + { + return null; + } + + var authority = registration.AuthorityId.Value; + var bytes = key.ToByteArray(); + // A provider failure crosses the same boundary the sibling stores use, so it answers in the Identity + // vocabulary and not as an unclassified exception. + var found = await ContextualIdentityStorageControl.ReadAsync(() => db.Database + .SqlQuery($"SELECT public.fn_identity_operator_resolve_user({authority}, {bytes}) AS \"Value\"") + .SingleAsync(cancellationToken)); + return found is { } id ? UserId.From(id) : null; + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs new file mode 100644 index 000000000..50d52f332 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// The confined definer that resolves an operator-named provider subject to an Active User inside a +/// tenant transaction (ADR-0102 § 5). +/// +/// +/// users is under forced row security keyed by identity settings that every tenant announcement +/// blanks, so a tenant transaction cannot read it. This function runs as the migration owner, whose +/// policy branch sees the table, and takes the stored authority and the derived subject key as +/// arguments. It refuses any session but the application role, any transaction that is not an ordinary +/// read-write tenant one, any authority other than the stored one, and any key that is not 32 bytes; +/// it answers the id of an Active, undeleted user or null. It reads nothing else and writes nothing. +/// +internal static class OperatorSubjectResolverDdl +{ + internal static void Add(MigrationBuilder migration) => migration.Sql(""" + CREATE FUNCTION public.fn_identity_operator_resolve_user(selected_authority uuid, selected_subject_key bytea) + RETURNS uuid LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path=pg_catalog AS $resolve$ + DECLARE resolved_user uuid; + BEGIN + IF session_user <> 'learnstack_app' + OR NULLIF(current_setting('app.tenant_id',true),'') IS NULL + OR current_setting('transaction_read_only') <> 'off' + OR current_setting('transaction_isolation') <> 'read committed' + OR selected_authority IS NULL OR selected_subject_key IS NULL OR octet_length(selected_subject_key) <> 32 + OR NOT EXISTS (SELECT FROM public.identity_authority a WHERE a.id=1 AND a.authority_id=selected_authority) + THEN RAISE EXCEPTION 'Operator subject resolution refused.' USING ERRCODE='23514'; END IF; + SELECT u.id INTO resolved_user FROM public.users u + WHERE u.authority_id=selected_authority AND u.subject_key=selected_subject_key + AND u.status='Active' AND u.deleted_at IS NULL; + RETURN resolved_user; + END $resolve$; + REVOKE ALL ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_operator_resolve_user(uuid,bytea) TO learnstack_app; + """); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs new file mode 100644 index 000000000..2e6d72a8f --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/Tenant/OperatorTenantCommands.cs @@ -0,0 +1,36 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Tenancy.Application.Contracts.Tenant; + +/// +/// Provisions a Tenant and its default Organization for an admitted operator (ADR-0102 § 2, § 3). +/// +/// +/// The operator supplies the tenant's id and slug, and the act is idempotent on that pair: the same +/// pair finds the tenant already there, a known slug under another id refuses. Reachable only through +/// the operator source; the seed's own is a different request +/// with a different policy, so neither authority can perform the other's act. +/// +public sealed record OperatorProvisionTenantCommand( + TenantId TenantId, + string Slug, + string DisplayName, + OrganizationId DefaultOrganizationId, + string DefaultOrganizationSlug, + string DefaultOrganizationDisplayName) + : IRequest>; + +/// +/// Maps a host to the operator-named Tenant through the host-mapping store (ADR-0102 § 2, § 4). +/// +/// +/// The tenant comes from the context the executor installed for the act, not from this body. The +/// operator asserts ownership of the host; LearnStack verifies no DNS. +/// +public sealed record OperatorMapHostCommand( + string Host, + OrganizationId? OrganizationId = null, + bool IsActive = true, + bool IsPubliclyLive = true) : IRequest>; diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs index 05c310dac..69d989413 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs @@ -93,6 +93,16 @@ public void Describe(IAuditCatalogBuilder builder) .MustAudit( "tenancy.organization.create", OperationType.Create, typeof(Organization)) + // The operator's production provisioning writes the same two rows under the same two slugs + // (ADR-0102 § 9); the act differs in its source and in the operator it records, not in what + // happened, so the matrix keeps one row per operation. + .MustAudit( + "tenancy.tenant.create", OperationType.Create, typeof(Domain.Tenant)) + .MustAudit( + "tenancy.organization.create", OperationType.Create, typeof(Organization)) + .MustAudit( + "tenancy.hostmapping.write", OperationType.Create, typeof(PlatformHostMapping)) + .MustAudit( "tenancy.hostmapping.write", OperationType.Create, typeof(PlatformHostMapping)) .MustAudit( @@ -110,12 +120,38 @@ public void Describe(IAuditCatalogBuilder builder) // to name the same one. .DeclareOffPath( "platform.admin_scope.enter", OperationType.SecurityEvent, OperationClass.Must) + // The killswitch flip is written inside an admitted platform scope on its work + // transaction (ADR-0101 § 13); the scope is a service, so there is no request type. + .DeclareOffPath( + "tenancy.killswitch.toggle", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.outbox.dead_letter", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.delivery.dead_letter", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.job.dead_letter", OperationType.SecurityEvent, OperationClass.Must) + // The three operator recovery operations of ADR-0103: an inspection is audited by the platform scope's + // entry row, whose reason is this slug's, and the two transitions write their own MUST row on the + // outbox-role transaction that makes the change. + .DeclareOffPath( + "platform.delivery.inspect", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.delivery.replay", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.delivery.reset", OperationType.SecurityEvent, OperationClass.Must) + // The three operator federation operations of ADR-0099 Amendment 10. A report is audited by the platform + // scope's entry row; a remove and a disable write an intent row on their attempt slug at the scope + // handle's checkpoint and a completion row on their own slug (Amendment 11), under the real tenant. + .DeclareOffPath( + "platform.federation.report", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.remove", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.remove_attempt", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.disable", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.federation.disable_attempt", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "tenancy.tenant_assertion.reject", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs index 38164652b..8fa391a2c 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Authorization/TenancyOperationPolicySource.cs @@ -55,5 +55,7 @@ public sealed class TenancyOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("tenancy.seed.add_locale", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("tenancy.seed.set_locale", AuthorizationSourceKind.Seed), OperationPolicy.ForTrusted("tenancy.seed.set_branding", AuthorizationSourceKind.Seed), + OperationPolicy.ForTrusted("tenancy.operator.provision_tenant", AuthorizationSourceKind.PlatformOperator), + OperationPolicy.ForTrusted("tenancy.operator.map_host", AuthorizationSourceKind.PlatformOperator), ]; } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs index cc950defb..72c52bfc1 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/MapHostToTenantCommandHandler.cs @@ -3,7 +3,10 @@ using LearnStack.Modules.Tenancy.Application.Seeding; using LearnStack.Modules.Tenancy.Domain; using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; @@ -34,8 +37,10 @@ internal sealed class MapHostToTenantCommandHandler( IOrganizationScopeValidator organizations, IReservedHostRegistry reservedHosts, IHostResolutionInvalidator resolutionCache, - ITenantContext tenantContext, SeedTenantWriteGuard seedGuard) - : IRequestHandler> + ITenantContext tenantContext, SeedTenantWriteGuard seedGuard, OperatorActGuard operatorGuard, + ITenantExistenceReader tenantExistence) + : IRequestHandler>, + IRequestHandler> { public async Task> Handle( MapHostToTenantCommand request, CancellationToken cancellationToken) @@ -56,13 +61,52 @@ public async Task> Handle( var admission = await seedGuard.AdmitAsync(request, cancellationToken); if (admission.IsFailure) return Result.Fail(admission.Error); + return await MapAsync( + request.Host, request.OrganizationId, request.IsActive, request.IsPubliclyLive, + () => seedGuard.VerifyAsync(admission.Value, request, cancellationToken), idempotent: false, cancellationToken); + } + + /// + /// The operator's act: the same mapping through the same store and rules, for the tenant the executor + /// resolved. The operator asserts ownership of the host; the act is idempotent, so a mapping this + /// tenant already holds, identical to the request, is the answer rather than a collision. + /// + public async Task> Handle( + OperatorMapHostCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!tenantContext.IsResolved) + { + return Result.FailFor>(TenantContextMissing); + } + + var admission = await operatorGuard.AdmitAsync( + request, new IdentityMutationLockPlan([], tenantContext.TenantId, IdentityTenantLockMode.Exclusive), cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + + // The tenant must be there: the foreign key would answer 23503, which has no arm in the status + // map and would be a 500 after the transaction opened. Read under the tenant's own lock. + if (!await tenantExistence.ExistsAsync(cancellationToken)) + { + return Result.FailFor>(new Error(new LocalizedMessage("lockey_not_found"))); + } + + return await MapAsync( + request.Host, request.OrganizationId, request.IsActive, request.IsPubliclyLive, + () => Task.FromResult(operatorGuard.RequireCurrent(admission.Value)), idempotent: true, cancellationToken); + } + + private async Task> MapAsync( + string host, OrganizationId? requestedOrganization, bool isActive, bool isPubliclyLive, + Func>> verify, bool idempotent, CancellationToken cancellationToken) + { // The organization must be one of this tenant's. Nothing else checks it before // the insert: the composite foreign key does, but it raises 23503, which has no // arm in HttpStatusMap and therefore answers 500 — after the transaction opened // and the tenant was announced. Reading it here turns a caller's mistake into a // refusal they can act on, and the foreign key stays as the layer that makes the // race impossible rather than merely unlikely. - if (request.OrganizationId is { } organizationId + if (requestedOrganization is { } organizationId && !await organizations.BelongsToTenantAsync( tenantContext.TenantId, organizationId, cancellationToken)) { @@ -77,11 +121,11 @@ [new LocalizedMessage("lockey_organization_not_in_tenant")], } var mapping = PlatformHostMapping.Create( - request.Host, + host, tenantContext.TenantId, - request.OrganizationId, - request.IsActive, - request.IsPubliclyLive); + requestedOrganization, + isActive, + isPubliclyLive); // A host on Tenancy:PlatformHosts is classified before the resolver is called at // all, so a row naming it would be inert — never read, never logged, never @@ -101,8 +145,25 @@ [new LocalizedMessage("lockey_host_reserved")], })); } - if (await seedGuard.VerifyAsync(admission.Value, request, cancellationToken) is { IsFailure: true } changed) + if (await verify() is { IsFailure: true } changed) return Result.Fail(changed.Error); + + if (idempotent && await hosts.FindForUpdateAsync(mapping.Host, cancellationToken) is { } existing) + { + if (existing.OrganizationId != mapping.OrganizationId || existing.IsActive != mapping.IsActive + || existing.IsPubliclyLive != mapping.IsPubliclyLive) + { + return Result.FailFor>(HostTaken()); + } + + // The retry is also the repair for the one thing the first run could not guarantee: a miss + // cached between its invalidation and its commit. Dropping the entry again is idempotent. + await resolutionCache.InvalidateAsync(mapping.Host, cancellationToken); + operatorGuard.MarkReplayed(); + return Result.Ok(new HostMappingDto( + existing.Host, existing.TenantId, existing.OrganizationId, existing.IsActive, existing.IsPubliclyLive)); + } + try { await hosts.AddAsync(mapping, cancellationToken); @@ -114,14 +175,7 @@ [new LocalizedMessage("lockey_host_reserved")], // another tenant, which is why the answer says only that it is taken. Naming // the holder would turn this endpoint into an oracle for which hostnames // belong to which customers. - return Result.FailFor>( - new Error( - new LocalizedMessage("lockey_business_rule_violation"), - new Dictionary>(StringComparer.Ordinal) - { - [nameof(MapHostToTenantCommand.Host)] = - [new LocalizedMessage("lockey_host_taken")], - })); + return Result.FailFor>(HostTaken()); } // The negative cache remembers hosts that resolved to nothing, and this host just @@ -150,6 +204,13 @@ [new LocalizedMessage("lockey_host_taken")], mapping.IsPubliclyLive)); } + private static Error HostTaken() => new( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [nameof(MapHostToTenantCommand.Host)] = [new LocalizedMessage("lockey_host_taken")], + }); + /// /// The pipeline's own answer for an unresolved context, reused rather than restated. /// diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs new file mode 100644 index 000000000..2f8d8e752 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/OperatorTenantCommandValidators.cs @@ -0,0 +1,43 @@ +using FluentValidation; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; + +namespace LearnStack.Modules.Tenancy.Application.Tenant; + +/// +/// The operator's provisioning command refuses exactly what the seed's does: the same shared rules, run +/// on the same fields, so a refusal reaches the operator in the same Problem Details shape and the two +/// cannot drift. +/// +internal sealed class OperatorProvisionTenantCommandValidator : AbstractValidator +{ + private static readonly ProvisionTenantCommandValidator Rules = new(); + + public OperatorProvisionTenantCommandValidator() => + RuleFor(command => command).Custom((command, context) => + { + var result = Rules.Validate(new ProvisionTenantCommand( + command.TenantId, command.Slug, command.DisplayName, command.DefaultOrganizationId, + command.DefaultOrganizationSlug, command.DefaultOrganizationDisplayName)); + foreach (var failure in result.Errors) + { + context.AddFailure(failure); + } + }); +} + +/// The operator's host-mapping command refuses what the seed's does, for the same reasons. +internal sealed class OperatorMapHostCommandValidator : AbstractValidator +{ + private static readonly MapHostToTenantCommandValidator Rules = new(); + + public OperatorMapHostCommandValidator() => + RuleFor(command => command).Custom((command, context) => + { + var result = Rules.Validate(new MapHostToTenantCommand( + command.Host, command.OrganizationId, command.IsActive, command.IsPubliclyLive)); + foreach (var failure in result.Errors) + { + context.AddFailure(failure); + } + }); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs index 41c2daa30..272856990 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Tenant/ProvisionTenantCommandHandler.cs @@ -3,6 +3,8 @@ using LearnStack.Modules.Tenancy.Application.Seeding; using LearnStack.Modules.Tenancy.Domain; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Persistence; @@ -49,13 +51,22 @@ namespace LearnStack.Modules.Tenancy.Application.Tenant; /// Cross_Aggregate_Writes_Are_Confined_To_Tenant_Provisioning asserts. A combined /// port would hide the cross-aggregate write from the rule that exists to count it. /// +/// +/// One class, two commands. The operator's production provisioning +/// (, ADR-0102) is handled here too, so the three-write +/// order, the conflict mapping and the two-port exception exist once; the seed and operator paths +/// differ only in their guard and in what they do when the tenant is already there. The operator act +/// runs on a context the executor resolved for the tenant it names, so the tenant it creates is +/// announced by the ordinary setter and row security admits the insert. +/// /// internal sealed class ProvisionTenantCommandHandler( ITenantWriteStore tenants, IOrganizationWriteStore organizations, IClock clock, - IGuidFactory guids, SeedTenantWriteGuard seedGuard) - : IRequestHandler> + IGuidFactory guids, SeedTenantWriteGuard seedGuard, OperatorActGuard operatorGuard) + : IRequestHandler>, + IRequestHandler> { public async Task> Handle( ProvisionTenantCommand request, CancellationToken cancellationToken) @@ -72,7 +83,7 @@ public async Task> Handle( try { - return await ProvisionAsync(request, actor, admission.Value, cancellationToken); + return await ProvisionAsync(request, actor, () => seedGuard.RequireCurrent(admission.Value, request), cancellationToken); } catch (AggregateConflictException conflict) { @@ -96,11 +107,76 @@ public async Task> Handle( } } + /// + /// The operator's act: the same three writes, once the act is known to be the live admitted one and + /// no tenant already carries the operator's id. + /// + public async Task> Handle( + OperatorProvisionTenantCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + + var admission = await operatorGuard.AdmitAsync( + request, new IdentityMutationLockPlan([], request.TenantId, IdentityTenantLockMode.Exclusive), cancellationToken); + if (admission.IsFailure) return Result.Fail(admission.Error); + + // An exact repeat of the act is the answer, and anything else under the same id is a different + // request: a reply lost on the wire costs nothing, and a retry that changes a value is refused + // rather than silently answered with a record it did not describe. The comparison reads the stored + // Organization, so the answer is what was written and never an echo of the request. A known slug + // under another id is the database's own answer, below, because row security hides another + // tenant's row from this read. + var existing = await tenants.FindAsync(request.TenantId, cancellationToken); + if (existing is not null) + { + var organization = existing.DefaultOrganizationId == request.DefaultOrganizationId + ? await organizations.FindForUpdateAsync(request.DefaultOrganizationId, cancellationToken) + : null; + if (organization is null || existing.Slug != request.Slug || existing.DisplayName != request.DisplayName + || organization.Slug != request.DefaultOrganizationSlug + || organization.DisplayName != request.DefaultOrganizationDisplayName) + { + return Result.FailFor>(TakenFor(nameof(OperatorProvisionTenantCommand.TenantId))); + } + + operatorGuard.MarkReplayed(); + return Result.Ok(new ProvisionedTenantDto(request.TenantId, existing.Slug, organization.Id, organization.Slug)); + } + + try + { + return await ProvisionAsync( + new ProvisionTenantCommand( + request.TenantId, request.Slug, request.DisplayName, request.DefaultOrganizationId, + request.DefaultOrganizationSlug, request.DefaultOrganizationDisplayName), + UserId.SystemActor, + () => operatorGuard.RequireCurrent(admission.Value), + cancellationToken); + } + catch (AggregateConflictException conflict) + { + var (field, reason) = ConflictFor(conflict.ConstraintName); + return Result.FailFor>(new Error( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage(reason)], + })); + } + } + + private static Error TakenFor(string field) => new( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + [field] = [new LocalizedMessage("lockey_identifier_taken")], + }); + /// The three writes, in the one order the schema permits. private async Task> ProvisionAsync( - ProvisionTenantCommand request, UserId actor, SeedTenantWriteAdmission admission, CancellationToken cancellationToken) + ProvisionTenantCommand request, UserId actor, Func> requireCurrent, CancellationToken cancellationToken) { - if (seedGuard.RequireCurrent(admission, request) is { IsFailure: true } changed) + if (requireCurrent() is { IsFailure: true } changed) return Result.Fail(changed.Error); var tenant = Domain.Tenant.Create( request.TenantId, request.Slug, request.DisplayName, clock, actor); @@ -109,7 +185,7 @@ private async Task> ProvisionAsync( // (tenant_id, id), so its row has nothing to reference until this one lands. await tenants.AddAsync(tenant, cancellationToken); - if (seedGuard.RequireCurrent(admission, request) is { IsFailure: true } changedAfterTenant) + if (requireCurrent() is { IsFailure: true } changedAfterTenant) return Result.Fail(changedAfterTenant.Error); var organization = Organization.Create( request.DefaultOrganizationId, @@ -125,7 +201,7 @@ private async Task> ProvisionAsync( // at a row that does not exist when the tenant is inserted, and the foreign key // behind it is MATCH SIMPLE — which skips the check only while the column is // null. Setting it on the insert would defeat that and fail. - if (seedGuard.RequireCurrent(admission, request) is { IsFailure: true } changedAfterOrganization) + if (requireCurrent() is { IsFailure: true } changedAfterOrganization) return Result.Fail(changedAfterOrganization.Error); tenant.AssignDefaultOrganization(request.DefaultOrganizationId, clock, guids, actor); await tenants.UpdateAsync(tenant, cancellationToken); diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs index 135ca0109..05864a882 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs @@ -244,14 +244,10 @@ public static PlatformHostMapping Create( /// § 5). /// /// -/// No writer ships with it, and that is reachability rather than scheduling. Every -/// toggle runs inside EnterPlatformAdminScope(reason) whose registered gate is -/// DenyAllPlatformAdminGate, so nothing can enter that scope until the -/// Platform-scope permission arrives with the registry in -/// Phase 03, -/// which owns the toggle command, its permission and its runbook. A command shipped now -/// would be unreachable code keyed on a permission nothing registers. Every gated read -/// honours a flipped switch the day one exists; what is absent is the flipping. +/// The writer is the killswitch toggle service, which runs inside an admitted platform +/// scope and records a MUST row on the same transaction +/// (ADR-0101 § 13). +/// Every gated read honours a flipped switch. /// /// public sealed class PlatformKillswitch diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs index 44102f675..4a32a8165 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchOverlay.cs @@ -17,12 +17,10 @@ namespace LearnStack.Modules.Tenancy.Infrastructure; /// can see it. /// /// -/// No writer, and that is reachability rather than scheduling. Every toggle runs -/// inside EnterPlatformAdminScope(reason) whose registered gate is -/// DenyAllPlatformAdminGate, so -/// Phase 03 owns -/// the toggle command, its permission and its runbook. This type reads a table nothing in -/// this packet can write, and every gated read honours a flipped switch the day one exists. +/// One writer. The killswitch toggle service flips a key inside an admitted platform scope +/// and drops this cache entry after the commit +/// (ADR-0101 § 13). +/// This type only reads, and every gated read honours a flipped switch. /// /// /// @@ -57,8 +55,8 @@ public sealed class KillswitchOverlay( /// Stated here rather than inherited. Standards 20 fixes this family at the /// 60-second hot-path default, and it IS the staleness bound an operator sees: a /// killswitch flipped during an incident takes at most this long to take effect on an - /// instance whose cache is warm, because Packet 9 ships no writer to invalidate it - /// eagerly. Phase 03's toggle command ships the invalidation with it. + /// instance whose cache is warm, on an instance other than the one that flipped it, because the writer + /// drops only its own process's entry. The flipping instance sees the change at once. /// public static readonly TimeSpan OverlayTtl = TimeSpan.FromSeconds(60); @@ -175,12 +173,12 @@ private static async ValueTask CleanupUnownedAsync(NpgsqlDataReader? reader, Npg private static readonly Action LogReadFailed = LoggerMessage.Define( LogLevel.Error, - new EventId(1, nameof(LogReadFailed)), + new EventId(7107, nameof(LogReadFailed)), "The killswitch overlay could not be read for {Key}; it resolved to the key's default, which is enabled. A cache or database outage must not disable every gated path platform-wide."); private static readonly Action LogUndeclared = LoggerMessage.Define( LogLevel.Error, - new EventId(2, nameof(LogUndeclared)), + new EventId(7108, nameof(LogUndeclared)), "'{Key}' is not in KillswitchKeys, so nothing can flip it and no gated path should be reading it. It resolved to enabled."); } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs new file mode 100644 index 000000000..1a133d46b --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs @@ -0,0 +1,162 @@ +using LearnStack.SharedKernel.Caching; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Modules.Tenancy.Infrastructure; + +/// +/// Writes platform_killswitches inside an admitted platform scope and records the +/// flip as a MUST row on the same transaction (ADR-0101 § 13). +/// +/// +/// +/// Order. Resolve the key from only, enter the scope +/// (which records its entry first), make sure the row exists, lock it and read the before +/// state, update it, write the MUST result row on the work transaction, commit, and only then +/// remove the overlay cache entry. Removing before the commit would let a concurrent load +/// repopulate the stale value; removing after a commit whose outcome is unknown still happens, +/// because the flip may have landed. +/// +/// +/// The first toggle of a key cannot race. SELECT … FOR UPDATE locks nothing when no +/// row exists, so two first toggles would both read the registry default as their before state. +/// The row is therefore created at its default with ON CONFLICT DO NOTHING first; the +/// lock and the read then see one row, and the loser reads the winner's committed state. +/// +/// +/// What it does not do. It cannot reach other instances: the cache is process-local +/// and the overlay refreshes within . The runbook +/// states that lag. Concurrent toggles serialise on the row lock, so each one's before state is +/// the previous one's after state. +/// +/// +public sealed partial class KillswitchToggle( + IPlatformAdminScope scope, + ICacheService cache, + IClock clock, + ILogger logger) : IKillswitchToggle +{ + private const string EnsureRow = + "INSERT INTO platform_killswitches (key, is_enabled, reason, toggled_at, toggled_by) " + + "VALUES (@key, @default, NULL, @at, NULL) ON CONFLICT (key) DO NOTHING"; + + private const string SelectBefore = "SELECT is_enabled FROM platform_killswitches WHERE key = @key FOR UPDATE"; + + // `reason` stays NULL: the application role can read this table, and the ticket never appears in + // a row a tenant's connection can reach (ADR-0101 § 9, as corrected in Amendment 1). The ticket is + // on the sentinel audit rows. + private const string Update = + "UPDATE platform_killswitches SET is_enabled = @enabled, reason = NULL, " + + "toggled_at = @at, toggled_by = NULL WHERE key = @key"; + + /// + public async Task ToggleAsync( + PlatformAdmission admission, KillswitchKey key, bool enabled, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, PlatformOperations.KillswitchToggle)) + { + throw new ArgumentException("The admission is not for a killswitch toggle.", nameof(admission)); + } + + if (!KillswitchKeys.All.TryGetValue(key, out var registryDefault)) + { + return new KillswitchToggleResult(KillswitchToggleOutcome.UnknownKey, key, true, true); + } + + var commitAttempted = false; + try + { + await using var handle = await scope.EnterAsync(admission, cancellationToken); + + await handle.ExecuteAsync( + EnsureRow, + [ + new PlatformSqlParameter("key", key.Value), + new PlatformSqlParameter("default", registryDefault), + new PlatformSqlParameter("at", clock.UtcNow), + ], + cancellationToken); + + var rows = await handle.QueryAsync( + SelectBefore, + [new PlatformSqlParameter("key", key.Value)], + reader => reader.GetBoolean(0), + cancellationToken); + if (rows.Count != 1) + { + throw new InvalidOperationException( + "The killswitch row was not there to lock after it was created; the toggle is abandoned."); + } + + var before = rows[0]; + + // The time is taken under the row lock, so a toggle that waited for another stamps the + // later time and the column agrees with the order of the result rows. + var updated = await handle.ExecuteAsync( + Update, + [ + new PlatformSqlParameter("key", key.Value), + new PlatformSqlParameter("enabled", enabled), + new PlatformSqlParameter("at", clock.UtcNow), + ], + cancellationToken); + if (updated != 1) + { + throw new InvalidOperationException( + "The killswitch update changed no row, so no result row describes it; the toggle is abandoned."); + } + + await handle.WriteResultAsync( + new PlatformResult( + TenantId.PlatformSentinel, + "PlatformKillswitch", + key.Value, + State(before), + State(enabled)), + cancellationToken); + + // Past the point where the caller's abort matters: a cancelled commit leaves its + // outcome unknown, which is the state this order is built to avoid. + commitAttempted = true; + await handle.CommitAsync(CancellationToken.None); + return new KillswitchToggleResult(KillswitchToggleOutcome.Applied, key, before, enabled); + } + finally + { + if (commitAttempted) + { + // Including an indeterminate commit: the flip may have landed, and a stale + // cache entry must not outlive it. A failure here is not the caller's to + // handle; the entry expires within the overlay TTL regardless. + await RemoveCacheAsync(); + } + } + } + + private static string State(bool enabled) => enabled ? "{\"isEnabled\":true}" : "{\"isEnabled\":false}"; + + private async Task RemoveCacheAsync() + { + try + { + await cache.RemoveAsync(CacheKey.ForKillswitchOverlay(), CancellationToken.None); + } + catch (Exception failure) when (failure is not OperationCanceledException) + { + // The cache is an optimisation here; the overlay TTL bounds the lag. The failure + // is still worth a line: a store that cannot remove is a store that serves stale. + LogCacheRemovalFailed(logger, failure); + } + } + + [LoggerMessage( + EventId = 7104, + Level = LogLevel.Warning, + Message = "The killswitch overlay cache entry could not be removed after a toggle; it expires within the overlay TTL.")] + private static partial void LogCacheRemovalFailed(ILogger logger, Exception failure); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs index 33f802357..c9c8e5d41 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs @@ -75,9 +75,8 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) public DbSet PlatformHostMappings => Set(); /// - /// The killswitch overlay. Read-only in this packet — no writer exists, because every - /// toggle runs inside a scope whose registered gate refuses everyone (ADR-0045 - /// Amendment 1 § 4). + /// The killswitch overlay. This context only reads it: the one writer is + /// KillswitchToggle, which runs inside an admitted platform scope (ADR-0101 § 13). /// public DbSet PlatformKillswitches => Set(); diff --git a/backend/tests/.editorconfig b/backend/tests/.editorconfig index b063d0c6b..b1e262767 100644 --- a/backend/tests/.editorconfig +++ b/backend/tests/.editorconfig @@ -22,3 +22,10 @@ dotnet_diagnostic.CA1515.severity = none dotnet_diagnostic.CA1034.severity = none # `HttpClient.GetAsync(string)` overload is fine in test assertions. dotnet_diagnostic.CA2234.severity = none +# A theory whose data xUnit cannot serialize is discovered as one case and executed as +# one result per row under that single id, which the hosted discovery protocol refuses +# (`completed_case_unexpected`, ADR-0063) and no local run shows. Both rules are off by +# default in xunit.analyzers; an Exception, a record or a delegate in `TheoryData<...>` +# is the case. Pass a label or a key and build the object inside the test. +dotnet_diagnostic.xUnit1044.severity = error +dotnet_diagnostic.xUnit1045.severity = error diff --git a/backend/tests/Fixtures/TestPlatformAdmissions.cs b/backend/tests/Fixtures/TestPlatformAdmissions.cs new file mode 100644 index 000000000..7a9b62a9a --- /dev/null +++ b/backend/tests/Fixtures/TestPlatformAdmissions.cs @@ -0,0 +1,43 @@ +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.Tests.Fixtures; + +/// +/// Test-only mints of operator witnesses and admissions. Production owns the closed minter +/// census (the operator scheme and the gate); a test mints through its own nested subclasses, +/// which the census architecture test does not scan. +/// +internal static class TestPlatformAdmissions +{ + internal const string Issuer = "https://operator.test/realms/learnstack-hub"; + + internal static PlatformOperatorWitness Witness(string subject = "operator-1", string? correlationId = "00-test-trace-01") => + WitnessMinter.Create( + Issuer, PlatformOperatorSubject.Digest(Issuer, subject), "mfa", DateTimeOffset.UtcNow, "operator.test", correlationId); + + internal static PlatformAdmission Admission( + PlatformOperation? operation = null, + string? ticket = null, + string subject = "operator-1", + string? correlationId = "00-test-trace-01", + DateTimeOffset? issuedAt = null) => + AdmissionMinter.Create( + Witness(subject, correlationId), + operation ?? PlatformOperations.KillswitchToggle, + ticket, + issuedAt ?? DateTimeOffset.UtcNow); + + private sealed class WitnessMinter : PlatformOperatorWitness.Minter + { + internal static PlatformOperatorWitness Create( + string issuer, string digest, string acr, DateTimeOffset at, string executor, string? correlationId) => + Mint(issuer, digest, acr, at, executor, correlationId); + } + + private sealed class AdmissionMinter : PlatformAdmission.Minter + { + internal static PlatformAdmission Create( + PlatformOperatorWitness witness, PlatformOperation operation, string? ticket, DateTimeOffset issuedAt) => + Mint(witness, operation, ticket, issuedAt); + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs index 19bbb9a1c..9d1e412e8 100644 --- a/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/ApiConventionTests.cs @@ -105,6 +105,6 @@ public void Unversioned_Route_Prefixes_Are_Declared_Once() // its contents keeps a silent widening — someone adding "api" to make // a route work — visible as a failing test rather than as a hole. VersionedRouteConvention.UnversionedRoutePrefixes - .Should().Equal("api/internal"); + .Should().Equal("api/internal", "api/platform"); } } diff --git a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index e98ac41f2..3409a5f05 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -516,15 +516,17 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() public void IAuditStore_Exposes_No_Update_Method() { // The other half of the same claim, and the one a reader checks first. ADR-0033 - // ADR-0046, ADR-0047, ADR-0072 and ADR-0077 authorize ten writes and no update; another method would - // make the port contradict its closed write contract. + // ADR-0046, ADR-0047, ADR-0072, ADR-0077, ADR-0099, ADR-0101, ADR-0103 and ADR-0104 authorize fifteen writes and no update; + // another method would make the port contradict its closed write contract. typeof(IAuditStore).GetMethods() .Select(method => method.Name) .Should().BeEquivalentTo( "WritePendingAsync", "WriteStandaloneAsync", "WriteBestEffortAsync", "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync", "WriteGlobalIdentityPendingAsync", "ReconcileGlobalIdentityAsync", - "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync"); + "WriteAuthorizationPendingAsync", "WriteAuthorizationStandaloneAsync", "WritePlatformOperatorResultAsync", + "WriteIdentityRebindIntentAsync", "WriteIdentityRebindResultAsync", "WriteOperatorRecoveryAsync", + "WritePlatformOperatorIntentAsync"); } /// diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs index 40e5df019..b458c984a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs @@ -1027,7 +1027,12 @@ private static bool IsRouteAttribute(TypeReference attribute, Dictionary MappingSites(IEnumerable modules, Func? predicate = null) => - Types(modules).SelectMany(type => type.Methods).Where(method => method.HasBody) + // The platform operator surface is a separate closed surface with its own scheme and its own exact + // census (PlatformOperatorHttpTests: the endpoint set, methods and policy). It is not part of the + // tenant surface this rule closes, and excluding it is by exact type, so a mapping added anywhere else + // is still an offender. + Types(modules).Where(type => type.FullName != "LearnStack.Api.Platform.PlatformOperatorEndpoints") + .SelectMany(type => type.Methods).Where(method => method.HasBody) .SelectMany(method => method.Body.Instructions.Where(instruction => instruction.Operand is MethodReference target && (predicate ?? IsEndpointMapping)(target) && !EndpointComposition.IsFixedInfrastructureMetadata(method, instruction)) .Select(instruction => new Mapping(method, instruction, (MethodReference)instruction.Operand))); diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs index 032f9de58..7ee15dbda 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs @@ -356,6 +356,23 @@ private static bool IsClosedInvitationForwarding(Method method, Instruction inst "LearnStack.SharedKernel.Permissions.OperationInvocation", "System.Threading.CancellationToken"); } + /// + /// The operator token profile is its own authority (ADR-0101 § 2, § 3) and reads the validated + /// operator token's claims by design; the offline validator that the rebind tool drives validates the same + /// token with the stock handler before it applies the profile (ADR-0101 § 7, ADR-0104 § 3). Both are exempt by + /// exact type and method, so a raw read in any other method of those types, or anywhere else, is still an + /// offender. + /// + private static bool IsOperatorTokenProfileRead(Call call) => + call.Source.Owner.FullName == OperatorValidation + "PlatformOperatorTokenProfile" && call.Source.Name == "TryRead" + // Exact members, so a later edit that reads a claim, a role or an identity in the validator is still flagged: + // the stock handler's validation call and the three members of its result the decision needs. + || call.Source.Owner.FullName == OperatorValidation + "PlatformOperatorTokenValidator" + && (call.Source.Name == "ValidateAsync" + && call.Target.Name is "ValidateTokenAsync" or "get_IsValid" or "get_Exception" or "get_SecurityToken" + || call.Source.Name == ".cctor" + && call.Target.Name is ".ctor" or "set_MapInboundClaims"); + private static bool IsClosedRolesAbsenceCheck(Call call) { if (call.Source.Site != Signature(Authentication + "OperationHttpClassifier", "Classify", Authentication + "HttpOperationClassification", diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs index 68c05c5f4..60e4ecbec 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs @@ -11,6 +11,7 @@ namespace LearnStack.Tests.Architecture; public sealed partial class AuthenticationAuthorityTests { private const string Authentication = "LearnStack.Api.Authentication."; + private const string OperatorValidation = "LearnStack.Infrastructure.PlatformOperator."; private const string Identity = Authentication + nameof(ValidatedTenantIdentity); private const string Verified = Authentication + nameof(VerifiedProviderSubject); private const string Feature = Authentication + nameof(TenantCredentialFeature); @@ -88,7 +89,7 @@ private static SortedSet Offenders(ModuleDefinition[] modules, foreach (var call in calls.Where(call => (rawReader ?? IsRawAuthorityRead)(call.Target) && !(call.Source.Site == ExpectedSite(Events + ".TokenValidated") && call.Target.FullName == "System.String Microsoft.IdentityModel.JsonWebTokens.JsonWebToken::get_EncodedToken()") - && !IsClosedRolesAbsenceCheck(call) && !IsClosedInvitationTokenRead(call, calls, methods) && !IsClosedConsentTokenRead(call, calls))) + && !IsClosedRolesAbsenceCheck(call) && !IsOperatorTokenProfileRead(call) && !IsClosedInvitationTokenRead(call, calls, methods) && !IsClosedConsentTokenRead(call, calls))) errors.Add("Raw claim/role authority: " + call.Source.Site + " -> " + call.Target.FullName); // Object virtual dispatch and generic formatting can export a positional // record without an identity-declared call. Close acquisition, holders diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs index b1736b88c..2a128949c 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobManifestBoundaryTests.cs @@ -248,7 +248,12 @@ private static SortedSet JobManifestOffenders(ProductionCensus census) if (offenders.Count != 0) return offenders; var bodies = OwnedBodies(census).ToArray(); - var sites = bodies.SelectMany(item => item.Body.Body.Instructions + // The platform operator surface (ADR-0101 § 4) is its own closed surface with its own scheme, and it + // maps minimal endpoints (a group, one verb, one policy, one fixed metadata) rather than controllers. + // It is excluded by exact type, so any other body that registers an endpoint is still counted here; + // the operator surface's own population is asserted in PlatformOperatorHttpTests. + var sites = bodies.Where(item => item.Owner.DeclaringType.FullName != "LearnStack.Api.Platform.PlatformOperatorEndpoints") + .SelectMany(item => item.Body.Body.Instructions .Where(instruction => instruction.Operand is MethodReference) .Select(instruction => (item.Owner, Instruction: instruction, Target: (MethodReference)instruction.Operand))).ToArray(); var invitation = types[("LearnStack.Modules.Identity.Infrastructure", typeof(InvitationEmailRegistration).FullName!)]; diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs index 0af20f609..2289f69a9 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRuntimeCompositionBoundaryTests.cs @@ -32,11 +32,25 @@ public sealed partial class OutboxDispatchConventionTests + "::CreateRuntime(System.IServiceProvider)"; private static string RuntimePreallocateId => InfrastructureAssembly + ":System.Void " + JobRuntime + "::PreallocateOwners(Hangfire.PostgreSql.PostgreSqlStorage)"; - private static IEnumerable MessagingStoreConsumerIds(string store) => - [ - BoundaryApi + ":System.Void " + MessagingLifetime + "::.ctor(" + store + ")", - BoundaryApi + ":System.Threading.Tasks.Task " + MessagingLifetime + "::ObserveExecutionAsync(System.Threading.Tasks.Task)", - ]; + private static IEnumerable MessagingStoreConsumerIds(string store) + { + // ADR-0103: the operator recovery owner is the one DI consumer of each store beside the processors, and it + // reaches only the store's own operator lane. + const string Result = "System.Threading.Tasks.Task`1 "; + return + [ + BoundaryApi + ":System.Void " + MessagingLifetime + "::.ctor(" + store + ")", + BoundaryApi + ":System.Threading.Tasks.Task " + MessagingLifetime + "::ObserveExecutionAsync(System.Threading.Tasks.Task)", + InfrastructureAssembly + ":System.Void " + OperatorRecoveryOwner + "::.ctor(" + DeliveryStore + "," + Store + ")", + InfrastructureAssembly + ":" + Result + OperatorRecoveryOwner + (store == DeliveryStore + ? "::ReplayDeliveryAsync(LearnStack.SharedKernel.Platform.PlatformAdmission," + + "LearnStack.SharedKernel.Platform.DeliveryReplayRequest,System.Threading.CancellationToken)" + : "::ResetOutboxAsync(LearnStack.SharedKernel.Platform.PlatformAdmission," + + "LearnStack.SharedKernel.Platform.OutboxResetRequest,System.Threading.CancellationToken)"), + ]; + } + + private const string OperatorRecoveryOwner = "LearnStack.Infrastructure.Messaging.OperatorRecovery"; private static bool IsDeclaredOwner(string owner, TypeDefinition type) => type.Methods.Any(method => MethodId(method) == owner); diff --git a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs index e0b684b7a..84b8d11f1 100644 --- a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs @@ -185,7 +185,7 @@ public void Delivery_SQL_census_rejects_quoted_CTE_helper_overload_missing_and_p "TRUNCATE another_table, event_deliveries", "MERGE INTO event_deliveries USING x ON true WHEN MATCHED THEN DELETE" }) AssertMutation(census, "an unauthorized subscriber SQL writer", () => AddSqlProbe(module, sql), DeliverySqlOffenders); var store = census.Types[(InfrastructureAssembly, DeliveryStore)]; - foreach (var name in new[] { "ReplayAsync", "UnrelatedSqlHelper" }) + foreach (var name in new[] { "ReplayCoreAsync", "UnrelatedSqlHelper" }) AssertMutation(census, "an extra SQL helper or overload", () => { var method = AddSqlMethod(store, name, "UPDATE event_deliveries SET attempts=0"); @@ -297,7 +297,8 @@ private static SortedSet DeliverySqlOffenders(ProductionCensus census) ("LearnStack.Infrastructure.Messaging.PostgresInboxGuard", "TryClaimAsync"), (DeliveryCompletionType, "FenceAsync"), (DeliveryStore, "AcquireAsync"), (DeliveryStore, "UpdateAsync"), - (DeliveryStore, "TryTerminalizeAsync"), (DeliveryStore, "ReplayAsync"), + // ADR-0103: the operator's fenced replay is the second writer of subscriber status. + (DeliveryStore, "TryTerminalizeAsync"), (DeliveryStore, "ReplayCoreAsync"), }) { if (!types.TryGetValue((InfrastructureAssembly, typeName), out var type)) @@ -459,7 +460,13 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc var storeConstructor = RequireBoundaryMethod(offenders, store, ".ctor", "System.Void", MethodAttributes.Public, BoundaryGuardedSource, "LearnStack.Infrastructure.Messaging.OutboxEventRegistry", "LearnStack.Infrastructure.Messaging.DeliveryDispatchOptions", "LearnStack.SharedKernel.Identifiers.IGuidFactory", - "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory"); + "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory", + "LearnStack.SharedKernel.Jobs.BackgroundJobLifecycleProjection"); + // The public replay is the operator's entry and holds no connection; the core below it owns the one. + RequireBoundaryMethod(offenders, store, "ReplayAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Public, + "LearnStack.SharedKernel.Platform.DeliveryReplayRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + BoundaryCancellation); string[] storeAcquisitions = [ RequireBoundaryMethod(offenders, store, "AcquireAsync", "System.Threading.Tasks.Task`1<" + DeliveryClaimType + ">", MethodAttributes.Private, @@ -471,11 +478,14 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc RequireBoundaryMethod(offenders, store, "IsDurablyTerminalAsync", BoundaryBooleanTask, MethodAttributes.Private, DeliveryClaimType), RequireBoundaryMethod(offenders, store, "ReadSnapshotAsync", "System.Threading.Tasks.Task`1", MethodAttributes.Public, BoundaryStrings, BoundaryCancellation), - RequireBoundaryMethod(offenders, store, "ReplayAsync", BoundaryBooleanTask, MethodAttributes.Public, - "System.Guid", "System.String", "System.Guid", BoundaryCancellation), + RequireBoundaryMethod(offenders, store, "ReplayCoreAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Private, + "LearnStack.SharedKernel.Platform.DeliveryReplayRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + DeliveryStore + "/RecoveryProgress", BoundaryCancellation), ]; var storeReader = RequireBoundaryMethod(offenders, store, "OpenConnectionAsync", - "System.Threading.Tasks.ValueTask`1<" + DeliveryStore + "/OwnedConnection>", MethodAttributes.Private, BoundaryCancellation); + "System.Threading.Tasks.ValueTask`1<" + DeliveryStore + "/OwnedConnection>", MethodAttributes.Private, + BoundaryCancellation, "System.Boolean"); CheckSourceFieldAccess(offenders, census, store, storeConstructor, [storeReader]); CheckCleanupConnectionOwner(offenders, census, store, storeReader, storeAcquisitions); var expected = new[] @@ -500,7 +510,8 @@ private static void CheckDeliveryCredentials(SortedSet offenders, Produc && !(stateMachines.Contains(Key(field.DeclaringType)) && field.Name == "<>4__this")).ToArray(); CheckSet(offenders, "privileged delivery store holders", fields.Select(field => TypeId(field.DeclaringType) + ":" + field.Name), [TypeId(worker) + ":_store", InfrastructureAssembly + ":" + DeliveryStore + "/OwnedConnection:P", - BoundaryApi + ":" + MessagingLifetime + ":_deliveryStore"]); + BoundaryApi + ":" + MessagingLifetime + ":_deliveryStore", + InfrastructureAssembly + ":" + OperatorRecoveryOwner + ":_deliveries"]); if (fields.Any(field => !field.IsPrivate || !field.IsInitOnly && !(field.DeclaringType.FullName == DeliveryStore + "/OwnedConnection" && field.Name == "P"))) offenders.Add("Delivery store holders must be private readonly or the exact construction-only cleanup capture"); diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index 05b241ed8..936f21007 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -47,11 +47,47 @@ public void Federation_Adapter_Admits_Only_The_Enumerated_Routes() var routes = typeof(FederationAdapterFactory).Assembly.GetType("LearnStack.Infrastructure.Identity.Federation.KeycloakFederationRoutes", true)!; routes.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly) .Where(method => method.ReturnType == typeof(Uri)).Select(method => method.Name).Order(StringComparer.Ordinal) - .Should().Equal(["Instance", "Instances", "Mappers", "Token"], "the token endpoint, create, one owned instance and its mappers only"); + .Should().Equal(["Instance", "InstanceOf", "InstancePage", "Instances", "Mappers", "Token"], + "the token endpoint, create, the operator's bounded page and one-alias read, one owned instance and its mappers only"); RouteOffenders(Sources()).Should().BeEmpty( "Fix: build every provider route in KeycloakFederationRoutes, which admits only identity-provider/instances[/{alias}[/mappers]] (ADR-0099)"); } + [Fact] + public void The_one_admitted_query_is_the_listing_page_and_no_provider_file_builds_another() + { + // ADR-0099 Amendment 11 item 7: the census admits the listing's collection route with its one exact query. The + // route builder names the three fragments of it, in order, and no other query fragment exists in the adapter. + var adapter = Sources().Where(source => source.Key.StartsWith(AdapterDirectory, StringComparison.Ordinal)).ToList(); + QueryLiterals(adapter.Single(source => source.Key == RoutesSource).Value).Should().Equal( + ["?first=", "&max=", "&briefRepresentation=false"]); + adapter.Where(source => source.Key != RoutesSource).SelectMany(source => QueryLiterals(source.Value)).Should().BeEmpty( + "Fix: a provider query string is built in KeycloakFederationRoutes alone"); + // A query built without a literal that holds a separator (a builder, a helper, a property) is not a literal to find. + adapter.Where(source => QueryBuilders(source.Value)).Select(source => source.Key).Should().BeEmpty( + "Fix: no query is composed through UriBuilder, QueryHelpers or a Query property in the adapter"); + } + + [Fact] + public void The_query_detector_sees_a_planted_fragment() + { + QueryBuilders("var u = new UriBuilder(uri) { Query = \"search=\" + term };").Should().BeTrue(); + QueryBuilders("var u = QueryHelpers.AddQueryString(path, \"search\", term);").Should().BeTrue(); + QueryBuilders("builder.Query = x;").Should().BeTrue(); + QueryBuilders("var clean = new Uri(options.AdminRealm, \"identity-provider/instances\");").Should().BeFalse(); + QueryLiterals("var uri = \"identity-provider/instances?search=\" + term; var x = \"&briefRepresentation=false\";") + .Should().Equal(["identity-provider/instances?search=", "&briefRepresentation=false"]); + QueryLiterals("var clean = \"identity-provider/instances\";").Should().BeEmpty(); + } + + private static bool QueryBuilders(string source) => + Regex.IsMatch(source, @"\bUriBuilder\b|\bAddQueryString\b|\bQueryHelpers\b|\.Query\s*="); + + /// The string literals of a source that hold a query separator, with whole-line comments set aside first. + private static List QueryLiterals(string source) => + [.. Regex.Matches(Regex.Replace(source, @"^\s*//.*$", string.Empty, RegexOptions.Multiline), @"""(?:[^""\\\r\n]|\\.)*""") + .Select(match => match.Value[1..^1]).Where(literal => literal.Contains('?') || literal.Contains('&'))]; + [Fact] public void The_route_detector_refuses_planted_routes() { @@ -204,6 +240,12 @@ [.. sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison "JWT bearer metadata and JWKS (ADR-0064): the fixed Authentication:Tenant:Issuer only", ["LearnStack.Api/Authentication/CurrentInvitationRecipientReader.cs"] = "the invitation recipient's UserInfo read (ADR-0093): the fixed tenant-realm issuer only", + ["LearnStack.Infrastructure/Identity/BoundedMetadataReader.cs"] = + "the bounded metadata read both bearer schemes and the rebind tool share (ADR-0064, ADR-0101 § 2, ADR-0104): the fixed issuer each caller configures only", + ["LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetadata.cs"] = + "the operator validator's metadata and JWKS client, shared by the API scheme and the offline rebind tool (ADR-0101 § 2, ADR-0104 § 3): the one pinned PlatformOperator:Issuer, never a followed redirect", + ["LearnStack.Tools.IdentityAuthorityRebind/KeycloakRealmContinuitySource.cs"] = + "the offline rebind tool's read of the new realm (ADR-0104 § 4, § 6): the one new issuer's own origin with an operator-supplied view-users credential, never a followed redirect", ["LearnStack.Infrastructure/Email/Smtp/SmtpEmailProvider.cs"] = "operator-configured SMTP host for invitation mail; not a tenant URL", }; diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs index 031cb444c..539eeb32c 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs @@ -112,6 +112,19 @@ public void Every_Federation_Request_Has_An_Audit_Catalogue_Entry() "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/PublicSignInReader.cs", ]; + /// + /// The operator's one read of the registry (ADR-0099 Amendment 10 and 11): an orphan is a broker with no row or a + /// tombstoned one, so this reader must see tombstones and is exempt from the shared live predicate. It is pinned + /// instead to exactly this statement, which names the four columns the platform role may select and reads by + /// primary key; a fifth column or another predicate is refused by PostgreSQL and by this census. + /// + private const string OperatorRowReader = IdentityInfrastructure + "Federation/FederationBrokerOperations.cs"; + + private const string OperatorRowQuery = + "SELECT id, tenant_id, state, deleted_at IS NOT NULL FROM federation_connections WHERE id = ANY(@ids)"; + + private static readonly string[] AllRawReaders = [.. RawLiveReaders, OperatorRowReader]; + [Fact] public void Raw_Federation_Reads_Share_The_One_Pinned_Live_Predicate() { @@ -126,7 +139,8 @@ public void Raw_Federation_Reads_Share_The_One_Pinned_Live_Predicate() RawLiveOffenders(sources).Should().BeEmpty( "Fix: every raw read of federation_connections lives in one of the three closed readers, and each statement interpolates " + "FederationConnectionReads.LiveSql and spells no tombstone predicate of its own"); - RawReaders(sources).Should().Equal(RawLiveReaders, "the census of raw registry readers is closed at three"); + RawReaders(sources).Should().Equal(AllRawReaders.Order(StringComparer.Ordinal), + "the census of raw registry readers is closed at three tenant readers and the operator's one pinned read"); } [Fact] @@ -141,9 +155,21 @@ public void The_raw_live_predicate_detector_refuses_a_reader_with_its_own_predic [RawLiveReaders[2]] = "\"\"\"\nSELECT alias FROM public.federation_connections " + Shared + " AND state='Active'\n\"\"\";", [IdentityInfrastructure + "Persistence/FederationConnectionStorageDdl.cs"] = "REVOKE ALL ON public.federation_connections FROM PUBLIC; CREATE TRIGGER t BEFORE INSERT OR UPDATE ON public.federation_connections;", + [OperatorRowReader] = "private const string RowQuery = \"" + OperatorRowQuery + "\";", }; RawLiveOffenders(clean).Should().BeEmpty(); - RawReaders(clean).Should().Equal(RawLiveReaders); + RawReaders(clean).Should().Equal(AllRawReaders.Order(StringComparer.Ordinal)); + // The operator's statement is pinned whole: a fifth column, another predicate or a second statement is refused. + foreach (var changed in new[] + { + OperatorRowQuery.Replace("state,", "state, alias,", StringComparison.Ordinal), + OperatorRowQuery.Replace("id = ANY(@ids)", "tenant_id = @tenant", StringComparison.Ordinal), + OperatorRowQuery + " AND state <> 'Deleted'", + }) + { + var widened = new Dictionary(clean) { [OperatorRowReader] = "private const string RowQuery = \"" + changed + "\";" }; + RawLiveOffenders(widened).Should().Equal([OperatorRowReader], "the operator reader is pinned: " + changed); + } var own = new Dictionary(clean) { [RawLiveReaders[1]] = "SELECT alias FROM public.federation_connections WHERE tenant_id=@tenant AND state='Active' AND deleted_at IS NULL", @@ -179,7 +205,7 @@ public void The_raw_live_predicate_detector_refuses_a_reader_with_its_own_predic } // A closed reader that is removed leaves the census short. var dropped = new Dictionary(clean) { [RawLiveReaders[2]] = "public sealed class PublicSignInReader;" }; - RawReaders(dropped).Should().Equal([RawLiveReaders[0], RawLiveReaders[1]]); + RawReaders(dropped).Should().Equal([OperatorRowReader, RawLiveReaders[0], RawLiveReaders[1]]); } private const string IdentityApplication = "Modules/Identity/LearnStack.Modules.Identity.Application/"; @@ -202,7 +228,9 @@ private static List RawReaders(IReadOnlyDictionary sourc /// ; or string delimiter on either side, must interpolate the shared constant and spell no tombstone predicate. /// private static List RawLiveOffenders(IReadOnlyDictionary sources) => - [.. sources.Where(pair => RawRead.Matches(pair.Value).Any(match => !RawLiveReaders.Contains(pair.Key, StringComparer.Ordinal) + [.. sources.Where(pair => RawRead.Matches(pair.Value).Any(match => pair.Key == OperatorRowReader + ? !string.Equals(Statement(pair.Value, match.Index).Trim(), OperatorRowQuery, StringComparison.Ordinal) + : !RawLiveReaders.Contains(pair.Key, StringComparer.Ordinal) || Statement(pair.Value, match.Index) is var statement && (!statement.Contains("{FederationConnectionReads.LiveSql}", StringComparison.Ordinal) || statement.Contains("deleted_at", StringComparison.OrdinalIgnoreCase) diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs index 4c1c7234d..0cf7c2023 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -43,6 +43,7 @@ public sealed partial class IdentityAuditConventionTests private const string OrdinaryAuditOwner = "LearnStack.Application.Audit.AuditExecutionCoordinator"; private static readonly string[] AuthorizationPrimaryKeyFilter = ["23505", "public", "audit_log", "audit_log_pkey"]; private const string SeedTenancyGuard = "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard"; + private const string OperatorActGuard = "LearnStack.SharedKernel.Permissions.OperatorActGuard"; private const string SeedCustomizationGuard = "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationWriteGuard"; private const string SeedEducationGuard = "LearnStack.Modules.Education.Application.Seeding.SeedEducationWriteGuard"; private const string SeedOriginHandler = "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler"; @@ -99,6 +100,9 @@ private static readonly (string Owner, string Method, int Count)[] CurrentInvoca (FixedCompletionSource, "HasInvocation", 1), (SeedTenancyGuard, "AdmitAsync", 1), (SeedTenancyGuard, "RequireCurrent", 1), + (OperatorActGuard, "AdmitAsync", 1), + (OperatorActGuard, "RequireCurrent", 1), + (OperatorActGuard, "RequireLiveAct", 1), (SeedTenancyGuard, "AllowsIdentityContinuationAsync", 1), (SeedTenancyGuard, "AllowsContentContinuationAsync", 1), (SeedTenancyGuard, "g__Current|14_0", 1), diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs index 8a434112b..85caaf697 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs @@ -18,6 +18,9 @@ public sealed partial class IdentityAuditConventionTests private const string BindingService = "LearnStack.Modules.Identity.Infrastructure.Bindings.GlobalIdentityBindingService"; private const string InitialMigration = "LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.create_identity_schema"; private const string Installer = "LearnStack.Infrastructure.Audit.IdentityCreationWitnessInstaller"; + private const string RebindInstaller = "LearnStack.Infrastructure.Audit.IdentityRebindAuditInstaller"; + private const string RebindDdl = "LearnStack.Modules.Identity.Infrastructure.Persistence.IdentityAuthorityRebindDdl"; + private const string RebindRun = "LearnStack.Modules.Identity.Infrastructure.Bindings.IdentityIssuerRebind"; private const string GlobalSource = "LearnStack.Application.Audit.AuditExecutionCoordinator+GlobalCreationSource"; private const string InvitationJobStore = "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailJobStore"; private const string InvitationStager = "LearnStack.Modules.Identity.Infrastructure.Invitations.InvitationEmailStager"; @@ -47,6 +50,11 @@ public void Global_Identity_Creation_Uses_The_Common_Audit_Owner() .Should().Equal(typeof(TransactionExecutionCoordinator).FullName + ".ExecuteFrameAsync"); Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.ReconcileGlobalIdentityAsync)) .Should().Equal(typeof(AuditExecutionCoordinator).FullName + ".ReconcileAsync"); + // ADR-0104 § 8: the two witness-bound rebind writes have one production caller each, the rebind run itself. + Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.WriteIdentityRebindIntentAsync)) + .Should().Equal(RebindRun + ".TryWriteIntentAsync"); + Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.WriteIdentityRebindResultAsync)) + .Should().Equal(RebindRun + ".RunCoreAsync"); var audit = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, "LearnStack.Infrastructure.Audit", "PostgresAuditStore.cs")); @@ -69,6 +77,8 @@ public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_m Il.MethodsNaming(migration!, Installer).Should().Equal("Down", "Up"); Callers(Installer, "Install").Should().Equal(InitialMigration + ".Up"); Callers(Installer, "Remove").Should().Equal(InitialMigration + ".Down"); + // ADR-0104: the rebind role's audit_log grant and policy arm have one central owner and one caller. + Callers(RebindInstaller, "Install").Should().Equal(RebindDdl + ".Add"); foreach (var owner in new[] { InvitationJobStore, InvitationStager }) { var adapter = module.GetType(owner); @@ -96,6 +106,36 @@ public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_m finally { definition.Body.Instructions.Remove(extraFrameworkRead); } } + [Fact] + public void The_Operator_Token_Validator_Has_Two_Callers_Of_The_Profile_And_One_Of_Its_Own() + { + // ADR-0101 § 7: the witness comes from one validator with two callers. The API scheme reads a token through the + // profile from its validated event; the offline validator reads one through the stock handler and then the + // profile; and the offline validator is constructed and called by the rebind tool alone, so no endpoint, job or + // module adapter can mint a witness by borrowing it. + const string Profile = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorTokenProfile"; + const string Validator = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorTokenValidator"; + Callers(Profile, "TryRead").Should().Equal( + "LearnStack.Api.Authentication.PlatformOperatorEvents.TokenValidated", + Validator + ".ValidateAsync"); + Callers(Validator, "ValidateAsync").Should().Equal("LearnStack.Tools.IdentityAuthorityRebind.RebindTool.RunAdmittedAsync"); + Callers(Validator, ".ctor").Should().Equal("LearnStack.Tools.IdentityAuthorityRebind.RebindTool.RunAdmittedAsync"); + } + + [Fact] + public void Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock() + { + // ADR-0104 § 5: the exclusive form belongs to the rebind run, and the shared form to authority qualification, the + // User-creation admission and the run's own reconciliation of an unknown COMMIT, which waits for the original + // transaction behind it. A further taker is a further party that can wait on, or hold, the freeze. + Callers(typeof(IdentityAdvisoryLockKey).FullName!, nameof(IdentityAdvisoryLockKey.ForAuthorityRebind)) + .Should().Equal( + "LearnStack.Infrastructure.Persistence.NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync", + "LearnStack.Modules.Identity.Infrastructure.Bindings.IdentityAuthorityQualification.QualifyCoreAsync", + RebindRun + ".CommitAsync", + RebindRun + ".RunCoreAsync"); + } + [Fact] public void A_new_minter_or_a_borrowed_core_edge_is_rejected() { @@ -140,6 +180,7 @@ private static IEnumerable CoreEdgeViolations(TypeDefinition type) or "LearnStack.Application.Persistence.TransactionExecutionCoordinator" or "LearnStack.Application.Persistence.TransactionExecutionCoordinator/PreparedGlobalIdentityOwner" || type.FullName == InitialMigration && reference.FullName == Installer + || type.FullName == RebindDdl && reference.FullName == RebindInstaller || type.FullName is InvitationJobStore or InvitationStager && reference.FullName is InvitationProducer or InvitationJobOrigin || type.FullName == InvitationRegistration && reference.FullName == FrameworkRequests; diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs index 6be1572d8..74b4ce7b0 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -116,6 +116,7 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() "LearnStack.Modules.Tenancy.Application.Authorization.TenancyAdministrationAuthorization.AdmitWriteAsync", "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationWriteGuard.PrepareAsync", "LearnStack.Modules.Education.Application.Seeding.SeedEducationWriteGuard.PrepareAsync", + "LearnStack.SharedKernel.Permissions.OperatorActGuard.AdmitAsync", "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard.AdmitAsync", "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler.Handle", "LearnStack.Modules.Identity.Application.Federation.FederationCommandHandlers.ActAsync", @@ -139,6 +140,7 @@ public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationWriteGuard.IsCurrent", "LearnStack.Modules.Education.Application.Seeding.SeedEducationWriteGuard.IsCurrent", "LearnStack.Modules.Tenancy.Application.Seeding.SeedTenantWriteGuard.RequireCurrent", + "LearnStack.SharedKernel.Permissions.OperatorActGuard.RequireCurrent", "LearnStack.Modules.Tenancy.Application.Seeding.AdoptSeedAdministrationOriginCommandHandler.Handle", "LearnStack.Modules.Identity.Infrastructure.Persistence.SeedIdentityStageReader.HasNoRoleHistoryAsync", "LearnStack.Modules.Customization.Application.Seeding.SeedCustomizationPrerequisiteReader.IsCompleteAsync", @@ -227,6 +229,30 @@ private static IEnumerable SessionCalls(string source) => Regex.Matches( @"\bpg_(?:try_)?advisory_(?:lock|unlock)(?:_shared|_all)?\s*\(", RegexOptions.IgnoreCase) .Select(match => match.Value); + [Fact] + public void Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject() + { + // ADR-0102 § 5: the confined definer is reached through one adapter, and the port through the one core that + // names a person for an administrator act. A second caller would be a second way to ask whether a provider + // subject is an Active user, and is added here deliberately with its own denied proof. + SourceScan.FilesContaining(SourceScan.SourceRoot, "fn_identity_operator_resolve_user", except: null) + .Should().BeEquivalentTo( + [ + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolverDdl.cs", + ], + "only the adapter calls the function and only its migration installs it"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "IOperatorSubjectResolver", except: null) + .Should().BeEquivalentTo( + [ + "Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IOperatorSubjectResolver.cs", + "Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/OperatorIdentityHandlers.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/OperatorSubjectResolver.cs", + ], + "the port is declared, implemented, registered and used by the operator administrator core, and by nothing else"); + } + private static string[] Callers(string typeName, string methodName) => ProductionAssemblies.All().SelectMany(assembly => { using var module = ModuleDefinition.ReadModule(assembly.Location); diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index e13dfab8c..e39fd8a3a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs @@ -541,7 +541,10 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(InfrastructureAssembly, LifecycleInvitationSmtpOwner, "ExecuteSqlAsync", LifecycleInvitationSmtpSqlParameters), Owner(InfrastructureAssembly, Store, "AcquireAsync"), Owner(InfrastructureAssembly, Store, "TryTerminalizeAsync"), Owner(InfrastructureAssembly, DeliveryStore, "AcquireAsync"), Owner(InfrastructureAssembly, DeliveryStore, "UpdateAsync"), - Owner(InfrastructureAssembly, DeliveryStore, "TryTerminalizeAsync"), Owner(InfrastructureAssembly, DeliveryStore, "ReplayAsync"), + // ADR-0103: the operator's fenced replay and reset each own one short transaction of their own on the + // dispatcher role, never business completion. + Owner(InfrastructureAssembly, DeliveryStore, "TryTerminalizeAsync"), Owner(InfrastructureAssembly, DeliveryStore, "ReplayCoreAsync"), + Owner(InfrastructureAssembly, Store, "ResetCoreAsync"), // Routing publishes a claim only after this owned operation acknowledges COMMIT and joins cleanup. Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobRoutingStore", "TryClaimOwnedAsync"), // Bridge transport hints own short privileged transactions, never business completion. @@ -556,12 +559,18 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityDeploymentInstaller", "InstallAsync", ["Npgsql.NpgsqlConnection", LifecycleIdentityBindings + "IdentityAuthorityRegistration", BoundaryCancellation]), Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityQualification", "QualifyCoreAsync", [BoundaryCancellation]), + // ADR-0104: the offline rebind owns two transactions of its own on its confined role, never business + // completion: the intent row commits alone, and the issuer change commits with its result row. + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityIssuerRebind", "CommitAsync"), + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityIssuerRebind", "TryWriteIntentAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "CommitAsync", ["LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation]), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobTerminalStore", "CommitAsync", ["LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation]), Owner(AuditAssembly, "LearnStack.Infrastructure.Audit.AuditConfigService", "LoadAsync"), Owner(InfrastructureAssembly, LifecyclePlatform, "RecordAsync"), Owner(InfrastructureAssembly, LifecyclePlatform + "/Handle", "CommitAsync"), + // ADR-0044 Amendment 18: the checkpoint commits the intent row alone before the provider is called. + Owner(InfrastructureAssembly, LifecyclePlatform + "/Handle", "WriteIntentAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.MultiTenancy.CachedHostToTenantResolver", "ReadAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.MultiTenancy.OrganizationScopeValidator", "BelongsToTenantAsync"), Owner("LearnStack.Modules.Tenancy.Infrastructure", "LearnStack.Modules.Tenancy.Infrastructure.FeatureFlags", "LoadTenantFlagsAsync"), @@ -570,6 +579,8 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( ], ["database.RollbackAsync"] = [Owner(InfrastructureAssembly, LifecycleAdapter, "RollbackCoreAsync"), Owner(InfrastructureAssembly, LifecyclePlatform + "/Handle", "DisposeAsync"), + // ADR-0104: a rebind whose target is already stored ends its own read-only transaction, writing nothing. + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityIssuerRebind", "RunCoreAsync"), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeCommitAsync", ["LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation]), // Read-only metadata probes own a separate connection/transaction and join its actual rollback/cleanup. diff --git a/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj b/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj index 73962a6ee..78e870086 100644 --- a/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj +++ b/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj @@ -32,6 +32,7 @@ itself is exactly what these rules exist to see. --> + diff --git a/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs new file mode 100644 index 000000000..481ab0fc4 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs @@ -0,0 +1,180 @@ +using FluentAssertions; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// ADR-0103: the operator recovery witness is minted only from the two stores' fenced resets and written once each. +public sealed partial class OutboxDispatchConventionTests +{ + private const string RecoveryWitness = "LearnStack.SharedKernel.Audit.OperatorRecoveryTransition"; + private const string RecoverySource = RecoveryWitness + "/MintingSource"; + private const string RecoveryReplayMint = "FromReplayUpdate"; + private const string RecoveryResetMint = "FromResetUpdate"; + private const string RecoveryWrite = "WriteOperatorRecoveryAsync"; + private const string RecoveryMintSubtype = "/RecoveryMint"; + private static readonly string[] RecoveryMintParameters = + [ + "System.Data.Common.DbConnection", "System.Data.Common.DbTransaction", + "System.Data.Common.DbDataReader", "LearnStack.SharedKernel.Platform.PlatformAdmission", + ]; + private static readonly string[] RecoveryWriteParameters = + [ + "LearnStack.SharedKernel.Audit.AuditEntryDraft", RecoveryWitness, + "System.Data.Common.DbConnection", "System.Data.Common.DbTransaction", + "System.Threading.CancellationToken", + ]; + + /// + /// ADR-0103 § 5: the second writer of dispatcher status mints its witness from the actual returned row of its + /// fenced UPDATE, and the audit port's recovery write has exactly the two dispatcher callers. PostgreSQL tests + /// separately prove that the live result and the draft agree. + /// + [Fact] + public void Operator_Recovery_Audit_Identity_Is_Row_Bound() + { + using var census = ProductionCensus.Read(); + RecoveryOffenders(census).Should().BeEmpty( + "Fix: keep the immutable private recovery witness, its two nested store minting subtypes and the " + + "recovery writer and its call sites closed; keep row and transaction identity checks in the witness"); + } + + [Fact] + public void Operator_recovery_census_detects_extra_derivers_constructors_and_callers() + { + using var census = ProductionCensus.Read(); + var source = census.Types[(KernelAssembly, RecoverySource)]; + var factory = source.Methods.Single(method => method.Name == RecoveryReplayMint); + var constructor = census.Types[(KernelAssembly, RecoveryWitness)].Methods.Single(method => method.IsConstructor && !method.IsStatic); + var port = census.Types[(KernelAssembly, AuditPort)]; + var write = port.Methods.Single(method => method.Name == RecoveryWrite); + var application = census.Modules.Single(module => module.Assembly.Name.Name == "LearnStack.Application"); + + AssertMutation(census, "a second minting subtype in another production assembly", () => + { + var type = AddProbe(application, "AdditionalRecoveryMintingSource"); + type.BaseType = application.ImportReference(source); + return () => application.Types.Remove(type); + }, RecoveryOffenders); + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) + { + AssertMutation(census, "a cross-assembly mint helper using " + opcode.Name, () => + AddCallProbe(application, "AdditionalRecoveryMintCaller", factory, opcode), RecoveryOffenders); + } + + AssertMutation(census, "a direct private witness constructor call", () => + AddCallProbe(application, "AdditionalRecoveryConstructor", constructor, OpCodes.Newobj), RecoveryOffenders); + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt }) + { + AssertMutation(census, "an extra recovery writer caller using " + opcode.Name, () => + AddCallProbe(application, "AdditionalRecoveryWriter", write, opcode), RecoveryOffenders); + } + + AssertMutation(census, "a helper on the sanctioned store type", () => + { + var type = census.Types[(InfrastructureAssembly, Store)]; + var method = AddCall(type, "UnrelatedRecoveryHelper", factory, OpCodes.Call); + return () => type.Methods.Remove(method); + }, RecoveryOffenders); + + // The reset factory is as closed as the replay one: it is probed the same ways. + var resetFactory = source.Methods.Single(method => method.Name == RecoveryResetMint); + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) + { + AssertMutation(census, "a cross-assembly reset mint helper using " + opcode.Name, () => + AddCallProbe(application, "AdditionalRecoveryResetMintCaller", resetFactory, opcode), RecoveryOffenders); + } + + AssertMutation(census, "a reset mint helper on the delivery store type", () => + { + var type = census.Types[(InfrastructureAssembly, DeliveryStore)]; + var method = AddCall(type, "UnrelatedRecoveryResetHelper", resetFactory, OpCodes.Call); + return () => type.Methods.Remove(method); + }, RecoveryOffenders); + } + + private static SortedSet RecoveryOffenders(ProductionCensus census) + { + var offenders = new SortedSet(StringComparer.Ordinal); + var types = census.Types; + foreach (var key in new[] { (KernelAssembly, RecoveryWitness), (KernelAssembly, RecoverySource), + (InfrastructureAssembly, Store), (InfrastructureAssembly, DeliveryStore), + (InfrastructureAssembly, Store + RecoveryMintSubtype), (InfrastructureAssembly, DeliveryStore + RecoveryMintSubtype), + (KernelAssembly, AuditPort), (AuditAssembly, AuditStore) }) + { + if (!types.ContainsKey(key)) offenders.Add("Missing production subject: " + key.Item2); + } + + if (offenders.Count != 0) return offenders; + + var witness = types[(KernelAssembly, RecoveryWitness)]; + var source = types[(KernelAssembly, RecoverySource)]; + var port = types[(KernelAssembly, AuditPort)]; + var auditStore = types[(AuditAssembly, AuditStore)]; + var subtypes = new[] { types[(InfrastructureAssembly, Store + RecoveryMintSubtype)], types[(InfrastructureAssembly, DeliveryStore + RecoveryMintSubtype)] }; + + var constructors = witness.Methods.Where(method => method.IsConstructor && !method.IsStatic).ToArray(); + if (!witness.IsSealed || witness.BaseType?.FullName != "System.Object") offenders.Add(RecoveryWitness + ": must be sealed with no custom base"); + if (constructors.Length != 1 || constructors.Any(method => !method.IsPrivate + || !ParametersMatch(method, [.. RecoveryMintParameters, "System.Boolean"]))) + offenders.Add(RecoveryWitness + ": requires exactly one private live-reader constructor"); + if (witness.Fields.All(field => field.IsStatic) || witness.Fields.Any(field => !field.IsStatic && !field.IsInitOnly)) + offenders.Add(RecoveryWitness + ": instance fields must be nonempty and readonly"); + if (witness.Properties.Count == 0 || witness.Properties.Any(property => property.SetMethod is not null)) + offenders.Add(RecoveryWitness + ": properties must be nonempty and getter-only"); + if (!source.IsNestedPublic || !source.IsAbstract || source.IsSealed) + offenders.Add(RecoverySource + ": requires the public abstract nested minting capability"); + if (source.Methods.Where(method => method.IsConstructor && !method.IsStatic).Any(method => !method.IsFamily)) + offenders.Add(RecoverySource + ": constructors must be protected"); + if (witness.Module.Assembly.CustomAttributes.Any(attribute => + attribute.AttributeType.FullName == "System.Runtime.CompilerServices.InternalsVisibleToAttribute")) + offenders.Add(KernelAssembly + ": friend assemblies reopen restricted authority"); + + var factories = source.Methods.Where(method => method.Name is RecoveryReplayMint or RecoveryResetMint).ToArray(); + if (factories.Length != 2 || factories.Select(method => method.Name).Distinct(StringComparer.Ordinal).Count() != 2 + || factories.Any(method => !method.IsFamily || !method.IsStatic || method.ReturnType.FullName != RecoveryWitness + || !ParametersMatch(method, RecoveryMintParameters))) + offenders.Add(RecoverySource + ": requires the two protected static live-reader mint signatures"); + if (subtypes.Any(type => !type.IsNestedPrivate || !type.IsSealed)) + offenders.Add("The recovery minting subtypes must be private sealed nested classes of their stores"); + + CheckSet(offenders, "recovery minting subtypes", types.Values.Where(type => Derives(type, source, types)).Select(TypeId), + subtypes.Select(TypeId)); + CheckSet(offenders, "recovery witness-producing methods", types.Values.SelectMany(type => type.Methods) + .Where(method => method.ReturnType.FullName == RecoveryWitness).Select(MethodId), + factories.Select(MethodId).Concat(subtypes.SelectMany(type => type.Methods.Where(method => method.Name is "Replay" or "Reset") + .Select(MethodId)))); + + var writers = types.Values.Where(type => !type.IsInterface && !type.IsAbstract && Derives(type, port, types)).ToArray(); + CheckSet(offenders, "audit store implementations", writers.Select(TypeId), [TypeId(auditStore)]); + var declarations = types.Values.Where(type => SameType(type, port) || Derives(type, port, types)) + .SelectMany(type => type.Methods).Where(method => method.Name == RecoveryWrite).ToArray(); + CheckSet(offenders, "recovery audit declarations", declarations.Select(method => TypeId(method.DeclaringType) + "." + method.Name), + [TypeId(port) + "." + RecoveryWrite, TypeId(auditStore) + "." + RecoveryWrite]); + foreach (var method in declarations.Where(method => method.ReturnType.FullName != "System.Threading.Tasks.Task" + || !ParametersMatch(method, RecoveryWriteParameters))) + offenders.Add(MethodId(method) + ": wrong recovery write signature"); + + var sites = CallSites(census).ToArray(); + CheckSet(offenders, "recovery witness constructor call sites", sites.Where(site => site.Target.Name == ".ctor" + && SameType(site.Target.DeclaringType, witness)).Select(site => site.Owner), factories.Select(MethodId)); + foreach (var (mint, wrapper, store) in new[] { (RecoveryReplayMint, "Replay", DeliveryStore), (RecoveryResetMint, "Reset", Store) }) + { + var subtype = types[(InfrastructureAssembly, store + RecoveryMintSubtype)]; + CheckSet(offenders, mint + " call sites", sites.Where(site => site.Target.Name == mint + && (SameType(site.Target.DeclaringType, source) || Derives(site.Target.DeclaringType, source, types))) + .Select(site => site.Owner), subtype.Methods.Where(method => method.Name == wrapper).Select(MethodId)); + var core = types[(InfrastructureAssembly, store)].Methods.Where(method => method.Name is "ReplayCoreAsync" or "ResetCoreAsync").ToArray(); + CheckSet(offenders, wrapper + " wrapper call sites", sites.Where(site => site.Target.Name == wrapper + && SameType(site.Target.DeclaringType, subtype)).Select(site => site.Owner), core.Select(MethodId)); + } + + var recoveryRows = types[(InfrastructureAssembly, Store)].Methods.Concat(types[(InfrastructureAssembly, DeliveryStore)].Methods) + .Where(method => method.Name == "WriteRecoveryRowAsync").ToArray(); + CheckSet(offenders, "recovery audit call sites", sites.Where(site => site.Target.Name == RecoveryWrite + && (SameType(site.Target.DeclaringType, port) || Derives(site.Target.DeclaringType, port, types))) + .Select(site => site.Owner), recoveryRows.Select(MethodId)); + return offenders; + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs index 350fdfb38..407149079 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs @@ -658,7 +658,13 @@ private static SortedSet CredentialOffenders(ProductionCensus census) var storeConstructor = RequireBoundaryMethod(offenders, store, ".ctor", "System.Void", MethodAttributes.Public, BoundaryGuardedSource, "LearnStack.Infrastructure.Messaging.OutboxEventRegistry", "LearnStack.Infrastructure.Messaging.OutboxDispatchOptions", "LearnStack.SharedKernel.Identifiers.IGuidFactory", - "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory"); + "LearnStack.SharedKernel.Time.IClock", "Microsoft.Extensions.DependencyInjection.IServiceScopeFactory", + "LearnStack.SharedKernel.Jobs.BackgroundJobLifecycleProjection"); + // The public reset is the operator's entry and holds no connection; the core below it owns the one. + RequireBoundaryMethod(offenders, store, "ResetAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Public, + "LearnStack.SharedKernel.Platform.OutboxResetRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + BoundaryCancellation); string[] storeAcquisitions = [ RequireBoundaryMethod(offenders, store, "AcquireAsync", "System.Threading.Tasks.Task`1<" + BoundaryClaim + ">", MethodAttributes.Private, @@ -670,9 +676,14 @@ private static SortedSet CredentialOffenders(ProductionCensus census) RequireBoundaryMethod(offenders, store, "IsDurablyTerminalAsync", BoundaryBooleanTask, MethodAttributes.Private, "System.Guid"), RequireBoundaryMethod(offenders, store, "ReadSnapshotAsync", "System.Threading.Tasks.Task`1", MethodAttributes.Public, BoundaryStrings, BoundaryCancellation), + RequireBoundaryMethod(offenders, store, "ResetCoreAsync", + "System.Threading.Tasks.Task`1", MethodAttributes.Private, + "LearnStack.SharedKernel.Platform.OutboxResetRequest", "LearnStack.SharedKernel.Platform.PlatformAdmission", + Store + "/RecoveryProgress", BoundaryCancellation), ]; var storeReader = RequireBoundaryMethod(offenders, store, "OpenConnectionAsync", - "System.Threading.Tasks.ValueTask`1<" + Store + "/OwnedConnection>", MethodAttributes.Private, BoundaryCancellation); + "System.Threading.Tasks.ValueTask`1<" + Store + "/OwnedConnection>", MethodAttributes.Private, + BoundaryCancellation, "System.Boolean"); CheckSourceFieldAccess(offenders, census, store, storeConstructor, [storeReader]); CheckCleanupConnectionOwner(offenders, census, store, storeReader, storeAcquisitions); if (storeFactory is not null) CheckStoreConsumers(offenders, census, outboxRoot, storeFactory); @@ -719,7 +730,8 @@ private static void CheckStoreConsumers(SortedSet offenders, ProductionC && field.FieldType.FullName == Store)).ToArray(); CheckSet(offenders, "privileged store fields", fields.Select(field => TypeId(field.DeclaringType) + ":" + field.Name), [TypeId(worker) + ":_store", InfrastructureAssembly + ":" + Store + "/OwnedConnection:P", - BoundaryApi + ":" + MessagingLifetime + ":_outboxStore"]); + BoundaryApi + ":" + MessagingLifetime + ":_outboxStore", + InfrastructureAssembly + ":" + OperatorRecoveryOwner + ":_outbox"]); foreach (var field in fields) if (!field.IsPrivate || !field.IsInitOnly && !(field.DeclaringType.FullName == Store + "/OwnedConnection" && field.Name == "P")) offenders.Add(field.FullName + ": store capability must remain private and readonly or the exact construction-only cleanup capture"); diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs index ae2c13b26..d9ff20860 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs @@ -321,6 +321,12 @@ public void Outbox_SQL_census_detects_quoted_schema_CTE_extra_and_missing_writer var method = AddSqlMethod(store, "AcquireAsync", "UPDATE outbox_messages SET attempts=0"); return () => store.Methods.Remove(method); }, OutboxSqlOffenders); + AssertMutation(census, "an extra overload of the operator's producer reset", () => + { + var store = census.Types[(InfrastructureAssembly, Store)]; + var method = AddSqlMethod(store, "ResetCoreAsync", "UPDATE outbox_messages SET attempts=0"); + return () => store.Methods.Remove(method); + }, OutboxSqlOffenders); AssertMutation(census, "a missing production mutation path", () => { var literal = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == Store) @@ -372,6 +378,8 @@ private static SortedSet OutboxSqlOffenders(ProductionCensus census) { ("LearnStack.Infrastructure.Messaging.PostgresOutbox", "EnqueueAsync"), (Store, "AcquireAsync"), (Store, "UpdateAsync"), (Store, "TryTerminalizeAsync"), + // ADR-0103: the operator's fenced producer reset is the second writer of dispatcher status. + (Store, "ResetCoreAsync"), ("LearnStack.Infrastructure.Persistence.Migrations.add_outbox_dispatch_state", "Up"), }) { diff --git a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs index 75d1ef83f..743c6291c 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs @@ -219,6 +219,9 @@ public void Module_DbContexts_Enlist_In_The_Ambient_UnitOfWork() "Persistence/EducationDbContextFactory.cs", "Persistence/IdentityDbContextFactory.cs", "LearnStack.Tools.IdentityAuthorityInstaller/Program.cs", + // ADR-0104's controlled issuer rebind opens its own direct, never-pooled connections as the confined + // sixth role: the exclusive-lock transaction, the intent-row transaction and the commit reconciliation. + "Bindings/IdentityIssuerRebind.cs", // Both runtime hosts delegate application-role construction to this // shared guard; the API retains its separate platform-role builder. diff --git a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index 55d9ec3a7..afca3a2bd 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -1,7 +1,10 @@ using System.Reflection; +using System.Text.RegularExpressions; using FluentAssertions; using LearnStack.Api.Messaging; using LearnStack.Infrastructure.Messaging; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Tenancy; using Microsoft.Extensions.DependencyInjection; using Xunit; @@ -11,7 +14,7 @@ namespace LearnStack.Tests.Architecture; /// /// The rules that keep the one BYPASSRLS credential reachable from one place. /// -public sealed class PlatformAdminScopeConventionTests +public sealed partial class PlatformAdminScopeConventionTests { /// /// Every LearnStack.* assembly under backend/src, loaded without a @@ -150,51 +153,306 @@ public void No_IgnoreQueryFilters_Outside_PlatformAdminScope() } [Fact] - public async Task PlatformAdminScope_Entry_Requires_Platform_Permission() + public void PlatformAdminScope_Entry_Requires_Platform_Permission() { - // Conjunct A — live. The gate port exists, the registered implementation refuses - // everyone, and the scope consults it. That last part is what makes ADR-0036's - // "checked before the scope opens" a call rather than a sentence; the ORDER — - // before the credential is touched — is asserted behaviourally in - // PlatformAdminGateTests, which a structural test cannot see. - typeof(IPlatformAdminGate).Should().BeAssignableTo(); - - (await new DenyAllPlatformAdminGate().IsPermittedAsync("any", CancellationToken.None)) - .Should().BeFalse("the shipped gate permits nobody until Phase 03"); - - SourceScan.FilesContaining(SourceScan.SourceRoot, "IsPermittedAsync", except: null) - .Should().Contain(ScopeFile, "the scope must actually consult the gate"); - - // Conjunct B — VACUOUS, and doubly so. The permission key itself does not exist: - // there is no permission system until Phase 03, and no production caller enters - // the scope at all. What can be asserted now is that no second gate - // implementation has appeared to sit beside the deny-all one, because that is how - // a permissive default arrives — registered somewhere else, for a demo. - // Swept across every production assembly, not just the one declaring the - // interface. The first version scanned typeof(IPlatformAdminGate).Assembly — - // SharedKernel — so a permissive gate in Infrastructure or Api, which is exactly - // where "registered elsewhere for a demo" would put one, was invisible to the - // rule whose own message names that scenario. The mutation that was supposed to - // prove this leg passed only because the probe was planted in SharedKernel too. - var gates = ProductionAssemblies() - .SelectMany(assembly => assembly.GetTypes()) - .Where(type => type is { IsAbstract: false, IsInterface: false }) - .Where(typeof(IPlatformAdminGate).IsAssignableFrom) - .Select(type => type.Name) - .Distinct() - .ToList(); + // Conjunct A — the scope takes an admission and nothing else. ADR-0036 asks for the + // permission to be "checked before the scope opens"; ADR-0101 § 7 makes that a type: + // the only way to hold a PlatformAdmission is to have passed the gate, so entry + // cannot happen unadmitted. The ORDER — before the credential is touched — is asserted + // behaviourally in PlatformAdminGateTests, which a structural test cannot see. + typeof(IPlatformAdminScope).GetMethod(nameof(IPlatformAdminScope.EnterAsync))! + .GetParameters()[0].ParameterType.Should().Be( + "entry takes the gate's proof and no caller-supplied reason or flag"); + + // Conjunct B — the admission census is closed. Swept across every production + // assembly, not just the one declaring the types: a permissive minter or gate would + // be registered somewhere else, for a demo, and that is exactly where a narrowed scan + // would not look. Test assemblies are not scanned, so a test double does not widen it. + // Abstract subclasses count: a census that skipped them would let a permissive abstract minter + // stand in the assembly for a test or a later edit to complete. Full names, not simple ones, + // so a lookalike in another namespace is a different (and failing) entry. + var types = ProductionAssemblies().SelectMany(assembly => assembly.GetTypes()) + .Where(type => !type.IsInterface).ToList(); + + FullNames(types, typeof(PlatformAdmission.Minter)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGate"], + "only the gate mints an admission, after it has evaluated a grant"); + FullNames(types, typeof(PlatformOperatorWitness.Minter)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorTokenProfile+WitnessMinter"], + "only the operator token profile mints a witness, through a private nested minter; the offline rebind " + + "tool is a second caller of the profile, not a second minter (ADR-0101 § 7, ADR-0104 § 3)"); + FullNames(types, typeof(IPlatformOperatorGate)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGate"], + "a second gate is how a permissive default ships"); + FullNames(types, typeof(IPlatformOperatorGrantSource)).Should().BeEquivalentTo( + ["LearnStack.Infrastructure.PlatformOperator.ConfigurationPlatformOperatorGrantSource"], + "a second grant source is how a permissive grant ships; the table adapter joins on its trigger"); + } + + [Fact] + public void The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only() + { + // The witness is evidence that a token passed the profile. TryRead is the only door to the + // minter, so who may call it is the question: the scheme's TokenValidated event, and the offline + // validator the rebind tool drives (ADR-0101 § 7: two callers, one validator), and nothing else in + // production code. The profile's own file names it too, because it defines it. + const string Scheme = "LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs"; + const string Offline = "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs"; + const string Profile = "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenProfile.cs"; + + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorTokenProfile", except: null) + .Should().BeEquivalentTo([Scheme, Offline, Profile], "no other source file may name the profile that mints a witness"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorTokenProfile.TryRead(", except: null) + .Should().BeEquivalentTo([Scheme, Offline], "only the two sanctioned callers read a token through the profile"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorWitness.Minter", except: null) + .Should().BeEquivalentTo([Profile], "the witness minter base is named by its one nested subclass"); + } + + [Fact] + public void The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool() + { + // ADR-0104 § 2: the sixth role's connection string exists only in the offline tool's environment, so no runtime + // host can change the issuer whatever it does. Every spelling of the key, in code with comments stripped, is + // confined to the one tool file that reads it, and that file must name it, or the scan could pass over nothing. + const string Tool = "LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs"; + string[] spellings = ["ConnectionStrings__IdentityRebind", "ConnectionStrings:IdentityRebind", "GetConnectionString(\"IdentityRebind\")"]; + + foreach (var spelling in spellings) + { + SourceScan.FilesContaining(SourceScan.SourceRoot, spelling, except: Tool) + .Should().BeEmpty($"the rebind credential '{spelling}' is read by the tool alone"); + } + + SourceScan.FilesContaining(SourceScan.SourceRoot, "ConnectionStrings__IdentityRebind", except: null) + .Should().Equal([Tool], "the tool reads the credential from its environment, and the scan matched it"); + + // A planted negative control: a second reader anywhere else is found. + var planted = Directory.CreateTempSubdirectory("rebind-key-"); + try + { + File.WriteAllText( + Path.Combine(planted.FullName, "Leak.cs"), + "class Leak { string S => System.Environment.GetEnvironmentVariable(\"ConnectionStrings__IdentityRebind\"); }"); + SourceScan.FilesContaining(planted.FullName, "ConnectionStrings__IdentityRebind", except: null) + .Should().Equal(["Leak.cs"]); + } + finally + { + planted.Delete(recursive: true); + } + + // No compose service, demo launcher or migration script forwards it to anything else. + foreach (var path in new[] { "scripts/demo.mjs", "scripts/demo-database.mjs", "scripts/migrate.mjs", "infra/compose/dev.yml", "infra/compose/e2e.yml" }) + { + File.ReadAllText(Path.Combine(RepositoryPaths.RepoRoot(), path.Replace('/', Path.DirectorySeparatorChar))) + .Should().NotContain("ConnectionStrings__IdentityRebind", $"{path} never carries the rebind credential"); + } + } + + [Fact] + public void Only_The_Operator_Services_Hold_The_Platform_Scope() + { + // The scope is reachable from the services that perform an admitted operator act and + // from nowhere else. A request handler holding it would enter a cross-tenant scope + // from a tenant request path, which the marker rules forbid for a platform entry. + SourceScan.FilesContaining(SourceScan.SourceRoot, "IPlatformAdminScope", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs", + ScopeFile, + CompositionFile, + KillswitchWriterFile, + DeliveryInspectionFile, + FederationOperationsFile, + ], + "each new operator service is added here deliberately, with its denied proof"); + } + + [Fact] + public void Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act() + { + // ADR-0102: the executor is the one place an operator's tenant reaches the pipeline, and an admission is + // the only thing that lets it run. The files that name it in code are the executor, the registration beside + // the source it enters and the onboarding routes, and nothing else: a second caller is a second route to an + // act, and is added here deliberately with its own denied proof. + SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorActExecutor", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs", + "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs", + ], + "each new caller of an operator act is added here deliberately, with its denied proof"); + } + + [Fact] + public void Only_The_Recovery_Routes_And_Their_Owners_Name_The_Operator_Recovery_And_Inspection_Ports() + { + // ADR-0103: the two fenced transitions and the inspection are reachable from the recovery routes alone. The + // files that name a port are the port, its one implementation, the registration beside the source it enters and + // the routes, and nothing else: a second caller is a second route to a reset, added here with its denied proof. + SourceScan.FilesContaining(SourceScan.SourceRoot, "IOperatorRecovery", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IOperatorRecovery.cs", + "LearnStack.Infrastructure/Messaging/OperatorRecovery.cs", + "LearnStack.Api/Composition/OutboxCompositionExtensions.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs", + ], + "each new caller of a recovery transition is added here deliberately, with its denied proof"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "IDeliveryInspection", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IDeliveryInspection.cs", + DeliveryInspectionFile, + "LearnStack.Api/Composition/PersistenceCompositionExtensions.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs", + ], + "each new caller of the inspection is added here deliberately, with its denied proof"); + } + + [Fact] + public void Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Operator_Ports() + { + // ADR-0099 Amendment 10: the report, the remove and the disable are reachable from the federation routes alone, + // through the one owner, and the operator's provider port is held by that owner and the adapter that implements + // it. The tenant runner holds neither, so the rule that the tenant's provider port is the runner's alone stands. + // The scan names the owner's class, not only its port: every file naming the interface names this substring too, so a + // holder of the concrete owner is found as well. + SourceScan.FilesContaining(SourceScan.SourceRoot, "FederationBrokerOperations", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IFederationBrokerOperations.cs", + FederationOperationsFile, + "LearnStack.Api/Composition/PersistenceCompositionExtensions.cs", + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Federation.cs", + ], + "each new caller of a federation operator act is added here deliberately, with its denied proof"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "IFederationOperator", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Identity/IFederationOperator.cs", + FederationOperationsFile, + "LearnStack.Infrastructure/Identity/Federation/KeycloakFederationProvider.cs", + "LearnStack.Infrastructure/Identity/Federation/FederationAdapterFactory.cs", + "LearnStack.Api/Composition/FederationComposition.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs", + ], + "the operator's provider port is held by the owner, its adapter and the composition that selects it"); + } + + [Fact] + public void The_Federation_Port_Census_Finds_A_Planted_Holder_Of_Either_Port_Or_The_Concrete_Owner() + { + var planted = Directory.CreateTempSubdirectory("federation-holder-"); + try + { + File.WriteAllText(Path.Combine(planted.FullName, "ViaPort.cs"), "class A(IFederationBrokerOperations operations) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaOwner.cs"), "class B(FederationBrokerOperations owner) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaProvider.cs"), "class C(IFederationOperator provider) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "Clean.cs"), "class D(IFederationProvider tenantProvider) { }"); + + SourceScan.FilesContaining(planted.FullName, "FederationBrokerOperations", except: null) + .Should().BeEquivalentTo(["ViaPort.cs", "ViaOwner.cs"]); + SourceScan.FilesContaining(planted.FullName, "IFederationOperator", except: null).Should().BeEquivalentTo(["ViaProvider.cs"]); + } + finally + { + planted.Delete(recursive: true); + } + } - gates.Should().BeEquivalentTo( - [nameof(DenyAllPlatformAdminGate)], - "Phase 03 replaces this one; a second implementation appearing before then is " - + "how 'permissive to unblock a demo' gets shipped"); + private const string FederationOperationsFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs"; + + private const string KillswitchWriterFile = + "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs"; + + private const string DeliveryInspectionFile = + "LearnStack.Infrastructure/PlatformOperator/DeliveryInspection.cs"; + + [Fact] + public void Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer() + { + // ADR-0101 § 13: the overlay reads the table, so a rule on every mention would be wrong; the + // confinement is on the write verbs, in any case, with an optional schema and quotes. The + // writer inserts the default row, locks it and updates it, so those two verbs must be present + // and DELETE and TRUNCATE must stay absent everywhere (the tests that clean up use the scope, + // outside backend/src). + var offenders = new List(); + var sawWriter = false; + foreach (var file in Directory.EnumerateFiles(SourceScan.SourceRoot, "*.cs", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(SourceScan.SourceRoot, file).Replace(Path.DirectorySeparatorChar, '/'); + if (relative.Split('/') is var segments && (segments.Contains("obj") || segments.Contains("bin"))) + { + continue; + } + + var code = SourceText.WithoutComments(File.ReadAllText(file)); + if (KillswitchWrite().IsMatch(code)) + { + offenders.Add(relative); + sawWriter |= relative == KillswitchWriterFile; + } + } + + sawWriter.Should().BeTrue("the premise: the sweep read the writer's own statements"); + offenders.Should().Equal([KillswitchWriterFile], "the writer alone writes the table"); + + var writer = SourceText.WithoutComments(File.ReadAllText( + Path.Combine(SourceScan.SourceRoot, KillswitchWriterFile.Replace('/', Path.DirectorySeparatorChar)))); + KillswitchWrite().Matches(writer).Select(match => match.Groups["verb"].Value.ToUpperInvariant().Split(' ')[0]) + .Distinct().Should().BeEquivalentTo(["INSERT", "UPDATE"], "the writer never deletes or truncates"); } + [Fact] + public void The_Killswitch_Write_Pattern_Can_Fail_And_Catches_The_Ordinary_Spellings() + { + // The rule above passes whether its pattern works or matches nothing, so the shapes it must + // catch and the ones it must not are checked against the pattern directly. + foreach (var caught in new[] + { + "INSERT INTO platform_killswitches (key) VALUES (@k)", + "insert into platform_killswitches", + "UPDATE platform_killswitches SET is_enabled = true", + "update only public.platform_killswitches set x = 1", + "UPDATE \"public\".\"platform_killswitches\" SET x = 1", + "DELETE FROM platform_killswitches", + "delete from only \"platform_killswitches\"", + "TRUNCATE platform_killswitches", + "truncate table public.platform_killswitches", + }) + { + KillswitchWrite().IsMatch(caught).Should().BeTrue(caught); + } + + foreach (var ignored in new[] + { + "SELECT is_enabled FROM platform_killswitches WHERE key = @k FOR UPDATE", + "INSERT INTO platform_killswitches_archive (key) VALUES (@k)", + "UPDATE platform_killswitches2 SET x = 1", + "GRANT SELECT, INSERT, UPDATE ON platform_killswitches TO learnstack_platform", + }) + { + KillswitchWrite().IsMatch(ignored).Should().BeFalse(ignored); + } + } + + [GeneratedRegex( + @"\b(?INSERT\s+INTO|UPDATE|DELETE\s+FROM|TRUNCATE(?:\s+TABLE)?)(?:\s+ONLY)?\s+(?:""?[A-Za-z_][A-Za-z0-9_]*""?\s*\.\s*)?""?platform_killswitches""?(?![A-Za-z0-9_])", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)] + private static partial Regex KillswitchWrite(); + + private static List FullNames(IEnumerable types, Type baseType) => + types.Where(type => type != baseType && baseType.IsAssignableFrom(type)) + .Select(type => type.FullName!).Distinct().ToList(); + [Fact] public void The_Platform_Scope_Writes_No_Tenant_Context_And_Sets_No_Session_Variable() { // Two closed sets it must stay outside of, both stated in Accepted ADRs. It is - // not one of the four writers of ITenantContextAccessor.Current — ADR-0036 names + // not one of the writers of ITenantContextAccessor.Current — ADR-0036 names // it as explicitly not one — and it is not a ninth setter of app.tenant_id beside // ADR-0040's eight, because the role bypasses policies and there is nothing to // announce to. SetTenant_Callers_Are_The_Enumerated_Four covers the first diff --git a/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs index 35c2ac4dd..acf570532 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs @@ -52,8 +52,11 @@ private static void CheckCleanupConnectionOwner(SortedSet offenders, Pro RequireBoundaryMethod(offenders, owner, "RecordCommitFailure", "System.Void", MethodAttributes.Assembly, "System.Exception"); RequireBoundaryMethod(offenders, owner, "ConfirmCommitOutcome", "System.Void", MethodAttributes.Assembly); var terminal = callers.Single(caller => caller.Contains("::TryTerminalizeAsync(", StringComparison.Ordinal)); + // ADR-0103: the operator's reset or replay core records its own uncertain COMMIT once. + var recovery = callers.Single(caller => caller.Contains("::ReplayCoreAsync(", StringComparison.Ordinal) + || caller.Contains("::ResetCoreAsync(", StringComparison.Ordinal)); CheckCallers(owner, "get_Slot", [release, release, retain]); - CheckCallers(owner, "RecordCommitFailure", [terminal, terminal]); + CheckCallers(owner, "RecordCommitFailure", [terminal, terminal, recovery]); CheckCallers(owner, "ConfirmCommitOutcome", [terminal]); } diff --git a/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs b/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs index 982e76efc..c2eff7452 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PublicSurfaceTests.cs @@ -305,7 +305,15 @@ internal static bool SkipValue(Mono.Collections.Generic.Collection .Where(type => type.IsDefined(typeof(PublicSurfaceAttribute), false)) .Select(type => type.FullName!).ToHashSet(StringComparer.Ordinal); - private static IEnumerable MinimalBypasses(ModuleDefinition module) => Types([module]).Where(type => + // The platform operator surface (ADR-0101 § 4) is its own closed surface with its own scheme: minimal + // endpoints in a group, one verb, one policy, one fixed metadata. It is excluded by exact type (and the + // compiler's nested types of it), so a mapping anywhere else is still a bypass; its own population is + // asserted in PlatformOperatorHttpTests. + private const string OperatorSurface = "LearnStack.Api.Platform.PlatformOperatorEndpoints"; + + private static IEnumerable MinimalBypasses(ModuleDefinition module) => Types([module]) + .Where(type => type.FullName != OperatorSurface && !type.FullName.StartsWith(OperatorSurface + "/", StringComparison.Ordinal)) + .Where(type => { var methods = Il.Methods(type).Where(method => method.Definition.HasBody).ToArray(); var composition = methods.SelectMany(method => method.Definition.Body.Instructions diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs index f9e7fbf0a..9d090183f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs @@ -174,7 +174,10 @@ public void SetTenant_Callers_Are_The_Enumerated_Four() // handler scope (integration events). HTTP and the acceptance/execution // halves of the integration-event scope and the job executor exist today; // the rule is written over the whole set so the next writer is a deliberate edit here rather - // than a silent addition there. + // than a silent addition there. The operator act executor (ADR-0102, ADR-0036 Amendment 22) + // is that deliberate edit: a fifth logical writer, which installs the resolved context + // of the tenant an admitted operator act names. The method keeps the name three Accepted + // ADRs and the catalogue cite. // // The needle is receiver-agnostic — a future `Activity.Current =` anywhere in // backend/src would trip this, which is a false positive to exempt by path @@ -212,10 +215,11 @@ public void SetTenant_Callers_Are_The_Enumerated_Four() "LearnStack.Infrastructure/Jobs/JobExecutor.ExternalCheckpoints.cs", "LearnStack.Infrastructure/Jobs/JobExecutor.External.cs", "LearnStack.Infrastructure/Jobs/JobExecutor.Recipients.cs", + "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs", ], - "three of the four logical writers have landed — HTTP, jobs and the integration-event " - + "acceptance/execution scopes; all JobExecutor partials belong to one logical writer. " - + "HubCorrelationMiddleware belongs to its later phase; a fifth writer is how a " + "four of the five logical writers have landed — HTTP, jobs, the integration-event " + + "acceptance/execution scopes and the operator act executor; all JobExecutor partials belong to one " + + "logical writer. HubCorrelationMiddleware belongs to its later phase; a sixth writer is how a " + "request runs under a tenant nothing resolved"); } diff --git a/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs index 0414690de..4c404bc95 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TrustedOperationSourceConventionTests.cs @@ -13,6 +13,8 @@ public sealed class TrustedOperationSourceConventionTests private const string Seed = "LearnStack.Tools.Seeder.SeedOperationSource"; private const string Delivery = "LearnStack.Infrastructure.Messaging.DeliveryOperationSource"; private const string Job = "LearnStack.Application.Jobs.BackgroundJobOperationSource"; + private const string Operator = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorOperationSource"; + private const string OperatorExecutor = "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorActExecutor"; private const string Admission = "LearnStack.Application.Jobs.BackgroundJobExecutionAdmission"; private const string JobOwner = "LearnStack.SharedKernel.Jobs.JobApplicationSourceOwner"; @@ -20,7 +22,8 @@ public sealed class TrustedOperationSourceConventionTests public void Finite_operation_descriptors_have_exact_minters_private_construction_and_revocable_evidence() { using var census = Census.Read(); - Offenders(census).Should().BeEmpty("Fix: preserve the exact owned seed/delivery/job source set and its closed lifetime (ADR-0076)"); + Offenders(census).Should().BeEmpty( + "Fix: preserve the exact owned seed/delivery/job/operator source set and its closed lifetime (ADR-0076, ADR-0102)"); var descriptor = census.Type(Descriptor); Dirty(census, () => { @@ -53,9 +56,11 @@ public void Finite_operation_descriptors_have_exact_minters_private_construction (Delivery, "IsEvidenceCurrent", "LearnStack.SharedKernel.Persistence.IUnitOfWork", "GetTenantContextAnnouncement"), (Admission, "IsOperationEvidenceCurrent", JobOwner, "get_IsCurrentBinding"), (Admission, "IsOperationEvidenceCurrent", Admission, "IsLive"), + (Operator, "IsEvidenceCurrent", "LearnStack.SharedKernel.Tenancy.ITenantContextAccessor", "get_Current"), + (Operator, "Capture", "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorActCatalog", "TryGet"), }) Dirty(census, () => RemoveCall(census.Body(type, method), target, name)); foreach (var (typeName, methodName) in new[] - { (Delivery, "Enter"), ("LearnStack.SharedKernel.Permissions.ITrustedOperationSource", "Capture") }) + { (Delivery, "Enter"), (Operator, "Enter"), ("LearnStack.SharedKernel.Permissions.ITrustedOperationSource", "Capture") }) foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) Dirty(census, () => { var module = census.Type(Seed).Module; @@ -74,17 +79,18 @@ private static List Offenders(Census census) var descriptor = census.Type(Descriptor); var constructors = descriptor.Methods.Where(method => method.IsConstructor).ToArray(); if (!descriptor.IsSealed || !descriptor.IsPublic || constructors.Length != 1 || !constructors[0].IsPrivate - || descriptor.Fields.Count != 5 || descriptor.Fields.Any(field => !field.IsPrivate || !field.IsInitOnly || field.IsStatic) + || descriptor.Fields.Count != 6 || descriptor.Fields.Any(field => !field.IsPrivate || !field.IsInitOnly || field.IsStatic) || descriptor.Properties.Any(property => property.SetMethod is not null) || !Same(descriptor.Fields.Select(field => field.Name), ["_source", "_context", "_evidence", - "k__BackingField", "k__BackingField"])) + "k__BackingField", "k__BackingField", "k__BackingField"])) errors.Add("The immutable descriptor has only private closed construction and exact evidence fields"); - if (!Same(census.Types.Where(type => type.BaseType?.FullName == Minter).Select(type => type.FullName), [Seed, Delivery, Job])) - errors.Add("Only the three enumerated owners derive the finite descriptor source"); + if (!Same(census.Types.Where(type => type.BaseType?.FullName == Minter).Select(type => type.FullName), [Seed, Delivery, Job, Operator])) + errors.Add("Only the four enumerated owners derive the finite descriptor source"); foreach (var instruction in census.Methods.SelectMany(method => method.Body.Instructions)) if (instruction.Operand is MethodReference target && (target.DeclaringType.FullName == Descriptor && target.Name == ".ctor" || target.DeclaringType.FullName == Minter && target.Name == "ForOperation" || target.DeclaringType.FullName == Delivery && target.Name == "Enter" + || target.DeclaringType.FullName == Operator && target.Name == "Enter" || target.DeclaringType.FullName == Admission && target.Name == "CaptureOperationEvidence" || target.DeclaringType.FullName == "LearnStack.SharedKernel.Permissions.ITrustedOperationSource" && target.Name == "Capture") && instruction.OpCode.Code is not (Code.Call or Code.Callvirt or Code.Newobj)) @@ -93,7 +99,9 @@ private static List Offenders(Census census) Exact(Seed, ".ctor", ["LearnStack.Tools.Seeder.SeedComposition::Build"]); Exact(Delivery, ".ctor", []); Exact(Job, ".ctor", []); - Exact(Minter, "ForOperation", [Seed + "::Capture", Delivery + "::Capture", Job + "::Capture"]); + Exact(Operator, ".ctor", []); + Exact(Minter, "ForOperation", [Seed + "::Capture", Delivery + "::Capture", Job + "::Capture", Operator + "::Capture"]); + Exact(Operator, "Enter", [OperatorExecutor + "::ExecuteAsync"]); Exact(Delivery, "Enter", ["LearnStack.Infrastructure.Messaging.DeliveryExecutor::ExecuteOwnedAsync"]); Exact(Admission, "CaptureOperationEvidence", [Job + "::Capture"]); Exact(Admission, "IsOperationEvidenceCurrent", [Admission + "::CaptureOperationEvidence", Job + "::IsEvidenceCurrent"]); @@ -106,6 +114,8 @@ private static List Offenders(Census census) Require(Delivery, "IsEvidenceCurrent", "LearnStack.SharedKernel.Persistence.IUnitOfWork", "GetTenantContextAnnouncement"); Require(Admission, "IsOperationEvidenceCurrent", JobOwner, "get_IsCurrentBinding"); Require(Admission, "IsOperationEvidenceCurrent", Admission, "IsLive"); + Require(Operator, "IsEvidenceCurrent", "LearnStack.SharedKernel.Tenancy.ITenantContextAccessor", "get_Current"); + Require(Operator, "Capture", "LearnStack.Infrastructure.PlatformOperator.PlatformOperatorActCatalog", "TryGet"); if (Calls(census.Body(Admission, "CaptureOperationEvidence")).Any(target => target.DeclaringType.FullName == Admission && target.Name is "TryEnterRequest" or "PermitsRequest")) errors.Add("Capturing job evidence never repeats root or nested request admission"); diff --git a/backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs new file mode 100644 index 000000000..b138962ca --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobCapacity.cs @@ -0,0 +1,15 @@ +using LearnStack.Infrastructure.Jobs; + +namespace LearnStack.Tests.Integration; + +/// +/// The smallest Maximum Pool Size the default background-job topology accepts. The +/// fixtures derive it from the production manifest instead of repeating a literal, so a +/// new connection slot in a messaging store or the job runtime cannot leave a test below +/// the floor. The literal is pinned once, in BackgroundJobPhysicalCapacityTests. +/// +internal static class BackgroundJobCapacity +{ + public static readonly int Floor = BackgroundJobPhysicalCapacity + .Calculate(BackgroundJobInfrastructureRegistry.CreateDefault()).RequiredConnections; +} diff --git a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs index dd4f319e9..6019ffcd2 100644 --- a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs @@ -325,7 +325,7 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(new Dictionary { ["ConnectionStrings:Default"] = "Host=localhost;Port=1;Database=learnstack;Username=learnstack_app;Maximum Pool Size=32", - ["ConnectionStrings:OutboxDispatcher"] = "Host=localhost;Port=1;Database=learnstack;Username=learnstack_outbox_admin;Maximum Pool Size=52", + ["ConnectionStrings:OutboxDispatcher"] = $"Host=localhost;Port=1;Database=learnstack;Username=learnstack_outbox_admin;Maximum Pool Size={BackgroundJobCapacity.Floor}", })); builder.ConfigureTestServices(collection => { diff --git a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs index fad7a5b50..c6a19df9d 100644 --- a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs +++ b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs @@ -25,6 +25,15 @@ protected sealed override void ConfigureWebHost(IWebHostBuilder builder) { ArgumentNullException.ThrowIfNull(builder); InvitationEmailFixtureConfiguration.AddTo(builder); + // Development configuration carries an operator issuer for the real developer stack + // (ADR-0101 § 12). A test host starts without one, so the tenant boundary is judged on its + // own; a case about the operator surface sets the issuer itself, after this line. + builder.UseSetting("PlatformOperator:Issuer", string.Empty); + // Development also grants the exported demo operator, which the grant validator refuses + // outside Development, and these hosts run under several modes. Pointing the one entry at a + // subject nobody holds keeps the grant list valid and matches no one. + builder.UseSetting("PlatformOperator:Grants:0:Subject", "test-host-matches-no-operator"); + builder.UseSetting("PlatformOperator:Grants:0:Permissions:0", "platform.killswitch.write"); ConfigureTestHost(builder); builder.ConfigureTestServices(services => { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs index b236ed304..93d3c6279 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.Callbacks.cs @@ -18,7 +18,6 @@ public async Task DTO_construction_and_attempt_ID_factory_cannot_open_ordinary_o await BackgroundJobSchemaSeed.SeedTenantsAsync(database.AppConnectionString); var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); var probe = new BackgroundJobFixtureProbe(); - var gate = new PermissiveGate(); var ids = new CallbackGuidFactory(); var callbacks = 0; var constructor = Fixture.ParameterType.GetField("OnConstruction")!; @@ -46,7 +45,6 @@ Action For(IServiceProvider services) => () => { observation.Configure(services); services.AddSingleton(ids); - services.AddSingleton(gate); }); try { @@ -55,7 +53,6 @@ Action For(IServiceProvider services) => () => result.Outcome.Should().Be(JobStartExecutionOutcome.Started); callbacks.Should().BeGreaterThan(0, "the callback must actually run in the production DTO/factory path"); probe.Constructions.Should().BeEmpty(); - gate.Calls.Should().Be(0, "privileged refusal precedes the deliberately permissive gate"); (await BackgroundJobRuntimeRows.CountAttemptsAsync(database.AppConnectionString, job)).Should().Be(1); } finally diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs index 4c165671a..ba366e599 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobAdmissionTests.cs @@ -110,7 +110,6 @@ public async Task The_preread_is_physically_readonly_RLS_scoped_and_framework_au BackgroundJobRuntimeFixture.OrganizationKey, SchemaFixture.OrgA2); var otherTenant = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, tenant: SchemaFixture.TenantB); var probe = new BackgroundJobFixtureProbe(); - var gate = new PermissiveGate(); var reads = 0; var starts = 0; var observation = new BackgroundJobAdmissionObservation @@ -136,16 +135,13 @@ public async Task The_preread_is_physically_readonly_RLS_scoped_and_framework_au await using var host = Fixture.Host(database, probe, configure: services => { observation.Configure(services); - services.AddSingleton(gate); }); - (await gate.IsPermittedAsync("positive-control")).Should().BeTrue(); var claim = (await host.Services.GetRequiredService().TryClaimAsync(job, 1))!; (await host.Services.GetRequiredService().ExecuteAsync(claim, BackgroundJobTestRun.Create())).Outcome.Should().Be(JobStartExecutionOutcome.Started); reads.Should().Be(1); starts.Should().Be(1); observation.ReadScopeDisposed.Should().BeTrue(); observation.StartScopeDisposed.Should().BeTrue(); - gate.Calls.Should().Be(1, "the sticky ceiling refuses privileged scope entry before even a permissive gate"); probe.Constructions.Should().BeEmpty(); } @@ -293,7 +289,7 @@ private static async Task AssertFrameworkCeilingAsync(IServiceProvider services, unit.IsRollbackOnly.Should().BeFalse(); (await Fixture.SendAsync(services)).IsFailure.Should().BeTrue("accessor replacement cannot remove framework confinement"); probe.Constructions.Should().BeEmpty("ordinary handler construction follows admission"); - await FluentActions.Awaiting(() => services.GetRequiredService().EnterAsync("framework-proof")) + await FluentActions.Awaiting(() => services.GetRequiredService().EnterAsync(LearnStack.Tests.Fixtures.TestPlatformAdmissions.Admission())) .Should().ThrowAsync().WithMessage("*background-job authority*"); var privileged = services.GetRequiredKeyedService(OutboxDispatcherDataSource.Key); await FluentActions.Awaiting(async () => await privileged.OpenConnectionAsync()) @@ -311,13 +307,6 @@ private static async Task ProveReadOnlyWriteRefusalAsync(IUnitOfWork unit, Backg await SchemaQueries.ExecuteAsync(unit.Connection, unit.Transaction, "ROLLBACK TO SAVEPOINT readonly_probe"); } - private sealed class PermissiveGate : IPlatformAdminGate - { - internal int Calls { get; private set; } - public ValueTask IsPermittedAsync(string reason, CancellationToken cancellationToken = default) - { Calls++; return ValueTask.FromResult(true); } - } - private sealed class ProvisioningProbe : IProvisionsTenant { public TenantId ProvisioningTenantId => TenantId.From(SchemaFixture.TenantA); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs index 60c4bb24b..187d31216 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobGrantExpectations.cs @@ -13,8 +13,19 @@ internal static class BackgroundJobGrantExpectations _ => "DELETE,SELECT", }))); + /// The metadata of a job an operator may inspect: no parameter, plan, trace, causal or capability column. + public const string PlatformJobMetadataColumns = + "id tenant_id organization_id definition_key profile queue capacity_group original_due_at created_at phase " + + "normal_attempts finalize_attempts available_after ownership_kind ownership_until attempt_deadline probe_after " + + "unsuccessful_probes last_error quarantine_reason terminal_reason processed_at dead_lettered_at " + + "finalization_status finalization_reason business_finalization_incomplete wake_generation"; + public static string[] Columns(string role, string table, string privilege, IEnumerable allColumns) { + // ADR-0103: the platform role reads every reservation column, and nothing else of the job tables is exposed to it + // beyond the named metadata of background_jobs below. + if (privilege == "SELECT" && role == "learnstack_platform" && table == "background_job_reservations") + return allColumns.ToArray(); if (privilege == "SELECT" && (role == "learnstack_app" && SchemaTableClasses.JobTenant.Contains(table) || role == "learnstack_outbox_admin" && table is "background_job_capacity" or "background_job_reservations" @@ -26,6 +37,7 @@ public static string[] Columns(string role, string table, string privilege, IEnu "id tenant_id organization_id definition_key profile queue capacity_group parameters original_due_at traceparent causal_actor_user_id causation_event_id parent_job_id recipient_id", ("learnstack_app", "background_jobs", "UPDATE") => "phase normal_attempts finalize_attempts current_attempt_id attempt_deadline plan plan_fingerprint prepared_at operation_id final_outcome_attempt_id finalization_status finalization_reason processed_at terminal_reason dead_lettered_at", + ("learnstack_platform", "background_jobs", "SELECT") => PlatformJobMetadataColumns, ("learnstack_app", "background_job_attempts", "INSERT") => "id tenant_id organization_id job_id stage ordinal admission_token deadline final_outcome_attempt_id", ("learnstack_app", "background_job_attempts", "UPDATE") => diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs index 0354e216a..6a06c8a63 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.NativeFlow.cs @@ -39,7 +39,7 @@ public async Task Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_ }, applicationPoolSize: 32); var bounds = host.Services.GetRequiredService(); var dispatcherConnection = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52 }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }.ConnectionString; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(dispatcherConnection)); using var globals = new NativeSdkGlobalFilterSnapshot(); var gate = new BackgroundJobRuntimeGate(Fixture.Registry.Infrastructure); @@ -47,7 +47,7 @@ public async Task Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_ var runtime = new BackgroundJobRuntime(source, Fixture.Registry, BackgroundJobRecurrenceRegistry.CreateEmpty(), host.Services.GetRequiredService(), new(source, Fixture.Registry, bounds, ids, gate), gate, bounds, ids, TimeProvider.System, - new(true, 52), new HangfireBoundedLogProvider(), host.Services.GetRequiredService()); + new(true, BackgroundJobCapacity.Floor), new HangfireBoundedLogProvider(), host.Services.GetRequiredService()); // Construction-only host removed both messaging workers; neither issued work. runtime.BindMessagingLifetime(Task.CompletedTask, Task.CompletedTask); var submitted = await Fixture.SubmitAsync(host.Services, Fixture.Parameters(resource, prepared, finalized)); @@ -64,7 +64,7 @@ public async Task Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_ { var settings = new NpgsqlConnectionStringBuilder(physical.ConnectionString); settings.Pooling.Should().BeTrue(); - settings.MaxPoolSize.Should().Be(52); + settings.MaxPoolSize.Should().Be(BackgroundJobCapacity.Floor); } var waiting = Stopwatch.StartNew(); // A successor hint may finish before the original Outcome cleanup diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs index d0882f052..b6f9fe4df 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.RecoveryWakes.cs @@ -165,14 +165,14 @@ public async Task Actual_facade_parks_expired_external_work_reconciles_or_uses_r }, applicationPoolSize: 32); var bounds = host.Services.GetRequiredService(); var dispatcherConnection = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52 }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }.ConnectionString; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(dispatcherConnection)); using var globals = new NativeSdkGlobalFilterSnapshot(); var gate = new BackgroundJobRuntimeGate(Fixture.Registry.Infrastructure); var ids = new SystemGuidFactory(); var runtime = new BackgroundJobRuntime(source, Fixture.Registry, BackgroundJobRecurrenceRegistry.CreateEmpty(), host.Services.GetRequiredService(), new(source, Fixture.Registry, bounds, ids, gate), - gate, bounds, ids, TimeProvider.System, new(true, 52), new HangfireBoundedLogProvider(), + gate, bounds, ids, TimeProvider.System, new(true, BackgroundJobCapacity.Floor), new HangfireBoundedLogProvider(), host.Services.GetRequiredService()); runtime.BindMessagingLifetime(Task.CompletedTask, Task.CompletedTask); try @@ -186,7 +186,7 @@ public async Task Actual_facade_parks_expired_external_work_reconciles_or_uses_r { var settings = new NpgsqlConnectionStringBuilder(physical.ConnectionString); settings.Pooling.Should().BeTrue(); - settings.MaxPoolSize.Should().Be(52); + settings.MaxPoolSize.Should().Be(BackgroundJobCapacity.Floor); } var waiting = Stopwatch.StartNew(); var completionBudget = bounds.HandoffRepairGrace + bounds.TransactionTimeout + bounds.SqlTimeout * 2 + bounds.ControlPoll * 2; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs index c565cb474..e4f60321b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobPositiveSdkTests.SourceContention.cs @@ -99,14 +99,14 @@ public async Task Native_transactional_pool_completes_at_the_app_source_floor_wh }, applicationPoolSize: 32, reconcileProbe: reconcile, componentRequests: [transactional.RequestType("Submit")]); var lifetime = host.Services.GetRequiredService(); var privilegedConnection = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52 }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }.ConnectionString; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(privilegedConnection)); using var globals = new NativeSdkGlobalFilterSnapshot(); var gate = new BackgroundJobRuntimeGate(registry.Infrastructure); var ids = new SystemGuidFactory(); var runtime = new BackgroundJobRuntime(source, registry, BackgroundJobRecurrenceRegistry.CreateEmpty(), host.Services.GetRequiredService(), new(source, registry, bounds, ids, gate), - gate, bounds, ids, TimeProvider.System, new(true, 52), new HangfireBoundedLogProvider(), lifetime); + gate, bounds, ids, TimeProvider.System, new(true, BackgroundJobCapacity.Floor), new HangfireBoundedLogProvider(), lifetime); // Neither messaging worker starts in the existing construction-only host. runtime.BindMessagingLifetime(Task.CompletedTask, Task.CompletedTask); var submitted = await Fixture.SubmitAsync(host.Services, Fixture.Parameters(resource, prepared, finalized)); @@ -132,7 +132,7 @@ void PreserveFailure(Exception error) lifetime.PoolSettings.Should().Be(new BackgroundJobApplicationPoolSettings(true, 32)); runtime.Snapshot.ApplicationCapacity!.RequiredConnections.Should().Be(32); await using (var physical = await source.OpenConnectionAsync(startup.Token)) - new NpgsqlConnectionStringBuilder(physical.ConnectionString).MaxPoolSize.Should().Be(52); + new NpgsqlConnectionStringBuilder(physical.ConnectionString).MaxPoolSize.Should().Be(BackgroundJobCapacity.Floor); // Execute and the provider journal commit are real. The native recovery // then enters the SDK's post-call barrier, retaining its actual task. boundary = "reconcile_wait"; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs index 56ef3dbca..b187768aa 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.AuxiliaryCleanup.cs @@ -121,7 +121,7 @@ public async Task Native_cache_waiter_timeout_joins_late_actual_auxiliary_cleanu services.AddSingleton>(auditLogger); services.AddSingleton>(reconcileLogger); }); - await using var source = Source(database, new(true, 52)); + await using var source = Source(database, new(true, BackgroundJobCapacity.Floor)); var applicationSource = host.Services.GetRequiredService(); var auditHealth = host.Services.GetRequiredService(); auditHealth.IsHealthy.Should().BeTrue(); @@ -137,7 +137,7 @@ public async Task Native_cache_waiter_timeout_joins_late_actual_auxiliary_cleanu auditListener.SetMeasurementEventCallback((_, count, tags, _) => auditFailures.Enqueue((count, tags.ToArray()))); auditListener.Start(); using var globals = new GlobalFilterSnapshot(); - var runtime = Runtime(host.Services, source, bounds, new(true, 52)); + var runtime = Runtime(host.Services, source, bounds, new(true, BackgroundJobCapacity.Floor)); HangfireGeneration? generation = null; var verified = false; Exception? testFailure = null; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs index 3bacc8327..b0b13011c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs @@ -72,7 +72,7 @@ await SchemaQueries.ExecuteAsync(owner, setup, """ services.RemoveAll(); services.AddSingleton(bounds); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(100)); @@ -168,7 +168,7 @@ public async Task Admitted_native_business_renews_across_local_drain_and_commits services.RemoveAll(); services.AddSingleton(bounds); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(100)); @@ -261,10 +261,10 @@ public async Task Native_business_overrun_and_private_callback_keep_both_sources services.RemoveAll(); services.AddSingleton(bounds); }); - await using var source = Source(database, new(true, 52)); + await using var source = Source(database, new(true, BackgroundJobCapacity.Floor)); var applicationSource = host.Services.GetRequiredService(); using var globals = new GlobalFilterSnapshot(); - var runtime = Runtime(host.Services, source, bounds, new(true, 52)); + var runtime = Runtime(host.Services, source, bounds, new(true, BackgroundJobCapacity.Floor)); using var deadline = new CancellationTokenSource(TestWait); try { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs index c6afac9f4..5cda08b11 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmission.cs @@ -41,7 +41,7 @@ public async Task Native_capacity_completion_releases_with_business_child_outbox services.AddSingleton(bounds); }, appConnectionString: new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 100 }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_commit_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs index 5083088ff..df161896a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityAdmissionRollback.cs @@ -56,7 +56,7 @@ public async Task Native_rolled_back_capacity_admission_joins_after_peer_clears_ services.AddScoped(); }, appConnectionString: new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 100 }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); await using var peerSource = Source(database, physical); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs index 77b0175c1..31ac4ec38 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCheckpoint.cs @@ -36,7 +36,7 @@ public async Task Native_capacity_checkpoint_lost_ACK_uses_exact_committed_clean services.AddSingleton(bounds); }, appConnectionString: new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 100 }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_checkpoint_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs index 0cdd7c808..d412684f4 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityCleanup.cs @@ -104,10 +104,10 @@ public async Task Native_grouped_rollback_checkpoints_only_after_original_auxili services.AddTransient>, CapacityCleanupCheckpointObserver>(); }); - await using var source = Source(database, new(true, 52)); + await using var source = Source(database, new(true, BackgroundJobCapacity.Floor)); var applicationSource = host.Services.GetRequiredService(); using var globals = new GlobalFilterSnapshot(); - var runtime = Runtime(host.Services, source, bounds, new(true, 52)); + var runtime = Runtime(host.Services, source, bounds, new(true, BackgroundJobCapacity.Floor)); var observation = host.Services.GetRequiredService(); using var metrics = new BackgroundJobStageProbe(observation); using var traces = new BackgroundJobTraceProbe(observation); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs index d0301752a..e85437d37 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityControl.cs @@ -32,7 +32,7 @@ public async Task Native_grouped_permanent_refusal_survives_lost_checkpoint_ACK_ services.RemoveAll(); services.AddSingleton(bounds); }, appConnectionString: proxy.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "native_capacity_control_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs index 48005d97f..f887ce27c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityNoStart.cs @@ -94,7 +94,7 @@ public async Task Native_grouped_admission_never_started_releases_only_after_act CommandTimeout = 0, CancellationTimeout = 1000, }.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_no_start_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs index 3184ee066..9111f3873 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityStop.cs @@ -35,7 +35,7 @@ public async Task Native_host_stop_after_recovery_ACK_does_not_issue_capacity_ch }, }; await using var host = CapacityStopHost(database, probe, state, bounds); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "capacity_stop_before_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); @@ -140,7 +140,7 @@ public async Task Native_host_stop_joins_issued_capacity_checkpoint_private_call }, }; await using var host = CapacityStopHost(database, probe, state, bounds); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); var applicationSource = host.Services.GetRequiredService(); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs index 48ff157b1..b12ec2e6a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CapacityTakeover.cs @@ -53,8 +53,8 @@ public async Task Native_capacity_recovery_reprobes_settled_history_after_peer_t }); await using var proxy = new CommitResponseDroppingProxy(database.OutboxConnectionString, commitsToPass: int.MaxValue, lifetime: TimeSpan.FromMinutes(2)); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); - var settings = new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = 52 }; + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); + var settings = new NpgsqlConnectionStringBuilder(proxy.ConnectionString) { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor }; await using var source = new PrivilegedDataSource(() => OutboxDispatcherDataSource.Build(settings.ConnectionString)); await using var peerSource = Source(database, physical); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs index ecd65034b..f5ba26f1a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs @@ -30,7 +30,7 @@ public async Task Supported_pool_serves_native_business_during_combined_actual_m await using var database = await DatabaseAsync(); var applicationName = "combined_capacity_" + Guid.NewGuid().ToString("N"); var connectionString = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) - { Pooling = true, MaxPoolSize = 52, ApplicationName = applicationName }.ConnectionString; + { Pooling = true, MaxPoolSize = BackgroundJobCapacity.Floor, ApplicationName = applicationName }.ConnectionString; var outboxHold = new CombinedTerminalHold(); var deliveryHold = new CombinedTerminalHold(); // Uncommitted unique-key contention identifies the exact stock expiration @@ -90,7 +90,7 @@ await SchemaQueries.ExecuteAsync(blocker, blockedTransaction, await delivery.StartAsync(CancellationToken.None); await jobs.StartAsync(CancellationToken.None); await EventuallyAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy)); - await AssertGuardedPoolAsync(source, new(true, 52)); + await AssertGuardedPoolAsync(source, new(true, BackgroundJobCapacity.Floor)); expiration = ActualExpiration(runtime); await EventuallyAsync(async () => { @@ -121,7 +121,7 @@ await FluentActions.Awaiting(() => expiration.StopAsync(callerWait.Token)) absentOwner.Should().Throw(); var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, tenant: SchemaFixture.TenantB); await EnsureQualificationStartAsync(runtime, source, job, bodyObserved.Task); - (await bodyObserved.Task.WaitAsync(TestWait)).Should().BeInRange(3, 52); + (await bodyObserved.Task.WaitAsync(TestWait)).Should().BeInRange(3, BackgroundJobCapacity.Floor); await EventuallyAsync(async () => (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, job, tenant: SchemaFixture.TenantB))?.Phase == "completed"); await AssertCombinedBusinessAsync(database, organization); @@ -133,7 +133,7 @@ await EventuallyAsync(async () => (await BackgroundJobRuntimeRows.ReadAsync(data AssertCombinedHolds(outboxHold, deliveryHold, expiration, source); await AssertCombinedBackendsAsync(database, applicationName, outboxHold, deliveryHold, expirationPid); runtime.Snapshot.RunningPools.Should().Be(3); - testOutput.WriteLine("Supported52 pool: real expiration + two distinct terminal-scope physical checkouts held; tenantB native business/MUST audit committed before release. Representative contention, not exact52 saturation."); + testOutput.WriteLine("Supported-floor pool: real expiration + two distinct terminal-scope physical checkouts held; tenantB native business/MUST audit committed before release. Representative contention, not exact-floor saturation."); } finally { @@ -171,7 +171,7 @@ private static void AssertCombinedHolds(CombinedTerminalHold outbox, CombinedTer expiration.Should().NotBeNull(); expiration!.Snapshot.Should().BeEquivalentTo(new { State = HangfireSharedComponentState.Retained, Invocations = 1L, OwnsResources = true, ActualJoined = false }); source.Should().NotBeNull(); - PoolStatistics(source!).Busy.Should().BeInRange(3, 52); + PoolStatistics(source!).Busy.Should().BeInRange(3, BackgroundJobCapacity.Floor); } private static async Task CombinedBlockedExpirationPidAsync(DisposableSchemaDatabase database, string applicationName, diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs index 44b852b13..d794e673c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CommitFaults.cs @@ -49,7 +49,7 @@ public async Task Native_lost_business_ACK_retains_the_actual_identity_until_a_l services.RemoveAll(); services.AddSingleton(bounds); }, appConnectionString: appSettings.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "native_commit_probe_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); @@ -164,7 +164,7 @@ public async Task Native_final_completion_rechecks_database_expiry_after_its_rea services.RemoveAll(); services.AddSingleton(bounds); }, appConnectionString: appSettings.ConnectionString); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(TestWait); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs index a720182ee..960b781b3 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ComposedLifetime.cs @@ -40,7 +40,7 @@ public async Task Actual_API_composition_keeps_both_sources_after_host_disposal_ var connectionString = new NpgsqlConnectionStringBuilder(database.OutboxConnectionString) { Pooling = true, - MaxPoolSize = 52, + MaxPoolSize = BackgroundJobCapacity.Floor, ApplicationName = applicationName, }.ConnectionString; var cleanup = new FacadeCleanupSignals(); @@ -83,7 +83,7 @@ public async Task Actual_API_composition_keeps_both_sources_after_host_disposal_ await EventuallyAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy && services.GetRequiredService().IsHealthy && services.GetRequiredService().IsHealthy)); - await AssertGuardedPoolAsync(source, new(true, 52)); + await AssertGuardedPoolAsync(source, new(true, BackgroundJobCapacity.Floor)); (await ServerCountAsync(source)).Should().Be(3); outbox.ExecuteTask.Should().NotBeNull(); delivery.ExecuteTask.Should().NotBeNull(); @@ -142,7 +142,7 @@ await EventuallyAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy await SchemaQueries.AssertApplicationRoleAsync(remaining); source.HasUnconfirmedCleanup.Should().BeFalse("pending scope ownership is not a disposal fault"); PoolStatistics(source).Busy.Should().Be(1); - await AssertGuardedPoolAsync(source, new(true, 52)); + await AssertGuardedPoolAsync(source, new(true, BackgroundJobCapacity.Floor)); PoolStatistics(source).Busy.Should().Be(1); cleanup.Release.TrySetResult(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs index e1df98d45..0dc161f71 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.ControlFailures.cs @@ -43,7 +43,7 @@ public async Task Native_clean_control_lock_timeout_retains_the_permanent_refusa services.RemoveAll(); services.AddSingleton(bounds); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var controlName = "native_control_failure_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, controlName); using var globals = new GlobalFilterSnapshot(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs index 3ee6f5af5..6e4c0bdd1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs @@ -147,7 +147,7 @@ public async Task Actual_common_database_outage_drains_all_pools_and_recovery_ke observation.Configure(services); services.AddScoped(_ => new FacadeHeldReadCleanup(cleanupSignals)); }); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); await using var source = Source(database, physical); using var globals = new GlobalFilterSnapshot(); using var deadline = new CancellationTokenSource(HeartbeatQualificationWait); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs index 8581cf419..7c41ac092 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Lifetime.cs @@ -24,7 +24,7 @@ public sealed partial class BackgroundJobRuntimeFacadeTests public async Task Native_framework_wait_retains_actual_cleanup_and_releases_its_slot_before_host_stop(bool synchronousPrefix) { await using var database = await DatabaseAsync(); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var applicationName = "facade_cleanup_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, applicationName); var cleanup = new FacadeCleanupSignals(); @@ -183,7 +183,7 @@ await FluentActions.Awaiting(() => runtime.StopAsync(callerWait.Token)) public async Task Pooled_boundary_52_keeps_actual_expiration_checkout_after_caller_timeout_while_transactional_admission_progresses() { await using var database = await DatabaseAsync(); - var physical = new BackgroundJobPhysicalPoolSettings(true, 52); + var physical = new BackgroundJobPhysicalPoolSettings(true, BackgroundJobCapacity.Floor); var applicationName = "facade_capacity_" + Guid.NewGuid().ToString("N"); await using var source = Source(database, physical, applicationName); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -211,7 +211,7 @@ await FluentActions.Awaiting(() => expiration.StopAsync(callerWait.Token)) .Should().ThrowAsync(); await EventuallyAsync(() => Task.FromResult(expiration.Snapshot.State == HangfireSharedComponentState.Retained)); expiration.Completion.IsCompleted.Should().BeFalse(); - PoolStatistics(source).Busy.Should().BeInRange(1, 52); + PoolStatistics(source).Busy.Should().BeInRange(1, BackgroundJobCapacity.Floor); var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); await EnsureQualificationStartAsync(runtime, source, job, entered.Task); @@ -226,7 +226,7 @@ await FluentActions.Awaiting(() => expiration.StopAsync(callerWait.Token)) ActualJoined = false, }); expiration.Completion.IsCompleted.Should().BeFalse(); - PoolStatistics(source).Busy.Should().BeInRange(1, 52); + PoolStatistics(source).Busy.Should().BeInRange(1, BackgroundJobCapacity.Floor); runtime.Snapshot.RunningPools.Should().Be(3); var health = await new BackgroundJobHealthCheck(runtime).CheckHealthAsync(new HealthCheckContext()); health.Status.Should().Be(HealthStatus.Unhealthy); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs index 1f64104ef..48475f330 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.cs @@ -25,8 +25,8 @@ public sealed partial class BackgroundJobRuntimeFacadeTests(SchemaFixture schema private static BackgroundJobRuntimeFixture Fixture => BackgroundJobRuntimeFixture.Shared; [Theory] - [InlineData(false, 3, 4, 1, 16, 52)] - [InlineData(true, 8, 32, 6, 64, 158)] + [InlineData(false, 3, 4, 1, 16, 54)] + [InlineData(true, 8, 32, 6, 64, 160)] public async Task Direct_real_composition_uses_one_pool_manifest_and_joins_all_owners_before_source_disposal( bool maximum, int pools, int workers, int controls, int invocations, int connections) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs b/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs index 0c4604479..8974b83ed 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntrySeal.cs @@ -54,6 +54,7 @@ private sealed class EntrySealProbe(MembershipWriteStore actual, IInvitationWrit public Task FindAsync(MembershipId id, CancellationToken cancellationToken = default) => actual.FindAsync(id, cancellationToken); public Task LockAsync(MembershipId id, CancellationToken cancellationToken = default) => actual.LockAsync(id, cancellationToken); public Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default) => actual.HasMembershipHistoryAsync(cancellationToken); + public Task HasActiveTenantAdministratorAsync(CancellationToken cancellationToken = default) => actual.HasActiveTenantAdministratorAsync(cancellationToken); public Task AddAsync(Membership aggregate, CancellationToken cancellationToken = default) => actual.AddAsync(aggregate, cancellationToken); public Task UpdateAsync(Membership aggregate, CancellationToken cancellationToken = default) => actual.UpdateAsync(aggregate, cancellationToken); public async Task ValidateGraphAsync(CancellationToken cancellationToken = default) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs index 44bd3d61f..24ab68b04 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DatabaseRoleTests.cs @@ -43,6 +43,7 @@ public async Task ThePublishedDatabasePortIsExclusivelyLoopback() [InlineData("learnstack_platform", true)] [InlineData("learnstack_outbox_admin", true)] [InlineData("learnstack_identity_ingress", false)] + [InlineData("learnstack_identity_rebind", false)] public async Task EachRoleExistsWithItsDeclaredBypassPosture(string role, bool expectedBypass) { await using var connection = await PostgresFixture.OpenAsync(_postgres.MigrationConnectionString); @@ -194,8 +195,9 @@ public async Task ABypassRoleWithNoGrantIsStillRefused() [Fact] public async Task EveryRoleCredentialActuallyLogsIn() { - // All four, including learnstack_outbox_admin, whose connection string no - // other case opens. A password the script never set, or set to something + // All six, including learnstack_outbox_admin, whose connection string no + // other case opens, and the two confined roles (ADR-0097, ADR-0104), whose + // credentials only their own tools use. A password the script never set, or set to something // else, is invisible until the dispatcher tries to start — in Phase 02b, // far from here. // Compared against the EXPECTED role, not against one derived from the same @@ -210,6 +212,8 @@ public async Task EveryRoleCredentialActuallyLogsIn() ("learnstack_app", _postgres.AppConnectionString), ("learnstack_platform", _postgres.PlatformConnectionString), ("learnstack_outbox_admin", _postgres.OutboxConnectionString), + ("learnstack_identity_ingress", _postgres.IdentityIngressConnectionString), + ("learnstack_identity_rebind", _postgres.IdentityRebindConnectionString), ]; foreach (var (expected, connectionString) in roles) @@ -226,7 +230,7 @@ public async Task EveryRoleCredentialActuallyLogsIn() public async Task PublicHoldsNoConnectPrivilegeOnTheDatabase() { // PUBLIC holds CONNECT and TEMPORARY on every database by default, so the - // script's four explicit grants add nothing until that default is revoked. + // script's explicit grants add nothing until that default is revoked. // Asserted because nothing else in this suite would notice: removing the // REVOKE from the script leaves all the other cases green, which was // measured — the grants and the roles are unaffected, only the reach is. @@ -249,7 +253,7 @@ public async Task PublicHoldsNoConnectPrivilegeOnTheDatabase() entries.Should().NotBeEmpty("an ACL of NULL means PostgreSQL's permissive default is still in force"); entries.Should().NotContain(e => e.StartsWith('='), - "PUBLIC must hold no privilege on this database; the four explicit grants are the whole of the reach"); + "PUBLIC must hold no privilege on this database; the explicit grants are the whole of the reach"); entries.Should().Contain(e => e.StartsWith("learnstack_app="), "and learnstack_app must still hold the CONNECT it was granted"); } @@ -303,6 +307,51 @@ public async Task TheRolesScriptTakesBackAnEscalatedAttribute() } } + [Fact] + public async Task TheRebindRoleIsNoInheritMemberOfNothingAndTheScriptTakesBackItsEscalation() + { + // The sixth role (ADR-0104) is bounded by its few grants and its policy arms and + // by nothing it could inherit, so an out-of-band INHERIT, BYPASSRLS or membership + // would make those bounds meaningless while every grant census still read correctly. + try + { + await _postgres.ExecuteAsSuperuserAsync( + "ALTER ROLE learnstack_identity_rebind INHERIT BYPASSRLS; " + + "GRANT learnstack_migration TO learnstack_identity_rebind; " + + "GRANT learnstack_identity_rebind TO learnstack_app"); + + (await RebindPostureAsync()).Should().Be((true, true, true, true), "the escalation must be real for the test to mean anything"); + + var result = await _postgres.RunRolesScriptAgainAsync(); + result.ExitCode.Should().Be(0, "{0}", result.Stderr); + + (await RebindPostureAsync()).Should().Be((false, false, false, false), + "re-running the script restores NOINHERIT NOBYPASSRLS and revokes every membership in both directions"); + } + finally + { + await _postgres.ExecuteAsSuperuserAsync( + "ALTER ROLE learnstack_identity_rebind NOINHERIT NOBYPASSRLS; " + + "REVOKE learnstack_migration FROM learnstack_identity_rebind; " + + "REVOKE learnstack_identity_rebind FROM learnstack_app"); + } + } + + private async Task<(bool Inherit, bool Bypass, bool MemberOfOwner, bool ApplicationIsMember)> RebindPostureAsync() + { + await using var connection = await PostgresFixture.OpenAsync(_postgres.MigrationConnectionString); + await using var command = new NpgsqlCommand( + """ + SELECT r.rolinherit, r.rolbypassrls, + pg_has_role('learnstack_identity_rebind', 'learnstack_migration', 'MEMBER'), + pg_has_role('learnstack_app', 'learnstack_identity_rebind', 'MEMBER') + FROM pg_roles r WHERE r.rolname = 'learnstack_identity_rebind' + """, (NpgsqlConnection)connection); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + return (reader.GetBoolean(0), reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3)); + } + [Theory] // Directly, and through a bridge role that holds the membership on the // application role's behalf — because a fix keyed on the four names would @@ -339,7 +388,7 @@ await _postgres.ExecuteAsSuperuserAsync( result.ExitCode.Should().Be(0, "{0}", result.Stderr); (await ReachesABypassRoleAsync()).Should().BeFalse( - "re-running the script revokes every membership the four roles hold"); + "re-running the script revokes every membership the six roles hold"); } finally { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs index 141eb7caf..3b4eccd2b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs @@ -7,7 +7,10 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Messaging; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Time; +using LearnStack.Modules.Tenancy.Infrastructure.Jobs; +using LearnStack.Tests.Fixtures; using LearnStack.Tools.Seeder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; @@ -256,7 +259,7 @@ public async Task Completed_sixth_attempt_with_inert_lease_is_excluded_from_reco (await store.TryClaimAsync(NoBlocked)).Should().BeNull(); (await store.TryClaimTerminalAsync(NoBlocked)).Should().BeNull(); (await store.FailAsync(claim, DeliveryFailureReason.UnknownOutcome)).Should().BeFalse(); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeFalse(); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().NotBe(OperatorRecoveryOutcome.Applied); (await test.InboxCountAsync()).Should().Be(1); } @@ -429,14 +432,15 @@ public async Task Replay_resets_only_exact_active_terminal_tuple_and_keeps_compl var id = await test.InsertAsync(); await test.InsertAsync(id, Second); var store = test.Store(); - var terminal = await TestDatabase.RequestTerminalAsync(store); + var terminal = await TestDatabase.RequestTerminalAsync(store, DeliveryTerminalReason.RetryExhausted); // Mark only sibling completed through the actual app completion grant. await test.CompleteAsync(id, Second, inbox: true); var sibling = await test.ReadAsync(id, Second); (await store.TryTerminalizeAsync(terminal, AttemptTrace)).Should().BeTrue(); - (await store.ReplayAsync(SchemaFixture.TenantB, First, id)).Should().BeFalse(); - (await store.ReplayAsync(SchemaFixture.TenantA, Second, id)).Should().BeFalse(); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeTrue(); + (await ReplayAsync(store, test, SchemaFixture.TenantB, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.NotFound); + (await ReplayAsync(store, test, SchemaFixture.TenantA, Second, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence, + "the sibling completed, so it shows no dead-letter instant for a fence to match"); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); var reset = await test.ReadAsync(id); reset.Attempts.Should().Be(0); reset.Error.Should().BeNull(); @@ -452,7 +456,7 @@ public async Task Replay_resets_only_exact_active_terminal_tuple_and_keeps_compl fresh.SubscriptionId.Should().Be(First); fresh.Token.Should().NotBe(terminal.Token); fresh.Attempts.Should().Be(1); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeFalse(); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); } [Fact] @@ -466,7 +470,7 @@ public async Task Replay_preserves_other_terminal_rows_differing_in_each_tuple_c var store = test.Store(); for (var index = 0; index < 4; index++) { - var terminal = await TestDatabase.RequestTerminalAsync(store); + var terminal = await TestDatabase.RequestTerminalAsync(store, DeliveryTerminalReason.RetryExhausted); (await store.TryTerminalizeAsync(terminal, AttemptTrace)).Should().BeTrue(); } (await store.TryClaimAsync(NoBlocked)).Should().BeNull(); @@ -477,7 +481,7 @@ public async Task Replay_preserves_other_terminal_rows_differing_in_each_tuple_c foreach (var row in new[] { target, sibling, foreign, unrelated }) row.DeadLettered.Should().NotBeNull("every control must itself satisfy the terminal replay state predicate"); - (await store.ReplayAsync(SchemaFixture.TenantA, First, id)).Should().BeTrue(); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); var reset = await test.ReadAsync(id); reset.Attempts.Should().Be(0); @@ -493,28 +497,288 @@ public async Task Replay_preserves_other_terminal_rows_differing_in_each_tuple_c (await test.ReadAsync(unrelatedId)).Should().Be(unrelated); } + private static PlatformAdmission ReplayAdmission(DateTimeOffset? issuedAt = null, PlatformOperation? operation = null) => + TestPlatformAdmissions.Admission( + operation ?? PlatformOperations.DeliveryReplay, null, + correlationId: "00-recovery-" + Guid.NewGuid().ToString("N"), issuedAt: issuedAt ?? Occurred); + + /// A replay under the fence the row shows now, as an operator would present what inspection returned. + private static async Task ReplayAsync( + DeliveryDispatchStore store, TestDatabase test, Guid tenant, string subscription, Guid id, + Func? change = null, PlatformAdmission? admission = null) + { + var row = await test.TryReadAsync(id, subscription, tenant); + var request = new DeliveryReplayRequest( + tenant, subscription, id, row?.ReplayCount ?? 0, row?.DeadLettered ?? DateTimeOffset.UnixEpoch, + row?.TerminalReason ?? "retry_exhausted"); + return await store.ReplayAsync(change?.Invoke(request) ?? request, admission ?? ReplayAdmission()); + } + + private const string DeadLetter = "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"; + [Theory] - [InlineData("pending")] - [InlineData("privileged")] - [InlineData("unknown")] - [InlineData("retired")] - [InlineData("requested")] - [InlineData("live")] - public async Task Replay_refuses_nonadmitted_or_unfinished_state(string state) + [InlineData("pending", "retry_exhausted")] + [InlineData("privileged", "retry_exhausted")] + [InlineData("unknown", "unknown_type")] + [InlineData("retired", "retired_type")] + [InlineData("active", "invalid_envelope")] + public async Task Replay_refuses_a_matching_fence_on_a_state_a_reset_may_not_act_on(string state, string reason) { await using var test = await TestDatabase.CreateAsync(schema.Postgres); var subscription = state == "pending" ? Pending : state == "privileged" ? Privileged : First; var type = state is "unknown" or "retired" ? state : TypeIdentity; var id = await test.InsertAsync(subscription: subscription, type: type); - await test.UpdateAsync(id, subscription, state switch - { - "live" => "locked_by = '11111111-1111-4111-8111-111111111111', locked_until = clock_timestamp() + interval '1 hour'", - "requested" => "terminal_reason = 'invalid_envelope'", - _ => "terminal_reason = 'invalid_envelope', dead_lettered_at = clock_timestamp()", - }); + await test.UpdateAsync(id, subscription, $"terminal_reason = '{reason}', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); var before = await test.ReadAsync(id, subscription); - (await test.Store().ReplayAsync(SchemaFixture.TenantA, subscription, id)).Should().BeFalse(); + + var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, subscription, id); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.NotRecoverable, state); + result.Refusal.Should().Be(state == "active" ? "invalid_envelope" : "subscription_not_active", state); (await test.ReadAsync(id, subscription)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty("a refusal writes no row"); + } + + [Theory] + [InlineData("count")] + [InlineData("reason")] + public async Task Replay_reports_a_stale_fence_before_it_reports_a_refused_state(string variation) + { + // The fence is compared before the state, so an operator who read an older row is told to read it again and + // is not told the row is refused: only a row whose fence they hold can be refused to them. + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, "terminal_reason = 'invalid_envelope', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); + var before = await test.ReadAsync(id); + + var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, + change: request => variation == "count" ? request with { ReplayCount = request.ReplayCount + 1 } + : request with { TerminalReason = "retry_exhausted" }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + } + + [Theory] + [InlineData("live")] + [InlineData("requested")] + public async Task Replay_treats_a_row_that_is_not_dead_lettered_as_a_stale_fence(string state) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, state == "live" + ? "locked_by = '11111111-1111-4111-8111-111111111111', locked_until = clock_timestamp() + interval '1 hour'" + : "terminal_reason = 'retry_exhausted'"); + var before = await test.ReadAsync(id); + + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + } + + [Fact] + public async Task Replay_under_the_current_fence_resets_the_row_writes_one_operator_row_and_returns_it_to_the_dispatcher() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.UpdateAsync(id, First, DeadLetter); + var store = test.Store(); + var admission = ReplayAdmission(); + + var result = await ReplayAsync(store, test, SchemaFixture.TenantA, First, id, admission: admission); + + result.Should().Be(new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, 1)); + var row = await test.ReadAsync(id); + (row.Attempts, row.TerminalReason, row.DeadLettered, row.Error, row.Token, row.ReplayCount).Should().Be((0, null, null, null, null, 1)); + var audit = (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle().Which; + audit.Tenant.Should().Be(SchemaFixture.TenantA); + audit.Organization.Should().Be(SchemaFixture.OrgA1); + audit.ActorIsNull.Should().BeTrue("an operator is not a user"); + audit.Reason.Should().Be("delivery_replay"); + audit.Class.Should().Be("Must"); + audit.Type.Should().Be("SecurityEvent"); + audit.Correlation.Should().Be(admission.Operator.CorrelationId); + var metadata = JsonNode.Parse(audit.Metadata)!.AsObject(); + metadata.Select(pair => pair.Key).Should().BeEquivalentTo(["operator", "event_id", "subscription_id", "fence"]); + metadata["operator"]!.AsObject().ContainsKey("ticket").Should().BeFalse("a tenant can read this row, and the ticket never rides on one"); + metadata["event_id"]!.GetValue().Should().Be(id); + metadata["subscription_id"]!.GetValue().Should().Be(First); + metadata["fence"]!["before"]!["replay_count"]!.GetValue().Should().Be(0); + metadata["fence"]!["before"]!["dead_lettered_at"]!.GetValue().Should().Be("2026-10-01T12:00:00.1234560Z"); + metadata["fence"]!["before"]!["terminal_reason"]!.GetValue().Should().Be("retry_exhausted"); + metadata["fence"]!["after"]!["replay_count"]!.GetValue().Should().Be(1); + var fresh = (await store.TryClaimAsync(NoBlocked))!; + fresh.EventId.Should().Be(id); + fresh.Attempts.Should().Be(1, "the dispatcher claims the reset row once, with a renewed budget"); + } + + [Theory] + [InlineData("count")] + [InlineData("reason")] + [InlineData("instant-after-one-microsecond")] + [InlineData("instant-before-one-microsecond")] + [InlineData("instant-whole-millisecond")] + public async Task Replay_with_any_part_of_the_fence_changed_is_stale_and_changes_nothing(string change) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var before = await test.ReadAsync(id); + + var result = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, request => change switch + { + "count" => request with { ReplayCount = request.ReplayCount + 1 }, + "reason" => request with { TerminalReason = "unknown_type" }, + "instant-after-one-microsecond" => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(10) }, + "instant-before-one-microsecond" => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(-10) }, + _ => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(-1234560 + 1230000) }, + }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence, "the fence is the instant to the microsecond, not to a coarser unit"); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + } + + [Fact] + public async Task Replay_of_a_delivery_whose_tenant_is_not_serving_is_not_recoverable() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + await test.SetTenantStatusAsync("Suspended"); + var before = await test.ReadAsync(id); + + var refused = await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id); + + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "tenant_not_serving")); + (await test.ReadAsync(id)).Should().Be(before); + await test.SetTenantStatusAsync("Active"); + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task A_failed_operator_audit_write_rolls_the_replay_back_and_the_spent_admission_cannot_retry() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var before = await test.ReadAsync(id); + var admission = ReplayAdmission(); + await test.AuditGrantAsync(false); + + var attempt = () => ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, admission: admission); + + await attempt.Should().ThrowAsync(); + (await test.ReadAsync(id)).Should().Be(before, "the MUST row and the reset commit together or not at all"); + await test.AuditGrantAsync(true); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + var again = () => ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id, admission: admission); + await again.Should().ThrowAsync("an admission is spent when it is used"); + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task Replay_refuses_an_admission_for_another_operation_or_a_stale_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var before = await test.ReadAsync(id); + var store = test.Store(); + + foreach (var admission in new[] + { + ReplayAdmission(operation: PlatformOperations.DeliveryReset), + ReplayAdmission(operation: PlatformOperations.IdentityAuthorityRebind), + ReplayAdmission(issuedAt: Occurred.AddSeconds(-31)), + }) + { + var act = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, id, admission: admission); + await act.Should().ThrowAsync(); + } + + (await test.ReadAsync(id)).Should().Be(before); + } + + [Fact] + public async Task The_operator_lane_is_its_own_slot_so_a_busy_operator_never_costs_the_dispatcher_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var first = await test.InsertAsync(); + var second = await test.InsertAsync(); + await test.UpdateAsync(first, First, DeadLetter); + await test.UpdateAsync(second, First, DeadLetter); + var store = test.Store(); + + // Hold the first row's lock, so the first replay waits inside the operator lane. + await using var holder = await test.Dispatch.OpenConnectionAsync(); + await using var holding = await holder.BeginTransactionAsync(); + await using (var hold = new NpgsqlCommand( + "SELECT 1 FROM event_deliveries WHERE tenant_id = @tenant AND subscription_id = @subscription AND event_id = @event FOR UPDATE", + holder, holding)) + { + hold.Parameters.AddWithValue("tenant", SchemaFixture.TenantA); + hold.Parameters.AddWithValue("subscription", First); + hold.Parameters.AddWithValue("event", first); + await hold.ExecuteScalarAsync(); + } + + var waiting = ReplayAsync(store, test, SchemaFixture.TenantA, First, first); + await test.WaitForLockWaitAsync(); + + var busy = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, second); + await busy.Should().ThrowAsync("one operator call at a time per store"); + (await store.ReadSnapshotAsync(NoBlocked)).Should().NotBeNull("the dispatcher's own slots are untouched"); + + await holding.CommitAsync(); + (await waiting).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, second)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the lane is free again once the first call ends"); + } + + [Fact] + public async Task A_replay_whose_commit_acknowledgement_is_lost_is_unknown_and_a_repeat_is_a_stale_fence() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var fence = await test.ReadAsync(id); + await using var proxy = new CommitResponseDroppingProxy(test.OutboxConnectionString, rejectReconciliationConnections: false); + await using var source = OutboxDispatcherDataSource.Build(proxy.ConnectionString); + + var attempt = () => ReplayAsync(test.Store(source: source), test, SchemaFixture.TenantA, First, id); + + (await attempt.Should().ThrowAsync()).Which.CommitOutcomeUnknown.Should().BeTrue(); + proxy.DroppedCommitResponses.Should().Be(1); + (await test.ReadAsync(id)).ReplayCount.Should().Be(1, "the commit landed although its answer did not"); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle(); + var repeat = await test.Store().ReplayAsync( + new DeliveryReplayRequest(SchemaFixture.TenantA, First, id, fence.ReplayCount, fence.DeadLettered!.Value, "retry_exhausted"), + ReplayAdmission()); + repeat.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + } + + [Fact] + public async Task Replay_leaves_every_other_row_inbox_and_the_producer_byte_identical() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.InsertAsync(id, Second); + var other = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + await test.UpdateAsync(id, Second, DeadLetter); + await test.UpdateAsync(other, First, DeadLetter); + var sibling = await test.ReadAsync(id, Second); + var unrelated = await test.ReadAsync(other); + var inbox = await test.InboxCountAsync(); + + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + + (await test.ReadAsync(id, Second)).Should().Be(sibling, "another subscription of the same event is its own row"); + (await test.ReadAsync(other)).Should().Be(unrelated, "another event is another row"); + (await test.InboxCountAsync()).Should().Be(inbox, "inbox identity is never reset"); } [Theory] @@ -535,6 +799,120 @@ public async Task Real_scheduler_role_cannot_read_payload_causality_or_inbox(str (await test.Store().TryClaimAsync(NoBlocked)).Should().NotBeNull(); } + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + [InlineData("operation")] + [InlineData("reason")] + [InlineData("metadata")] + [InlineData("correlation")] + [InlineData("actor")] + [InlineData("class")] + [InlineData("type")] + [InlineData("transaction")] + public async Task Substituting_a_field_of_the_replay_row_or_its_transaction_is_refused_by_the_real_seam_and_rolls_the_replay_back( + string substitution) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.UpdateAsync(id, First, DeadLetter); + var calls = 0; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + calls++; + // The witness came from the real successful UPDATE, before the row it must describe is written. + witness.Kind.Should().Be("replay"); + witness.EventId.Should().Be(id); + witness.TenantId.Should().Be(SchemaFixture.TenantA); + witness.OrganizationId.Should().Be(SchemaFixture.OrgA1); + if (substitution == "transaction") + { + await using var otherConnection = await test.Dispatch.OpenConnectionAsync(cancellationToken); + await using var otherTransaction = await otherConnection.BeginTransactionAsync(cancellationToken); + await inner.WriteOperatorRecoveryAsync(draft, witness, otherConnection, otherTransaction, cancellationToken); + return; + } + + var changed = substitution switch + { + "tenant" => draft with { TenantId = TenantId.From(SchemaFixture.TenantB) }, + "organization" => draft with { OrganizationId = OrganizationId.From(SchemaFixture.OrgA2) }, + "operation" => draft with { Operation = PlatformOperations.DeliveryReset.AuditSlug }, + "reason" => draft with { Reason = PlatformOperations.DeliveryReset.ReasonSlug }, + "metadata" => draft with { Metadata = draft.Metadata + " " }, + "correlation" => draft with { CorrelationId = "00-forged" }, + "actor" => draft with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + "class" => draft with { OperationClass = OperationClass.Should }, + "type" => draft with { OperationType = OperationType.Update }, + _ => throw new ArgumentOutOfRangeException(nameof(substitution)), + }; + await inner.WriteOperatorRecoveryAsync(changed, witness, connection, transaction, cancellationToken); + })); + var before = await test.ReadAsync(id); + + var attempt = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, id); + await attempt.Should().ThrowAsync(); + + calls.Should().Be(1, "the refusal must come from the real audit seam, after a successful UPDATE"); + (await test.ReadAsync(id)).Should().Be(before, "the replay and its row commit together or not at all"); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().BeEmpty(); + (await ReplayAsync(test.Store(), test, SchemaFixture.TenantA, First, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the same fence succeeds through the unmodified seam"); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle(); + } + + [Fact] + public async Task A_witness_from_an_earlier_replay_cannot_be_reused_on_a_later_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + OperatorRecoveryTransition? previous = null; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + await inner.WriteOperatorRecoveryAsync(draft, previous ?? witness, connection, transaction, cancellationToken); + previous = witness; + })); + var first = await test.InsertAsync(); + await test.UpdateAsync(first, First, DeadLetter); + (await ReplayAsync(store, test, SchemaFixture.TenantA, First, first)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + var second = await test.InsertAsync(); + await test.UpdateAsync(second, First, DeadLetter); + var before = await test.ReadAsync(second); + + var attempt = () => ReplayAsync(store, test, SchemaFixture.TenantA, First, second); + await attempt.Should().ThrowAsync(); + + (await test.ReadAsync(second)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.replay")).Should().ContainSingle("only the first replay committed"); + } + + [Fact] + public async Task The_recovery_owner_replays_through_the_delivery_store_and_counts_each_outcome_under_the_replay_operation() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.UpdateAsync(id, First, DeadLetter); + var fence = await test.ReadAsync(id); + var request = new DeliveryReplayRequest(SchemaFixture.TenantA, First, id, fence.ReplayCount, fence.DeadLettered!.Value, "retry_exhausted"); + var owner = new OperatorRecovery(test.Store(), test.OutboxStore()); + using var meters = new OperatorRecoveryMeterProbe(); + + var applied = await owner.ReplayDeliveryAsync(ReplayAdmission(), request); + var stale = await owner.ReplayDeliveryAsync(ReplayAdmission(), request); + var unknown = await owner.ReplayDeliveryAsync(ReplayAdmission(), request with { EventId = Guid.CreateVersion7() }); + + (applied.Outcome, stale.Outcome, unknown.Outcome).Should().Be( + (OperatorRecoveryOutcome.Applied, OperatorRecoveryOutcome.StaleFence, OperatorRecoveryOutcome.NotFound)); + (await test.ReadAsync(id)).ReplayCount.Should().Be(1, "the owner reached the delivery store and no other"); + var replay = PlatformOperations.DeliveryReplay.AuditSlug; + var reset = PlatformOperations.DeliveryReset.AuditSlug; + (meters.Recoveries(replay, "applied"), meters.Recoveries(replay, "stale_fence"), meters.Recoveries(replay, "not_found")) + .Should().Be((1, 1, 1)); + meters.Results(replay).Should().Be(1, "only an applied replay committed a result row"); + meters.Recoveries(reset, "applied").Should().Be(0, "a delivery replay is never counted as a producer reset"); + } + private static OutboxEventRegistry Registry() { var handlers = IntegrationEventHandlerRegistry.FromServiceDescriptors([ @@ -572,6 +950,8 @@ public sealed class PrivilegedHandler : IIntegrationEventHandler private sealed record Row(int Attempts, string? Token, DateTimeOffset? LockedUntil, DateTimeOffset Available, DateTimeOffset? Processed, string? TerminalReason, DateTimeOffset? DeadLettered, string? Error, int ReplayCount, DateTimeOffset? Replayed); + private sealed record OperatorAuditRow(Guid Tenant, Guid? Organization, bool ActorIsNull, string Operation, + string? Reason, string Correlation, string Metadata, string Class, string Type); private sealed record AuditRow(Guid Tenant, Guid? Organization, Guid Actor, string Operation, string Type, string Class, string Correlation, string Metadata); @@ -605,6 +985,7 @@ INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row VALUES (@tenant, 'delivery-store', 'Delivery store', 'Trial', now(), @actor, 0); INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at, created_by, row_version) VALUES (@organization, @tenant, 'hq', 'HQ', 'Active', now(), @actor, 0); + UPDATE tenants SET default_organization_id = @organization WHERE id = @tenant; """, ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), ("actor", UserId.SystemActor.Value)); await transaction.CommitAsync(); return test; @@ -612,11 +993,18 @@ INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at catch { await test.DisposeAsync(); throw; } } + /// The producer store beside the delivery store, for a test that builds the recovery owner over both. + public OutboxDispatchStore OutboxStore() => + new(new PrivilegedDataSource(() => Dispatch), Registry(), new OutboxDispatchOptions(), new SystemGuidFactory(), + new FixedClock(Occurred), _provider.GetRequiredService(), + BackgroundJobLifecycleProjectionDeclaration.Create()); + public DeliveryDispatchStore Store(NpgsqlDataSource? source = null, Func? decorate = null) => new(new PrivilegedDataSource(() => source ?? Dispatch), Registry(), new DeliveryDispatchOptions(), new SystemGuidFactory(), new FixedClock(Occurred), decorate is null ? _provider.GetRequiredService() - : new DecoratingScopes(_provider.GetRequiredService(), decorate)); + : new DecoratingScopes(_provider.GetRequiredService(), decorate), + BackgroundJobLifecycleProjectionDeclaration.Create()); public async Task InsertAsync(Guid? id = null, string subscription = First, string? type = null, Guid? organization = null, string? partition = null, Guid? tenant = null, DateTimeOffset? occurred = null) @@ -646,6 +1034,10 @@ INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization } public async Task ReadAsync(Guid id, string subscription = First, Guid? tenant = null, + CancellationToken cancellationToken = default) => + (await TryReadAsync(id, subscription, tenant, cancellationToken)).Should().NotBeNull().And.Subject.As(); + + public async Task TryReadAsync(Guid id, string subscription = First, Guid? tenant = null, CancellationToken cancellationToken = default) { await using var connection = await Dispatch.OpenConnectionAsync(cancellationToken); @@ -656,7 +1048,7 @@ public async Task ReadAsync(Guid id, string subscription = First, Guid? ten """, connection); Bind(command, id, subscription, tenant); await using var row = await command.ExecuteReaderAsync(cancellationToken); - (await row.ReadAsync(cancellationToken)).Should().BeTrue(); + if (!await row.ReadAsync(cancellationToken)) return null; return new(row.GetInt32(0), Text(row, 1), Time(row, 2), row.GetFieldValue(3), Time(row, 4), Text(row, 5), Time(row, 6), Text(row, 7), row.GetInt32(8), Time(row, 9)); } @@ -687,10 +1079,11 @@ public async Task NowAsync(CancellationToken cancellationToken = await row.ReadAsync(cancellationToken); return row.GetFieldValue(0); } - public static async Task RequestTerminalAsync(DeliveryDispatchStore store) + public static async Task RequestTerminalAsync( + DeliveryDispatchStore store, DeliveryTerminalReason reason = DeliveryTerminalReason.InvalidEnvelope) { var claim = (await store.TryClaimAsync(NoBlocked))!; - (await store.RequestTerminalAsync(claim, DeliveryTerminalReason.InvalidEnvelope)).Should().BeTrue(); + (await store.RequestTerminalAsync(claim, reason)).Should().BeTrue(); return (await store.TryClaimTerminalAsync(NoBlocked))!; } public async Task CompleteAsync(Guid id, string subscription, bool inbox) @@ -727,6 +1120,37 @@ private async Task CountAsync(string sql) await using var command = new NpgsqlCommand(sql, connection, transaction); return (long)(await command.ExecuteScalarAsync())!; } + public async Task SetTenantStatusAsync(string status) + { + await using var connection = await _app.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.ExecuteAsync(connection, transaction, + "UPDATE tenants SET status = @status WHERE id = @tenant", + ("status", status), ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + public async Task> ReadOperatorAuditAsync(string operation) + { + await using var connection = await _app.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.SetSettingAsync(connection, transaction, "app.scope", "tenant"); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, organization_id, actor_user_id IS NULL, operation, reason, correlation_id, + metadata::text, operation_class, operation_type + FROM audit_log WHERE operation = @operation ORDER BY timestamp + """, connection, transaction); + command.Parameters.AddWithValue("operation", operation); + await using var row = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await row.ReadAsync()) + rows.Add(new(row.GetGuid(0), row.IsDBNull(1) ? null : row.GetGuid(1), row.GetBoolean(2), row.GetString(3), + row.IsDBNull(4) ? null : row.GetString(4), row.GetString(5), row.GetString(6), row.GetString(7), row.GetString(8))); + return rows; + } + public async Task ReadAuditAsync() { await using var connection = await _app.OpenConnectionAsync(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs new file mode 100644 index 000000000..9e644432a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryInspectionTests.cs @@ -0,0 +1,540 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Messaging; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Messaging; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The operator's metadata-only inspection of dead-lettered work against a real database and the real platform +/// scope (ADR-0103 § 1): its pages, its cursors, the one entry row each page writes and what the platform role's +/// column grants refuse. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DeliveryInspectionTests(SchemaFixture schema) +{ + private const string Subscription = "test.inspect.v1"; + private static readonly string KnownType = typeof(InspectionEvent).AssemblyQualifiedName!; + + [Fact] + public async Task A_page_lists_dead_lettered_outbox_rows_oldest_first_with_the_fence_and_pages_by_cursor() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var ids = new[] { Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7() }; + for (var index = 0; index < ids.Length; index++) + await proof.OutboxAsync(ids[index], $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index + 1} 12:00:00.123456+00'"); + await proof.OutboxAsync(Guid.CreateVersion7(), "processed_at = now()"); + await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted'"); + + var first = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 2); + var second = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 2); + + first.Items.Select(row => row.EventId).Should().Equal(ids[0], ids[1]); + first.NextCursor.Should().NotBeNull(); + second!.Items.Select(row => row.EventId).Should().Equal([ids[2]], "a page after the last row holds only it"); + second.NextCursor.Should().BeNull(); + var row = first.Items[0]; + row.TenantId.Should().Be(SchemaFixture.TenantA); + row.Attempts.Should().Be(6); + row.TerminalReason.Should().Be("retry_exhausted"); + row.DeadLetteredAt!.Value.UtcTicks.Should().Be(new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero).AddTicks(1234560).UtcTicks, + "the fence instant comes back to the microsecond"); + row.EventType.Should().Be("InspectionEvent", "the registry's label stands for the stored type text"); + row.Actionable.Should().BeTrue(); + } + + [Fact] + public async Task A_terminal_requested_row_is_listed_and_never_actionable() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var id = Guid.CreateVersion7(); + await proof.OutboxAsync(id, "attempts = 6, terminal_reason = 'retry_exhausted'"); + await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now()"); + + var page = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 10); + + var row = page!.Items.Should().ContainSingle().Which; + row.EventId.Should().Be(id); + row.DeadLetteredAt.Should().BeNull(); + row.Actionable.Should().BeFalse("its state is shown and a reset is not offered"); + } + + [Fact] + public async Task Deliveries_show_the_replay_fence_and_mark_what_a_replay_could_act_on() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var replayable = Guid.CreateVersion7(); + var envelope = Guid.CreateVersion7(); + await proof.DeliveryAsync(replayable, Subscription, "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.5+00', replay_count = 2, replayed_at = now()"); + await proof.DeliveryAsync(envelope, Subscription, "terminal_reason = 'invalid_envelope', dead_lettered_at = '2026-10-02 12:00:00+00'"); + + var page = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + + page!.Items.Select(row => row.EventId).Should().Equal(replayable, envelope); + page.Items[0].Should().Match(row => row.ReplayCount == 2 && row.TerminalReason == "retry_exhausted" + && row.SubscriptionId == Subscription && row.Actionable && row.EventType == "InspectionEvent"); + page.Items[1].Actionable.Should().BeFalse("an envelope that is invalid cannot become valid"); + } + + [Fact] + public async Task Quarantined_jobs_list_with_their_reservation_occupancy_and_no_parameters() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var job = await BackgroundJobRuntimeRows.InsertAsync( + proof.Database.AppConnectionString, definition: "fixture.unknown.v1", tenant: SchemaFixture.TenantA); + await using (var dispatcher = await PostgresFixture.OpenAsync(proof.Database.OutboxConnectionString)) + await SchemaQueries.ExecuteAsync(dispatcher, null, + "UPDATE background_jobs SET phase = 'quarantined', quarantine_reason = 'unknown_outcome' WHERE id = @id", ("id", job.Value)); + + var page = await proof.Inspection.InspectJobsAsync(Proof.Admission(), null, 10); + + var row = page!.Items.Should().ContainSingle().Which; + row.JobId.Should().Be(job.Value); + row.Phase.Should().Be("quarantined"); + row.QuarantineReason.Should().Be("unknown_outcome"); + row.DefinitionKey.Should().Be("fixture.unknown.v1"); + row.HeldReservations.Should().Be(0); + JsonSerializer.Serialize(row).Should().NotContain("parameters", "no envelope or parameter column is read"); + } + + [Fact] + public async Task Each_page_writes_one_entry_row_naming_the_inspection_and_no_result_row_and_the_scope_changes_nothing() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.OutboxAsync(Guid.CreateVersion7(), "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now()"); + var admission = Proof.Admission("INC-103"); + + await proof.Inspection.InspectOutboxAsync(admission, DeliveryInspectionState.DeadLettered, null, 10); + + var rows = await proof.AuditAsync(admission.Operator.CorrelationId!); + var entry = rows.Should().ContainSingle("the scope reads and changes nothing, so it writes no result row").Which; + entry.Operation.Should().Be(PlatformAdminScope.EnterOperation); + entry.Reason.Should().Be("delivery_inspect"); + entry.Metadata.Should().Contain("INC-103", "a sentinel-tenant row is unreadable to every tenant, so it carries the ticket"); + } + + [Fact] + public async Task A_malformed_or_foreign_cursor_answers_null_and_enters_no_scope() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var admission = Proof.Admission(); + + (await proof.Inspection.InspectOutboxAsync(admission, DeliveryInspectionState.DeadLettered, "not-a-cursor", 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("v1~outbox.DeadLettered~1~x")), 10)).Should().BeNull("a cursor of another resource is refused"); + + (await proof.AuditAsync(admission.Operator.CorrelationId!)).Should().BeEmpty(); + } + + [Fact] + public async Task The_platform_role_cannot_select_an_excluded_column_of_any_inspected_table() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + + foreach (var sql in new[] + { + "SELECT payload FROM outbox_messages", "SELECT correlation_id FROM outbox_messages", + "SELECT locked_by FROM outbox_messages", "SELECT * FROM outbox_messages", + "SELECT payload FROM event_deliveries", "SELECT correlation_id FROM event_deliveries", + "SELECT locked_by FROM event_deliveries", "SELECT * FROM event_deliveries", + "SELECT parameters FROM background_jobs", "SELECT plan FROM background_jobs", + "SELECT traceparent FROM background_jobs", "SELECT operation_id FROM background_jobs", + "SELECT ownership_token FROM background_jobs", "SELECT * FROM background_jobs", + }) + { + await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sql)).Should() + .ThrowAsync(sql).Where(failure => failure.SqlState == PostgresErrorCodes.InsufficientPrivilege, sql); + } + + await SchemaQueries.ExecuteAsync(platform, null, "SELECT id, attempts, dead_lettered_at FROM outbox_messages"); + await SchemaQueries.ExecuteAsync(platform, null, "SELECT job_id, released_at FROM background_job_reservations"); + } + + [Fact] + public async Task Job_occupancy_counts_the_unreleased_reservations_of_the_job_and_of_its_capacity_group() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var held = await BackgroundJobRuntimeRows.InsertAsync( + proof.Database.AppConnectionString, definition: "fixture.unknown.v1", tenant: SchemaFixture.TenantA, + capacityGroup: "fixture.resource"); + var neighbour = await BackgroundJobRuntimeRows.InsertAsync( + proof.Database.AppConnectionString, definition: "fixture.unknown.v1", tenant: SchemaFixture.TenantA, + capacityGroup: "fixture.resource"); + await using (var dispatcher = await PostgresFixture.OpenAsync(proof.Database.OutboxConnectionString)) + await SchemaQueries.ExecuteAsync(dispatcher, null, + "UPDATE background_jobs SET phase = 'quarantined', quarantine_reason = 'unknown_outcome' WHERE id = @id", ("id", held.Value)); + // The fixture rows are written with the foreign keys and guard triggers off: the proof is the two counts, and + // a reservation's own lifecycle has its own proofs. One unreleased and one released reservation belong to the + // quarantined job; a second job of the same group holds one more. + await proof.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO background_job_capacity (tenant_id, capacity_group) + SELECT DISTINCT tenant_id, capacity_group FROM background_jobs WHERE id IN ('{held.Value}', '{neighbour.Value}') + ON CONFLICT DO NOTHING; + INSERT INTO background_job_attempts (id, tenant_id, job_id, stage, ordinal, admission_token, deadline) + SELECT uuidv7(), tenant_id, id, 'normal', ordinal, uuidv7(), clock_timestamp() + interval '4 minutes' + FROM background_jobs, (VALUES (1), (2)) AS attempts(ordinal) WHERE id = '{held.Value}' + UNION ALL + SELECT uuidv7(), tenant_id, id, 'normal', 1, uuidv7(), clock_timestamp() + interval '4 minutes' + FROM background_jobs WHERE id = '{neighbour.Value}'; + INSERT INTO background_job_reservations (tenant_id, capacity_group, job_id, attempt_id, reserved_at, released_at, release_reason) + SELECT j.tenant_id, j.capacity_group, j.id, a.id, clock_timestamp() - interval '1 minute', + CASE WHEN a.ordinal = 2 AND j.id = '{held.Value}' THEN clock_timestamp() END, + CASE WHEN a.ordinal = 2 AND j.id = '{held.Value}' THEN 'completed' END + FROM background_jobs j JOIN background_job_attempts a ON a.job_id = j.id AND a.tenant_id = j.tenant_id + WHERE j.id IN ('{held.Value}', '{neighbour.Value}'); + """); + + var page = await proof.Inspection.InspectJobsAsync(Proof.Admission(), null, 10); + + var row = page!.Items.Should().ContainSingle("only the quarantined job is listed").Which; + row.JobId.Should().Be(held.Value); + row.HeldReservations.Should().Be(1, "the released reservation of the job is not held"); + row.GroupOccupancy.Should().Be(2, "the job's unreleased reservation and its neighbour's, both of one capacity group"); + } + + [Fact] + public async Task A_cursor_belongs_to_the_resource_and_state_that_issued_it_even_when_its_key_is_valid_for_another() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + for (var index = 1; index <= 2; index++) + { + await proof.OutboxAsync(Guid.CreateVersion7(), $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index} 12:00:00+00'"); + await proof.DeliveryAsync(Guid.CreateVersion7(), Subscription, $"terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-0{index} 12:00:00+00'"); + } + + var outbox = (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; + var delivery = (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1))!.NextCursor; + outbox.Should().NotBeNull(); + delivery.Should().NotBeNull(); + + // Each was issued for the route and state it came from: the same position under another one is refused. + (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, outbox, 10)).Should().BeNull(); + (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, delivery, 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().BeNull(); + (await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, delivery, 10)).Should().BeNull(); + (await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, outbox, 10)).Should().NotBeNull(); + } + + [Fact] + public async Task Deliveries_page_through_equal_instants_without_a_repeat_or_a_gap() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var ids = Enumerable.Range(0, 5).Select(_ => Guid.CreateVersion7()).ToArray(); + foreach (var id in ids) + await proof.DeliveryAsync(id, Subscription, "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.000001+00'"); + + var seen = new List(); + string? cursor = null; + var pages = 0; + do + { + var page = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, cursor, 2); + seen.AddRange(page!.Items.Select(row => row.EventId)); + cursor = page.NextCursor; + pages++; + } + while (cursor is not null && pages < 10); + + pages.Should().Be(3); + seen.Should().BeEquivalentTo(ids, "every row once").And.OnlyHaveUniqueItems(); + seen.Should().Equal(ids.OrderBy(id => id), "equal instants are ordered by the row's own key"); + } + + [Fact] + public async Task Terminal_requested_rows_page_in_the_order_their_dead_letter_is_due() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var late = Guid.CreateVersion7(); + var early = Guid.CreateVersion7(); + await proof.OutboxAsync(late, "attempts = 6, terminal_reason = 'retry_exhausted', available_after = '2026-10-03 12:00:00+00'"); + await proof.OutboxAsync(early, "attempts = 6, terminal_reason = 'retry_exhausted', available_after = '2026-10-02 12:00:00+00'"); + + var first = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, null, 1); + var second = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.TerminalRequested, first!.NextCursor, 1); + + first.Items.Single().EventId.Should().Be(early); + second!.Items.Single().EventId.Should().Be(late); + second.NextCursor.Should().BeNull(); + } + + [Fact] + public async Task The_platform_role_can_select_exactly_the_twelve_outbox_columns_the_inspection_projects() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT attname FROM pg_attribute + WHERE attrelid = 'outbox_messages'::regclass AND attnum > 0 AND NOT attisdropped + AND has_column_privilege('learnstack_platform', 'outbox_messages', attnum, 'SELECT') + ORDER BY attname + """, (NpgsqlConnection)platform); + var granted = new List(); + await using (var reader = await command.ExecuteReaderAsync()) + while (await reader.ReadAsync()) granted.Add(reader.GetString(0)); + + granted.Should().Equal( + "attempts", "available_after", "dead_lettered_at", "id", "last_error", "locked_until", "occurred_at", + "organization_id", "processed_at", "tenant_id", "terminal_reason", "type"); + } + + [Theory] + [InlineData("publish:failed:provider", "publish:failed:provider")] + [InlineData("migration:legacy:redacted", "migration:legacy:redacted")] + [InlineData("stored text", "unrecognized")] + [InlineData("Free Text With Spaces", "unrecognized")] + public async Task The_last_error_a_page_shows_is_a_descriptor_or_the_word_unrecognized(string stored, string shown) + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.OutboxAsync(Guid.CreateVersion7(), $"attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = now(), last_error = '{stored}'"); + await proof.DeliveryAsync(Guid.CreateVersion7(), Subscription, $"terminal_reason = 'retry_exhausted', dead_lettered_at = now(), last_error = '{stored}'"); + + var outbox = await proof.Inspection.InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + var delivery = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + + outbox!.Items.Single().LastError.Should().Be(shown); + delivery!.Items.Single().LastError.Should().Be(shown); + } + + [Fact] + public async Task A_refused_credential_is_a_defect_and_an_unreachable_database_is_a_retryable_outage() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var wrongPassword = new NpgsqlConnectionStringBuilder(proof.Database.PlatformConnectionString) + { + Password = "not-the-password", + Pooling = false, + }.ConnectionString; + var unreachable = new NpgsqlConnectionStringBuilder(proof.Database.PlatformConnectionString) + { + Host = "127.0.0.1", + Port = 1, + Pooling = false, + Timeout = 3, + }.ConnectionString; + await using var refusedSource = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(wrongPassword); + await using var unreachableSource = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(unreachable); + + // A retry cannot cure a refused credential, so it surfaces as the defect it is and not as a retryable outage. + var refused = async () => await proof.InspectionOver(refusedSource) + .InspectOutboxAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + (await refused.Should().ThrowAsync()).Which.IsTransient.Should().BeFalse(); + + var outage = async () => await proof.InspectionOver(unreachableSource) + .InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 10); + (await outage.Should().ThrowAsync()).Which.InnerException.Should().BeAssignableTo(); + } + + [Fact] + public async Task Deliveries_with_equal_instants_page_by_tenant_then_subscription_then_event() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + // The event ids run against the subscriptions' order, so a keyset that dropped a column would skip a row. + var larger = Guid.Parse("ffffffff-0000-7000-8000-000000000001"); + var smaller = Guid.Parse("00000000-0000-7000-8000-000000000001"); + const string instant = "terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.000001+00'"; + await proof.DeliveryAsync(larger, "a.first.v1", instant); + await proof.DeliveryAsync(smaller, "b.second.v1", instant); + + var first = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, null, 1); + var second = await proof.Inspection.InspectDeliveriesAsync(Proof.Admission(), DeliveryInspectionState.DeadLettered, first!.NextCursor, 1); + + first.Items.Single().SubscriptionId.Should().Be("a.first.v1"); + second!.Items.Single().SubscriptionId.Should().Be("b.second.v1", "the subscription orders before the event id"); + second.NextCursor.Should().BeNull(); + } + + [Fact] + public async Task The_dead_letter_indexes_exist_with_the_keys_and_predicates_the_inspection_orders_and_filters_by() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + async Task Definition(string index) + { + await using var command = new NpgsqlCommand("SELECT indexdef FROM pg_indexes WHERE indexname = @name", (NpgsqlConnection)platform); + command.Parameters.AddWithValue("name", index); + return await command.ExecuteScalarAsync() as string; + } + + (await Definition("ix_outbox_messages_dead_lettered")).Should() + .Contain("(dead_lettered_at, id)").And.Contain("WHERE (dead_lettered_at IS NOT NULL)"); + (await Definition("ix_event_deliveries_dead_lettered")).Should() + .Contain("(dead_lettered_at, tenant_id, subscription_id, event_id)").And.Contain("WHERE (dead_lettered_at IS NOT NULL)"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task The_dead_lettered_pages_use_their_partial_index_in_key_order_with_no_sort(bool afterCursor) + { + // The statement is the text the inspection runs. Sequential and bitmap scans are disabled so that the only + // plan left is an ordered scan of the index: the index being absent from it, or a Sort above it, means the + // statement's predicate or its order no longer matches the index, and a page would scan and sort every dead + // letter. + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.SqlAsync($""" + INSERT INTO outbox_messages (id, tenant_id, organization_id, occurred_at, correlation_id, type, topic, partition_key, + payload, attempts, terminal_reason, dead_lettered_at, processed_at) + SELECT uuidv7(), '{SchemaFixture.TenantA}', '{SchemaFixture.OrgA1}', now(), 'c', '{KnownType}', + 'learnstack.test.inspection', 'k', '[]'::jsonb, CASE WHEN g % 30 = 0 THEN 6 ELSE 0 END, + CASE WHEN g % 30 = 0 THEN 'retry_exhausted' END, + CASE WHEN g % 30 = 0 THEN now() - make_interval(secs => g) END, + CASE WHEN g % 30 = 0 THEN NULL ELSE now() END + FROM generate_series(1, 6000) g; + INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization_id, occurred_at, correlation_id, type, + topic, partition_key, payload, terminal_reason, dead_lettered_at, processed_at) + SELECT '{SchemaFixture.TenantA}', '{Subscription}', uuidv7(), '{SchemaFixture.OrgA1}', now(), 'c', '{KnownType}', + 'learnstack.test.inspection', 'k', '[]'::jsonb, + CASE WHEN g % 30 = 0 THEN 'retry_exhausted' END, + CASE WHEN g % 30 = 0 THEN now() - make_interval(secs => g) END, + CASE WHEN g % 30 = 0 THEN NULL ELSE now() END + FROM generate_series(1, 6000) g; + ANALYZE outbox_messages; + ANALYZE event_deliveries; + """); + await using var platform = await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + + async Task Plan(string sql, params (string Name, object Value)[] parameters) + { + await using var command = new NpgsqlCommand("SET enable_seqscan = off; SET enable_bitmapscan = off; EXPLAIN (FORMAT JSON) " + sql, (NpgsqlConnection)platform); + foreach (var (name, value) in parameters) command.Parameters.AddWithValue(name, value); + return (await command.ExecuteScalarAsync())!.ToString()!; + } + + var after = new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero); + var outbox = await Plan( + DeliveryInspection.OutboxSql(DeliveryInspectionState.DeadLettered, afterCursor), + [("size", 21), .. afterCursor ? new (string, object)[] { ("after", after), ("key", Guid.CreateVersion7()) } : []]); + var delivery = await Plan( + DeliveryInspection.DeliverySql(DeliveryInspectionState.DeadLettered, afterCursor), + [("size", 21), .. afterCursor + ? new (string, object)[] { ("after", after), ("tenant", SchemaFixture.TenantA), ("subscription", Subscription), ("event", Guid.CreateVersion7()) } + : []]); + + outbox.Should().Contain("ix_outbox_messages_dead_lettered").And.NotContain("\"Node Type\": \"Sort\"").And.NotContain("Seq Scan"); + delivery.Should().Contain("ix_event_deliveries_dead_lettered").And.NotContain("\"Node Type\": \"Sort\"").And.NotContain("Seq Scan"); + } + + [IntegrationEventPartition(nameof(TenantId), tenantWide: true)] + public sealed record InspectionEvent : IntegrationEventBase + { + public override string Topic => "learnstack.test.inspection"; + public override string PartitionKey => TenantId.ToString("D"); + } + + public sealed class InspectionHandler : IIntegrationEventHandler + { + public Task HandleAsync(InspectionEvent fact, CancellationToken cancellationToken) => Task.CompletedTask; + } + + private sealed class Proof : IAsyncDisposable + { + private readonly PostgresFixture _postgres; + private readonly NpgsqlDataSource _platform; + private readonly OutboxEventRegistry _registry; + + private Proof(PostgresFixture postgres, DisposableSchemaDatabase database) + { + _postgres = postgres; + Database = database; + _platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); + var handlers = IntegrationEventHandlerRegistry.FromServiceDescriptors( + [ServiceDescriptor.Scoped, InspectionHandler>()]); + _registry = OutboxEventRegistry.Create( + [OutboxEventRegistration.Required(typeof(InspectionEvent), [OutboxSubscriptionManifest.Active(Subscription, typeof(InspectionHandler))], + "declared.previous.inspection")], [], handlers, [typeof(InspectionEvent).Assembly]); + Inspection = InspectionOver(_platform); + } + + /// The inspection as production builds it, over the platform data source a test supplies. + internal DeliveryInspection InspectionOver(NpgsqlDataSource platform) => new( + new PlatformAdminScope( + new PrivilegedDataSource(() => platform), new AuditCatalog([new TenancyAuditCatalogSource()]), + AuditStoreScopeFactory(), new SystemClock(), new SystemGuidFactory(), NullLogger.Instance), + _registry); + + internal DisposableSchemaDatabase Database { get; } + + internal DeliveryInspection Inspection { get; } + + internal static async Task CreateAsync(PostgresFixture postgres) + { + var proof = new Proof(postgres, await DisposableSchemaDatabase.CreateAsync(postgres)); + await proof.SqlAsync($""" + INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row_version) + VALUES ('{SchemaFixture.TenantA}', 'inspection', 'Inspection', 'Trial', now(), '{UserId.SystemActor.Value}', 0); + INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at, created_by, row_version) + VALUES ('{SchemaFixture.OrgA1}', '{SchemaFixture.TenantA}', 'hq', 'HQ', 'Active', now(), '{UserId.SystemActor.Value}', 0); + UPDATE tenants SET default_organization_id = '{SchemaFixture.OrgA1}' WHERE id = '{SchemaFixture.TenantA}'; + """); + return proof; + } + + internal static PlatformAdmission Admission(string? ticket = null) => TestPlatformAdmissions.Admission( + PlatformOperations.DeliveryInspect, ticket, correlationId: "00-inspect-" + Guid.NewGuid().ToString("N")); + + internal Task OutboxAsync(Guid id, string assignments) => SqlAsync($""" + INSERT INTO outbox_messages (id, tenant_id, organization_id, occurred_at, correlation_id, type, topic, partition_key, payload) + VALUES ('{id}', '{SchemaFixture.TenantA}', '{SchemaFixture.OrgA1}', '2026-10-01 12:00:00+00', 'c', '{KnownType}', 'learnstack.test.inspection', 'k', '[]'::jsonb); + UPDATE outbox_messages SET {assignments} WHERE id = '{id}'; + """); + + internal Task DeliveryAsync(Guid id, string subscription, string assignments) => SqlAsync($""" + INSERT INTO event_deliveries (tenant_id, subscription_id, event_id, organization_id, occurred_at, correlation_id, type, topic, partition_key, payload) + VALUES ('{SchemaFixture.TenantA}', '{subscription}', '{id}', '{SchemaFixture.OrgA1}', '2026-10-01 12:00:00+00', 'c', '{KnownType}', 'learnstack.test.inspection', 'k', '[]'::jsonb); + UPDATE event_deliveries SET {assignments} WHERE event_id = '{id}'; + """); + + internal async Task> AuditAsync(string correlation) + { + await using var connection = await PostgresFixture.OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT operation, reason, metadata::text FROM audit_log WHERE correlation_id = @c ORDER BY timestamp", (NpgsqlConnection)connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List<(string, string?, string)>(); + while (await reader.ReadAsync()) rows.Add((reader.GetString(0), reader.IsDBNull(1) ? null : reader.GetString(1), reader.GetString(2))); + return rows; + } + + internal Task SqlAsync(string sql) => _postgres.ExecuteAsSuperuserAsync(sql, RebindProofSupport.DatabaseOf(Database.MigrationConnectionString)); + + public async ValueTask DisposeAsync() + { + await _platform.DisposeAsync(); + await Database.DisposeAsync(); + } + + private static IServiceScopeFactory AuditStoreScopeFactory() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The scope's row is written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs b/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs index 7020b606c..2e600621c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DisposableSchemaDatabase.cs @@ -22,12 +22,14 @@ private DisposableSchemaDatabase(PostgresFixture postgres) AppConnectionString = For(postgres.AppConnectionString); PlatformConnectionString = For(postgres.PlatformConnectionString); OutboxConnectionString = For(postgres.OutboxConnectionString); + IdentityRebindConnectionString = For(postgres.IdentityRebindConnectionString); } public string MigrationConnectionString { get; } public string AppConnectionString { get; } public string PlatformConnectionString { get; } public string OutboxConnectionString { get; } + public string IdentityRebindConnectionString { get; } public static async Task CreateAsync( PostgresFixture postgres, bool applyMigrations = true) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs index 3cd0673e9..d20c60e43 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EventDeliveryMigrationTests.cs @@ -40,6 +40,14 @@ INSERT INTO event_deliveries "terminal_reason", "dead_lettered_at", "replay_count", "replayed_at", ]; + /// ADR-0103: the metadata an operator inspects, with no envelope, causal, routing or lease-token column. + private static readonly string[] PlatformInspectionColumns = + [ + "tenant_id", "subscription_id", "event_id", "organization_id", "occurred_at", "type", "processed_at", + "attempts", "last_error", "available_after", "locked_until", "terminal_reason", "dead_lettered_at", + "replay_count", "replayed_at", + ]; + private static readonly string[] SchedulerReadColumns = [ "tenant_id", "subscription_id", "event_id", "organization_id", "occurred_at", @@ -88,7 +96,10 @@ AND relname IN ('inbox_messages','event_deliveries') } await context.Database.MigrateAsync(); - (await InventoryAsync(database.MigrationConnectionString)).Should().Equal(before); + // The database was built at this migration and brought to the head, so what later migrations add to these two + // tables (the platform role's inspection grants and the dead-letter index, ADR-0103) is not a difference. + (await InventoryAsync(database.MigrationConnectionString)).Where(item => !AddedAfterTheLedger(item)) + .Should().Equal(before); await using var restored = await PostgresFixture.OpenAsync(database.AppConnectionString); await using var restoredTransaction = await restored.BeginTransactionAsync(); await AnnounceAsync(restored, restoredTransaction, SchemaFixture.TenantA); @@ -134,6 +145,7 @@ SELECT column_name FROM information_schema.columns ("learnstack_app", "INSERT") => AcceptanceColumns.ToList(), ("learnstack_app", "UPDATE") => ["processed_at"], ("learnstack_outbox_admin", "SELECT") => SchedulerReadColumns.ToList(), + ("learnstack_platform", "SELECT") => PlatformInspectionColumns.ToList(), ("learnstack_outbox_admin", "UPDATE") => SchedulingColumns.ToList(), _ => [], }; @@ -905,6 +917,10 @@ SELECT column_name FROM information_schema.column_privileges return result; } + private static bool AddedAfterTheLedger(string item) => + item.StartsWith("grant:event_deliveries:learnstack_platform:", StringComparison.Ordinal) + || item.Contains("ix_event_deliveries_dead_lettered", StringComparison.Ordinal); + private static async Task> InventoryAsync(string connectionString) { await using var owner = await PostgresFixture.OpenAsync(connectionString); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs new file mode 100644 index 000000000..0c72c09e1 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs @@ -0,0 +1,1103 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Federation; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.FederationConnectionSchemaSeed; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The operator's federation report, remove and disable against a real database and the real platform scope (ADR-0099 +/// Amendment 10 and 11): the rows are read as learnstack_platform through its four granted columns, the realm is +/// a scripted provider, and every act's intent and completion rows are read back as written. +/// +/// +/// The database is an isolated one that holds a tombstone and a live connection of tenant A and a live connection of +/// tenant B, as the shared schema does. A tenant can hold only one live connection, so no test writes a connection row, +/// and every act writes audit rows under tenant A or B: audit_log is append-only, so those rows stay out of the shared +/// schema, whose isolation census counts what each seeded tenant sees. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class FederationBrokerOperationsTests(FederationBrokerOperationsTests.FederationDatabase database) + : IClassFixture +{ + /// One isolated, fully migrated database with tenants A and B and the federation rows of the shared seed. + public sealed class FederationDatabase(SchemaFixture schema) : IAsyncLifetime + { + private DisposableSchemaDatabase? _database; + + /// A tenant with no connection row, for the case where a live row appears after the intent. + public static readonly Guid TenantC = Guid.Parse("33333333-3333-7333-8333-333333333333"); + + public string PlatformConnectionString => _database!.PlatformConnectionString; + + public string AppConnectionString => _database!.AppConnectionString; + + public async Task InitializeAsync() + { + _database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await using (var owner = await PostgresFixture.OpenAsync(_database.MigrationConnectionString)) + { + foreach (var (tenant, slug) in new[] { (SchemaFixture.TenantA, "alpha"), (SchemaFixture.TenantB, "beta"), (FederationDatabase.TenantC, "gamma") }) + { + await using var transaction = await owner.BeginTransactionAsync(); + await SchemaQueries.ExecuteAsync(owner, transaction, $"SET LOCAL app.tenant_id = '{tenant:D}'"); + await SchemaQueries.ExecuteAsync( + owner, transaction, + "INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row_version) " + + "VALUES (@id, @slug, @slug, 'Trial', now(), @actor, 0)", + ("id", tenant), ("slug", slug), ("actor", SchemaFixture.Actor)); + await transaction.CommitAsync(); + } + } + + await FederationConnectionSchemaSeed.SeedAsync(_database.AppConnectionString); + } + + public async Task DisposeAsync() + { + if (_database is not null) await _database.DisposeAsync(); + } + } + + private static FederationBrokerOwner OwnerOf(Guid connection, Guid? tenant = null) => + new(TenantId.From(tenant ?? SchemaFixture.TenantA), connection, Alias(connection)); + + private static FederationBrokerFacts Facts(FederationBrokerOwner owner, bool readable = true, bool conforms = true, bool enabled = true) => + new(owner, readable, conforms, enabled, readable ? FederationBrokerProtocol.Oidc : null); + + [Fact] + public async Task A_report_names_a_broker_with_no_row_a_tombstone_and_an_unreadable_one_and_not_a_healthy_live_one() + { + var operations = new Scripted(); + var healthy = OwnerOf(LiveA); + var tombstoned = OwnerOf(TombstoneA); + var absent = OwnerOf(Guid.CreateVersion7()); + var unreadableLive = OwnerOf(LiveB, SchemaFixture.TenantB); + operations.Listed = [Facts(healthy), Facts(tombstoned), Facts(absent), Facts(unreadableLive, readable: false)]; + var service = Service(operations); + + var result = await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Ok); + result.Items.Select(item => (item.ConnectionId, string.Join('+', item.Classes), item.RowState)).Should().Equal( + (TombstoneA, "orphan", "deleted"), + (absent.ConnectionId, "orphan", "absent"), + (LiveB, "unreadable_owned", "Draft")); + result.Items.Should().OnlyContain(item => item.Alias.StartsWith("lsf-", StringComparison.Ordinal)); + result.Scanned.Should().Be(4); + // A healthy live broker with no mapper drift is no finding, and its mapper count was asked once. + operations.MapperCalls.Should().Equal(healthy.Alias); + result.Unread.Should().Be(0, "a tombstone, an absent row and an unreadable broker are never mapper-read, so none is unread"); + } + + [Fact] + public async Task A_report_enters_the_scope_first_reads_the_realm_next_and_the_rows_only_after_it() + { + // A tenant commits its row before it creates the broker, so a broker the realm listed already has its row when the + // rows are read; a reader that took the rows first would call a broker created in between an orphan. The order + // is observed, not inferred: the scope entry, the listing and the row query are recorded as they happen. + var events = new List(); + var operations = new Scripted { Listed = [Facts(OwnerOf(LiveA))], Events = events }; + var service = new FederationBrokerOperations(new RecordingScope(Scope(false, false), events), operations); + + await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + events.Should().Equal("enter", "list", "query", "mappers"); + } + + [Fact] + public async Task A_report_never_names_a_broker_whose_marker_and_row_disagree_about_the_tenant() + { + var operations = new Scripted(); + var wrongTenant = OwnerOf(LiveA, SchemaFixture.TenantB); + operations.Listed = [Facts(wrongTenant, readable: false)]; + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Items.Should().BeEmpty(); + result.Ignored.Should().Be(1, "it is counted and never named"); + } + + [Fact] + public async Task A_report_pages_by_an_opaque_cursor_it_issued_and_refuses_one_it_did_not() + { + var operations = new Scripted { Listed = [.. Enumerable.Range(0, 5).Select(_ => Facts(OwnerOf(Guid.CreateVersion7()), readable: false))] }; + var service = Service(operations); + + var first = await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 2); + var second = await service.ReportAsync(Admission(PlatformOperations.FederationReport), first.NextCursor, 2); + var last = await service.ReportAsync(Admission(PlatformOperations.FederationReport), second.NextCursor, 2); + + (first.Scanned, second.Scanned, last.Scanned).Should().Be((2, 2, 1)); + last.NextCursor.Should().BeNull(); + first.Items.Concat(second.Items).Concat(last.Items).Select(item => item.Alias).Should().OnlyHaveUniqueItems().And.HaveCount(5); + operations.Offsets.Should().Equal(0, 2, 4); + foreach (var forged in new[] { "x", "djF-ZmVkZXJhdGlvbn4tMQ", Convert.ToBase64String("v1~federation~-1"u8) }) + { + var refused = await service.ReportAsync(Admission(PlatformOperations.FederationReport), forged, 2); + refused.Outcome.Should().Be(FederationReportOutcome.InvalidCursor, forged); + } + + operations.Offsets.Should().Equal([0, 2, 4], "a refused cursor reaches no provider and enters no scope"); + } + + [Fact] + public async Task A_report_the_provider_cannot_answer_is_unavailable_and_writes_only_the_scopes_entry_row() + { + var operations = new Scripted { Unavailable = true }; + var admission = Admission(PlatformOperations.FederationReport, ticket: "CHG-1"); + + var result = await Service(operations).ReportAsync(admission, null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Unavailable); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + rows[0].Metadata.Should().Contain("CHG-1", "the entry row is a sentinel row, which carries the ticket"); + } + + [Theory] + [InlineData(true, true, true)] + [InlineData(true, false, true)] + [InlineData(true, true, false)] + [InlineData(false, true, true)] + public async Task A_remove_of_a_broker_that_reads_or_is_still_enabled_with_a_live_row_is_refused_before_anything_is_written_or_sent( + bool readable, bool conforms, bool enabled) + { + // A pair that reads is retired by the tenant's own Delete, and an unreadable broker that is still enabled may be + // serving: the operator disables it first (ADR-0099 Amendment 13 item 1). + var operations = new Scripted { Inspected = Facts(OwnerOf(LiveA), readable, conforms, enabled), InspectedMappers = conforms ? 0 : 1 }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, Alias(LiveA)); + + result.Outcome.Should().Be(FederationActOutcome.LiveConnection); + operations.Removed.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_remove_of_an_unreadable_disabled_broker_is_applied_even_with_a_live_row_because_the_tenants_delete_cannot_reach_it() + { + // The tenant's Delete reports an unreadable owned broker as foreign and fails, so a live row would otherwise hold it + // forever (ADR-0099 Amendment 12). It is disabled first, and the adapter proves that again at the delete. + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable: false, enabled: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Should().Be(new FederationActResult(FederationActOutcome.Applied, SchemaFixture.TenantA, LiveA)); + operations.Removed.Should().ContainSingle(); + operations.RemoveRequirements.Should().Equal([true], "the adapter is told to prove 'unreadable and disabled' at the delete"); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("rowState").GetString().Should().Be("Draft", "the live row is recorded as found"); + before.RootElement.GetProperty("classes").EnumerateArray().Select(item => item.GetString()).Should().Equal("unreadable_owned"); + (await ScalarAsync("SELECT count(*) FROM public.federation_connections WHERE id = @id AND state <> 'Deleted'", LiveA)) + .Should().Be(1, "the operator never writes the tenant's row"); + } + + [Fact] + public async Task A_remove_whose_broker_stopped_being_unreadable_and_disabled_before_the_delete_is_refused_by_the_provider_proof() + { + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable: false, enabled: false), RemoveOutcome = FederationOperatorOutcome.Refused }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Refused); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("refused"); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeFalse("nothing was deleted"); + } + + [Fact] + public async Task A_remove_of_an_orphan_does_not_ask_the_adapter_for_the_unreadable_proof() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: true, conforms: false), InspectedMappers = 1 }; + + await Service(operations).RemoveAsync(Admission(PlatformOperations.FederationRemove), owner.Alias); + + operations.RemoveRequirements.Should().Equal([false], "an orphan has no live row to be let through"); + } + + [Theory] + [InlineData("tombstone")] + [InlineData("absent")] + [InlineData("tenant_without_a_row")] + public async Task A_remove_of_an_orphan_writes_an_intent_before_the_provider_call_and_a_completion_after_it_under_the_markers_tenant(string kind) + { + var tenant = kind == "tenant_without_a_row" ? Guid.CreateVersion7() : SchemaFixture.TenantA; + var connection = kind == "tombstone" ? TombstoneA : Guid.CreateVersion7(); + var owner = OwnerOf(connection, tenant); + var operations = new Scripted { Inspected = Facts(owner, readable: false), InspectedMappers = 0 }; + var admission = Admission(PlatformOperations.FederationRemove, ticket: "CHG-5"); + operations.BeforeRemove = async () => + { + // The intent row is already committed when the provider is called: another connection sees it. + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + }; + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Should().Be(new FederationActResult(FederationActOutcome.Applied, tenant, connection)); + operations.Removed.Should().ContainSingle().Which.Should().Be(owner); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + (PlatformAdminScope.EnterOperation, "success"), + ("platform.federation.remove_attempt", "indeterminate"), + ("platform.federation.remove", "success")); + rows.Skip(1).Should().OnlyContain(row => row.Tenant == tenant, "the rows name the marker's tenant, never the sentinel"); + rows.Skip(1).Should().OnlyContain(row => !row.Metadata.Contains("CHG-5"), "a tenant can read these rows"); + rows[1].EntityId.Should().Be(connection.ToString("D")); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("applied"); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeTrue(); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("classes").EnumerateArray().Select(item => item.GetString()).Should().Contain("orphan"); + } + + [Fact] + public async Task A_remove_of_an_absent_or_foreign_broker_writes_no_tenant_row() + { + var operations = new Scripted { InspectedStatus = FederationInspectionStatus.Absent }; + var absent = Admission(PlatformOperations.FederationRemove); + (await Service(operations).RemoveAsync(absent, Alias(Guid.CreateVersion7()))).Outcome.Should().Be(FederationActOutcome.AlreadyApplied); + + operations.InspectedStatus = FederationInspectionStatus.NotOwned; + var foreign = Admission(PlatformOperations.FederationRemove); + (await Service(operations).RemoveAsync(foreign, Alias(Guid.CreateVersion7()))).Outcome.Should().Be(FederationActOutcome.NotOwned); + + operations.Removed.Should().BeEmpty(); + foreach (var admission in new[] { absent, foreign }) + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Theory] + [InlineData(FederationOperatorOutcome.Uncertain, "uncertain", FederationActOutcome.Uncertain)] + [InlineData(FederationOperatorOutcome.Unavailable, "unavailable", FederationActOutcome.Unavailable)] + [InlineData(FederationOperatorOutcome.Refused, "refused", FederationActOutcome.Refused)] + public async Task A_provider_that_does_not_apply_a_remove_is_recorded_in_the_completion_row( + FederationOperatorOutcome provider, string recorded, FederationActOutcome expected) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false), RemoveOutcome = provider }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(expected); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be(recorded); + } + + [Fact] + public async Task A_failed_intent_write_stops_the_remove_before_the_provider_is_called() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + + var act = async () => await Service(operations, failIntent: true).RemoveAsync(admission, owner.Alias); + + await act.Should().ThrowAsync(); + operations.Removed.Should().BeEmpty("the effect must not start on an intent nobody recorded"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Theory] + [InlineData("remove", FederationOperatorOutcome.Applied)] + [InlineData("remove", FederationOperatorOutcome.Uncertain)] + [InlineData("disable", FederationOperatorOutcome.Applied)] + public async Task A_completion_that_cannot_be_written_after_a_change_is_answered_as_the_unknown_outcome_and_leaves_the_intent_standing( + string act, FederationOperatorOutcome provider) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false), RemoveOutcome = provider, DisableOutcome = provider }; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations, failResult: true); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain, "the change was sent and its record was not written"); + (remove ? operations.Removed : operations.Disabled).Should().ContainSingle("the provider call had been made"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, remove ? "platform.federation.remove_attempt" : "platform.federation.disable_attempt"); + } + + [Fact] + public async Task A_completion_that_cannot_be_written_when_nothing_changed_is_still_the_audit_failure() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false), RemoveOutcome = FederationOperatorOutcome.Refused }; + var admission = Admission(PlatformOperations.FederationRemove); + + var act = async () => await Service(operations, failResult: true).RemoveAsync(admission, owner.Alias); + + await act.Should().ThrowAsync("a refused change recorded nowhere is safe to repeat"); + } + + [Fact] + public async Task A_caller_that_leaves_while_the_provider_changes_the_broker_is_recorded_as_uncertain_on_a_detached_budget() + { + var owner = OwnerOf(Guid.CreateVersion7()); + using var caller = new CancellationTokenSource(); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + operations.BeforeRemove = () => + { + // The request is aborted after the change may have been sent: the adapter rethrows the caller's cancellation. + caller.Cancel(); + throw new OperationCanceledException(caller.Token); + }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, owner.Alias, caller.Token); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("uncertain"); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeTrue("the change may have deleted the links"); + } + + [Theory] + [InlineData("remove")] + [InlineData("disable")] + public async Task A_marker_that_names_another_tenant_than_its_row_is_not_owned_and_writes_no_tenant_row(string act) + { + // The tombstone is tenant A's, and the instance's marker names tenant B: never touched, and no row names B. + var owner = OwnerOf(TombstoneA, SchemaFixture.TenantB); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.NotOwned); + operations.Removed.Should().BeEmpty(); + operations.Disabled.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_live_row_that_appears_after_the_intent_refuses_the_delete_and_is_recorded_without_calling_the_provider() + { + // Amendment 10 item 3: the row is read again immediately before the delete. A tenant commits its row at that moment. + var connection = Guid.CreateVersion7(); + var owner = OwnerOf(connection, FederationDatabase.TenantC); + var operations = new Scripted { Inspected = Facts(owner, readable: true, conforms: false), InspectedMappers = 1 }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations(Scope(false, false, afterIntent: async _ => + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, FederationDatabase.TenantC); + await InsertAsync(app, transaction, connection, FederationDatabase.TenantC, IdentityMembershipFixture.AdminA, + DateTimeOffset.UtcNow.AddMinutes(-5)); + await transaction.CommitAsync(); + }), operations, TimeSpan.FromSeconds(30)); + + var result = await service.RemoveAsync(admission, owner.Alias); + + result.Should().Be(new FederationActResult(FederationActOutcome.LiveConnection, FederationDatabase.TenantC, connection)); + operations.Removed.Should().BeEmpty("the provider is not called once the row is live"); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt", "platform.federation.remove"); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("rowState").GetString().Should().Be("absent", "the first read found no row"); + using var after = JsonDocument.Parse(rows[2].After); + (after.RootElement.GetProperty("outcome").GetString(), after.RootElement.GetProperty("cause").GetString()) + .Should().Be(("refused", "live_connection")); + after.RootElement.GetProperty("accountReviewOwed").GetBoolean().Should().BeFalse("nothing was changed"); + } + + [Theory] + [InlineData("io")] + [InlineData("closed")] + [InlineData("timeout")] + public async Task A_commit_that_fails_after_a_change_answers_the_unknown_outcome_whatever_the_failure_and_keeps_its_cause(string kind) + { + Exception fault = kind switch + { + "io" => new NpgsqlException("the connection dropped", new IOException("reset")), + "closed" => new InvalidOperationException("The transaction has completed"), + _ => new TimeoutException("the commit timed out"), + }; + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations( + new FaultingScope(Scope(false, false), new HandleFaults { Commit = fault }), operations, TimeSpan.FromSeconds(30)); + + var result = await service.RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain, "the change was sent and its record was not committed"); + result.Cause.Should().BeSameAs(fault, "the cause goes to the route's log"); + operations.Removed.Should().ContainSingle(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + } + + [Fact] + public async Task A_completion_write_that_outlives_its_budget_is_cut_and_answers_the_unknown_outcome() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations( + new FaultingScope(Scope(false, false), new HandleFaults { HangResult = true }), operations, TimeSpan.FromMilliseconds(200)); + + var result = await service.RemoveAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + result.Cause.Should().BeAssignableTo("the budget, not the request, cut the write"); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + } + + [Fact] + public async Task A_failure_while_the_handle_is_disposed_after_a_change_is_the_unknown_outcome_and_never_nothing_changed() + { + var owner = OwnerOf(Guid.CreateVersion7()); + var fault = new InvalidOperationException("the connection could not be returned"); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var service = new FederationBrokerOperations( + new FaultingScope(Scope(false, false), new HandleFaults { Dispose = fault }), operations, TimeSpan.FromSeconds(30)); + + var act = async () => await service.RemoveAsync(Admission(PlatformOperations.FederationRemove), owner.Alias); + + var thrown = (await act.Should().ThrowAsync()).Which; + (thrown.CommitOutcomeUnknown, thrown.InnerException).Should().Be((true, fault)); + } + + [Theory] + [InlineData("remove")] + [InlineData("disable")] + public async Task An_unexpected_provider_failure_after_the_change_may_have_been_sent_is_completed_as_uncertain_with_its_cause(string act) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var fault = new ObjectDisposedException("the host is shutting down"); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + operations.BeforeRemove = () => throw fault; + operations.BeforeDisable = () => throw fault; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + result.Cause.Should().BeSameAs(fault); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, remove ? "platform.federation.remove_attempt" : "platform.federation.disable_attempt", + remove ? "platform.federation.remove" : "platform.federation.disable"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be("uncertain"); + } + + [Fact] + public async Task A_caller_that_leaves_while_the_provider_disables_the_broker_is_recorded_as_uncertain() + { + var owner = OwnerOf(Guid.CreateVersion7()); + using var caller = new CancellationTokenSource(); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + operations.BeforeDisable = () => + { + caller.Cancel(); + throw new OperationCanceledException(caller.Token); + }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias, caller.Token); + + result.Outcome.Should().Be(FederationActOutcome.Uncertain); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.disable_attempt", "platform.federation.disable"); + } + + [Theory] + [InlineData("remove")] + [InlineData("disable")] + public async Task A_broker_the_provider_finds_already_gone_or_disabled_after_the_intent_is_recorded_as_already_applied_with_no_review_owed(string act) + { + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted + { + Inspected = Facts(owner, readable: false), + RemoveOutcome = FederationOperatorOutcome.AlreadyApplied, + DisableOutcome = FederationOperatorOutcome.AlreadyApplied, + }; + var remove = act == "remove"; + var admission = Admission(remove ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + var service = Service(operations); + + var result = remove ? await service.RemoveAsync(admission, owner.Alias) : await service.DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.AlreadyApplied); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Should().HaveCount(3, "it changed between the first read and the provider call, so both rows exist"); + using var after = JsonDocument.Parse(rows[2].After); + (after.RootElement.GetProperty("outcome").GetString(), after.RootElement.GetProperty("accountReviewOwed").GetBoolean()) + .Should().Be(("already_applied", false)); + } + + [Fact] + public async Task A_listing_that_runs_out_of_the_pages_time_is_unavailable_and_never_an_empty_realm() + { + var operations = new Scripted { ListFailure = new OperationCanceledException("the page's time ran out") }; + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Unavailable); + result.Items.Should().BeEmpty(); + } + + [Fact] + public async Task An_intent_commit_that_fails_for_any_reason_stops_the_act_as_the_audit_failure_before_the_provider_is_called() + { + // The connection is closed after the intent row is written and before it is committed, as a dropped link would be: + // the commit then fails with a failure that is not a database exception, and it must still be the audit failure. + var owner = OwnerOf(Guid.CreateVersion7()); + var operations = new Scripted { Inspected = Facts(owner, readable: false) }; + var admission = Admission(PlatformOperations.FederationRemove); + var service = new FederationBrokerOperations( + Scope(false, false, afterIntent: async connection => await connection.CloseAsync()), operations, TimeSpan.FromSeconds(30)); + + var act = async () => await service.RemoveAsync(admission, owner.Alias); + + await act.Should().ThrowAsync(); + operations.Removed.Should().BeEmpty("the effect must not start on an intent nobody can prove was recorded"); + } + + [Theory] + [InlineData(FederationOperatorOutcome.Uncertain, "uncertain", FederationActOutcome.Uncertain)] + [InlineData(FederationOperatorOutcome.Unavailable, "unavailable", FederationActOutcome.Unavailable)] + [InlineData(FederationOperatorOutcome.Refused, "refused", FederationActOutcome.Refused)] + [InlineData(FederationOperatorOutcome.NotOwned, "not_owned", FederationActOutcome.NotOwned)] + public async Task A_provider_that_does_not_apply_a_disable_is_recorded_in_the_completion_row( + FederationOperatorOutcome provider, string recorded, FederationActOutcome expected) + { + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable: false), DisableOutcome = provider }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(expected); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.disable_attempt", "platform.federation.disable"); + using var after = JsonDocument.Parse(rows[2].After); + after.RootElement.GetProperty("outcome").GetString().Should().Be(recorded); + } + + [Theory] + [InlineData(FederationInspectionStatus.Unavailable, FederationActOutcome.Unavailable)] + [InlineData(FederationInspectionStatus.Absent, FederationActOutcome.NotFound)] + [InlineData(FederationInspectionStatus.NotOwned, FederationActOutcome.NotOwned)] + public async Task A_disable_the_provider_cannot_inspect_or_that_names_nothing_it_owns_sends_nothing_and_writes_no_tenant_row( + FederationInspectionStatus status, FederationActOutcome expected) + { + var operations = new Scripted { InspectedStatus = status }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, Alias(Guid.CreateVersion7())); + + result.Outcome.Should().Be(expected); + operations.Disabled.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_provider_that_cannot_inspect_a_remove_sends_nothing_and_writes_no_tenant_row() + { + var operations = new Scripted { InspectedStatus = FederationInspectionStatus.Unavailable }; + var admission = Admission(PlatformOperations.FederationRemove); + + var result = await Service(operations).RemoveAsync(admission, Alias(Guid.CreateVersion7())); + + result.Outcome.Should().Be(FederationActOutcome.Unavailable); + operations.Removed.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Fact] + public async Task A_report_counts_the_mappers_of_a_healthy_broker_and_names_one_that_carries_drift() + { + var healthy = OwnerOf(LiveA); + var operations = new Scripted { Listed = [Facts(healthy)] }; + operations.MapperCounts[healthy.Alias] = 2; + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + var item = result.Items.Should().ContainSingle().Which; + (string.Join('+', item.Classes), item.Mappers, item.RowState).Should().Be(("nonconforming", 2, "Draft")); + result.Unread.Should().Be(0); + } + + [Fact] + public async Task A_broker_whose_mappers_could_not_be_read_is_counted_as_unread_and_never_reported_as_clean() + { + var first = OwnerOf(LiveA); + var second = OwnerOf(LiveB, SchemaFixture.TenantB); + var operations = new Scripted { Listed = [Facts(first), Facts(second)] }; + operations.MapperCounts[first.Alias] = null; + operations.MapperDeadlines.Add(second.Alias); + + var result = await Service(operations).ReportAsync(Admission(PlatformOperations.FederationReport), null, 20); + + result.Outcome.Should().Be(FederationReportOutcome.Ok); + result.Items.Should().BeEmpty("a broker with no mapper count is unknown, and an unknown broker is not a finding"); + result.Unread.Should().Be(2, "the page says how many healthy-looking brokers it could not clear"); + } + + [Theory] + [InlineData("report")] + [InlineData("remove")] + [InlineData("disable")] + public async Task A_transient_database_fault_is_the_unavailable_owner_with_its_cause_and_never_a_raw_failure(string act) + { + var fault = new NpgsqlException("the database is not reachable", new IOException("reset")); + var owner = OwnerOf(Guid.CreateVersion7()); + var service = new FederationBrokerOperations(new ThrowingScope(fault), new Scripted { Inspected = Facts(owner, readable: false) }); + + var call = act switch + { + "report" => (Func)(async () => await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 5)), + "remove" => async () => await service.RemoveAsync(Admission(PlatformOperations.FederationRemove), owner.Alias), + _ => async () => await service.DisableAsync(Admission(PlatformOperations.FederationDisable), owner.Alias), + }; + + (await call.Should().ThrowAsync()).Which.InnerException.Should().BeSameAs(fault); + } + + [Fact] + public async Task A_database_fault_that_is_not_transient_surfaces_as_the_defect_it_is() + { + var defect = new InvalidOperationException("a defect"); + var service = new FederationBrokerOperations(new ThrowingScope(defect), new Scripted()); + + var report = async () => await service.ReportAsync(Admission(PlatformOperations.FederationReport), null, 5); + + (await report.Should().ThrowAsync()).Which.Should().BeSameAs(defect); + } + + [Theory] + [InlineData("healthy_live", FederationActOutcome.NotApplicable)] + [InlineData("already_disabled", FederationActOutcome.AlreadyApplied)] + public async Task A_disable_that_nothing_needs_writes_no_row_and_sends_nothing(string kind, FederationActOutcome expected) + { + var owner = OwnerOf(LiveA); + var facts = kind == "healthy_live" ? Facts(owner) : Facts(owner, readable: false, enabled: false); + var operations = new Scripted { Inspected = facts }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(expected); + operations.Disabled.Should().BeEmpty(); + (await RowsAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + [Theory] + [InlineData("unreadable", false, true, 0)] + [InlineData("profile_drift", true, false, 0)] + [InlineData("mapper_drift", true, true, 2)] + public async Task A_disable_of_a_broker_the_tenant_cannot_reach_or_that_has_drifted_is_applied_with_two_rows( + string kind, bool readable, bool conforms, int mappers) + { + var owner = OwnerOf(LiveA); + var operations = new Scripted { Inspected = Facts(owner, readable, conforms), InspectedMappers = mappers }; + var admission = Admission(PlatformOperations.FederationDisable); + + var result = await Service(operations).DisableAsync(admission, owner.Alias); + + result.Outcome.Should().Be(FederationActOutcome.Applied, kind); + operations.Disabled.Should().ContainSingle(); + var rows = await RowsAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, "platform.federation.disable_attempt", "platform.federation.disable"); + using var before = JsonDocument.Parse(rows[1].Before); + before.RootElement.GetProperty("classes").EnumerateArray().Select(item => item.GetString()).Should().Contain( + readable ? "nonconforming" : "unreadable_owned"); + before.RootElement.GetProperty("rowState").GetString().Should().Be("Draft", "the tenant's own row is left as found"); + } + + [Fact] + public async Task An_admission_for_another_operation_is_refused_by_each_entry_before_the_provider_or_the_scope() + { + var operations = new Scripted(); + var service = Service(operations); + var wrong = Admission(PlatformOperations.FederationReport); + + var remove = async () => await service.RemoveAsync(wrong, Alias(Guid.CreateVersion7())); + var disable = async () => await service.DisableAsync(wrong, Alias(Guid.CreateVersion7())); + var report = async () => await service.ReportAsync(Admission(PlatformOperations.FederationRemove), null, 5); + + await remove.Should().ThrowAsync(); + await disable.Should().ThrowAsync(); + await report.Should().ThrowAsync(); + operations.Calls.Should().BeEmpty(); + (await RowsAsync(wrong.Operator.CorrelationId!)).Should().BeEmpty("no scope was entered"); + } + + [Fact] + public async Task The_platform_role_reads_exactly_the_four_projection_columns_and_writes_nothing() + { + await using var platform = await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT attname FROM pg_attribute + WHERE attrelid = 'public.federation_connections'::regclass AND attnum > 0 AND NOT attisdropped + AND has_column_privilege('learnstack_platform', 'public.federation_connections', attnum, 'SELECT') + ORDER BY attname + """, (NpgsqlConnection)platform); + var granted = new List(); + await using (var reader = await command.ExecuteReaderAsync()) + while (await reader.ReadAsync()) granted.Add(reader.GetString(0)); + granted.Should().Equal("deleted_at", "id", "state", "tenant_id"); + + foreach (var sql in new[] + { + "SELECT alias FROM public.federation_connections", "SELECT display_name FROM public.federation_connections", + "SELECT issuer_or_entity_id FROM public.federation_connections", "SELECT * FROM public.federation_connections", + "SELECT client_id FROM public.federation_connections", "SELECT configuration_digest FROM public.federation_connections", + "UPDATE public.federation_connections SET state = 'Deleted'", "DELETE FROM public.federation_connections", + "INSERT INTO public.federation_connections (id) VALUES (gen_random_uuid())", + }) + { + await FluentActions.Awaiting(() => SchemaQueries.ExecuteAsync(platform, null, sql)).Should() + .ThrowAsync(sql).Where(failure => failure.SqlState == PostgresErrorCodes.InsufficientPrivilege, sql); + } + + // The granted four read across both tenants, which the role's BYPASSRLS makes possible. + await using var distinct = new NpgsqlCommand( + "SELECT count(DISTINCT tenant_id) FROM public.federation_connections", (NpgsqlConnection)platform); + ((long)(await distinct.ExecuteScalarAsync())!).Should().BeGreaterThanOrEqualTo(2); + } + + // A generous budget keeps the cases that finish well inside it from depending on a stalled runner. + private FederationBrokerOperations Service(Scripted operations, bool failIntent = false, bool failResult = false, TimeSpan? budget = null) => + new(Scope(failIntent, failResult), operations, budget ?? TimeSpan.FromSeconds(30)); + + private PlatformAdminScope Scope(bool failIntent, bool failResult, Func? afterIntent = null) + { + var platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); + var store = AuditStore(); + return new PlatformAdminScope( + new PrivilegedDataSource(() => platform), new AuditCatalog([new TenancyAuditCatalogSource()]), + failIntent || failResult || afterIntent is not null ? new FailingStore(store, failIntent, failResult, afterIntent) : store, + new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); + } + + private static PlatformAdmission Admission(PlatformOperation operation, string? ticket = null) => TestPlatformAdmissions.Admission( + operation, ticket, correlationId: "00-federation-" + Guid.NewGuid().ToString("N")); + + private async Task ScalarAsync(string sql, Guid id) + { + await using var connection = await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)connection); + command.Parameters.AddWithValue("id", id); + return (long)(await command.ExecuteScalarAsync())!; + } + + private async Task> RowsAsync(string correlation) + { + await using var connection = await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT operation, outcome::text, tenant_id, metadata::text, coalesce(before_state::text, ''), coalesce(after_state::text, ''), + coalesce(entity_id, '') + FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id + """, (NpgsqlConnection)connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + rows.Add(new AuditRow(reader.GetString(0), reader.GetString(1), reader.GetGuid(2), reader.IsDBNull(3) ? string.Empty : reader.GetString(3), + reader.GetString(4), reader.GetString(5), reader.GetString(6))); + return rows; + } + + private static IServiceScopeFactory AuditStore() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The scope's rows are written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + /// The real scope, recording the order in which its handle is entered and queried. + private sealed class RecordingScope(IPlatformAdminScope inner, List events) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) + { + events.Add("enter"); + return new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine), events); + } + + private sealed class Handle(IPlatformAdminScopeHandle inner, List events) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + inner.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) + { + events.Add("query"); + return inner.QueryAsync(sql, parameters, map, cancellationToken); + } + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + inner.WriteIntentAsync(intent, cancellationToken); + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + inner.WriteResultAsync(result, cancellationToken); + + public Task CommitAsync(CancellationToken cancellationToken = default) => inner.CommitAsync(cancellationToken); + + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } + + /// What a faulting handle does, each at the moment the owner reaches that call. + private sealed class HandleFaults + { + public Exception? Commit { get; init; } + public Exception? Dispose { get; init; } + public bool HangResult { get; init; } + } + + /// The real scope with a handle that fails its commit or its disposal, or hangs its result write until cut. + private sealed class FaultingScope(IPlatformAdminScope inner, HandleFaults faults) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine), faults); + + private sealed class Handle(IPlatformAdminScopeHandle real, HandleFaults faults) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + real.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) => real.QueryAsync(sql, parameters, map, cancellationToken); + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + real.WriteIntentAsync(intent, cancellationToken); + + public async Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) + { + if (faults.HangResult) await Task.Delay(Timeout.Infinite, cancellationToken); + await real.WriteResultAsync(result, cancellationToken); + } + + public Task CommitAsync(CancellationToken cancellationToken = default) => + faults.Commit is { } fault ? Task.FromException(fault) : real.CommitAsync(cancellationToken); + + public async ValueTask DisposeAsync() + { + await real.DisposeAsync(); + if (faults.Dispose is { } fault) throw fault; + } + } + } + + /// A scope whose database cannot be reached: entering it fails with the fault it was given. + private sealed class ThrowingScope(Exception fault) : IPlatformAdminScope + { + public Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => throw fault; + } + + private sealed record AuditRow(string Operation, string Outcome, Guid Tenant, string Metadata, string Before, string After, string EntityId); + + /// Fails the intent or the completion row of the operator, as an outage at that moment would. + private sealed class FailingStore( + IServiceScopeFactory inner, bool failIntent, bool failResult, Func? afterIntent = null) + : IServiceScopeFactory + { + public IServiceScope CreateScope() => new Scope(inner.CreateScope(), failIntent, failResult, afterIntent); + + private sealed class Scope( + IServiceScope inner, bool failIntent, bool failResult, Func? afterIntent) + : IServiceScope, IServiceProvider + { + public IServiceProvider ServiceProvider => this; + + public object? GetService(Type type) => type == typeof(IAuditStore) + ? new Decorator(inner.ServiceProvider.GetRequiredService(), failIntent, failResult, afterIntent) + : inner.ServiceProvider.GetService(type); + + public void Dispose() => inner.Dispose(); + } + + private sealed class Decorator( + IAuditStore store, bool failIntent, bool failResult, Func? afterIntent) : IAuditStore + { + public Task WritePlatformScopeAsync(AuditEntryDraft entry, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + store.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public async Task WritePlatformOperatorIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) + { + if (failIntent) throw new AuditWriteFailedException("forced intent failure"); + await store.WritePlatformOperatorIntentAsync(entry, admission, connection, transaction, cancellationToken); + // Between the intent and the provider call, as a tenant that commits a row at that moment would. + if (afterIntent is not null) await afterIntent(connection); + } + + public Task WritePlatformOperatorResultAsync(AuditEntryDraft entry, PlatformAdmission admission, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + failResult + ? throw new AuditWriteFailedException("forced result failure") + : store.WritePlatformOperatorResultAsync(entry, admission, connection, transaction, cancellationToken); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + } + + /// A scripted realm: what the provider lists, what it says about one alias, and how a change ends. + private sealed class Scripted : IFederationOperator + { + public IReadOnlyList Listed { get; set; } = []; + public bool Unavailable { get; set; } + public List? Events { get; set; } + public FederationBrokerFacts? Inspected { get; set; } + public int InspectedMappers { get; set; } + public FederationInspectionStatus? InspectedStatus { get; set; } + public FederationOperatorOutcome RemoveOutcome { get; set; } = FederationOperatorOutcome.Applied; + public FederationOperatorOutcome DisableOutcome { get; set; } = FederationOperatorOutcome.Applied; + public Func? BeforeRemove { get; set; } + public Func? BeforeDisable { get; set; } + public Exception? ListFailure { get; set; } + public List RemoveRequirements { get; } = []; + public Dictionary MapperCounts { get; } = new(StringComparer.Ordinal); + public HashSet MapperDeadlines { get; } = new(StringComparer.Ordinal); + public List Calls { get; } = []; + public List Offsets { get; } = []; + public List MapperCalls { get; } = []; + public List Removed { get; } = []; + public List Disabled { get; } = []; + + public Task ListAsync(int offset, int limit, CancellationToken cancellationToken = default) + { + Calls.Add("list"); + Events?.Add("list"); + Offsets.Add(offset); + if (ListFailure is not null) return Task.FromException(ListFailure); + if (Unavailable) return Task.FromResult(FederationBrokerPage.Unavailable); + var page = Listed.Skip(offset).Take(limit).ToList(); + return Task.FromResult(new FederationBrokerPage(FederationOperatorStatus.Ok, page, 0, page.Count)); + } + + public Task InspectAsync(string brokerAlias, CancellationToken cancellationToken = default) + { + Calls.Add("inspect"); + return Task.FromResult(InspectedStatus switch + { + FederationInspectionStatus.Absent => FederationBrokerInspection.Absent, + FederationInspectionStatus.NotOwned => FederationBrokerInspection.NotOwned, + FederationInspectionStatus.Unavailable => FederationBrokerInspection.Unavailable, + _ => new FederationBrokerInspection(FederationInspectionStatus.Owned, Inspected, InspectedMappers), + }); + } + + public Task CountMappersAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + Calls.Add("mappers"); + Events?.Add("mappers"); + MapperCalls.Add(owner.Alias); + if (MapperDeadlines.Contains(owner.Alias)) throw new OperationCanceledException("the page's time ran out"); + return Task.FromResult(MapperCounts.TryGetValue(owner.Alias, out var count) ? count : 0); + } + + public async Task RemoveAsync( + FederationBrokerOwner owner, bool requireDisabledUnreadable = false, CancellationToken cancellationToken = default) + { + Calls.Add("remove"); + Removed.Add(owner); + RemoveRequirements.Add(requireDisabledUnreadable); + if (BeforeRemove is { } hook) await hook(); + return RemoveOutcome; + } + + public async Task DisableAsync(FederationBrokerOwner owner, CancellationToken cancellationToken = default) + { + Calls.Add("disable"); + Disabled.Add(owner); + if (BeforeDisable is { } hook) await hook(); + return DisableOutcome; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs index f5a46f1a9..2b98a6c10 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.CreationAdmission.cs @@ -32,6 +32,25 @@ public async Task Self_bootstrap_uses_the_production_common_owner_and_repeat_con row.Outcome.Should().Be("success"); } + [Fact] + public async Task A_self_bootstrap_from_a_process_that_qualified_before_a_rebind_is_refused_and_creates_nothing() + { + // ADR-0104 § 5: the process qualified against the old issuer and kept running; the issuer then changed. + await using var provider = SelfProvider(); + await QualifyAsync(provider); + await using (var rebind = await OpenConnectionAsync(_database.IdentityRebindConnectionString)) + await using (var change = new NpgsqlCommand( + "UPDATE public.identity_authority SET issuer = 'https://after-the-rebind.example.test/realms/learnstack' WHERE id = 1", rebind)) + { + (await change.ExecuteNonQueryAsync()).Should().Be(1); + } + + var result = await BootstrapAsync(provider, Subject); + + result.Refusal.Should().Be(IdentityCreationRefusal.Unavailable, "the debit transaction reads the issuer after the rebind lock"); + (await CountsAsync()).Should().Be((0L, 0L)); + } + [Fact] public async Task Unadmitted_self_bootstrap_is_denied_before_any_creation_owner() { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs index 871ee49d5..c32ca8b0b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -407,12 +407,12 @@ private static CanonicalFunction[] CompiledFunctions() : attributes.Contains("STABLE", StringComparison.Ordinal) ? "s" : "v", attributes.Contains("STRICT", StringComparison.Ordinal)); }).OrderBy(function => function.Name, StringComparer.Ordinal).ToArray(); - functions.Should().HaveCount(28, "the closed set includes three provider definers, one target transition guard and the federation connection guard"); - functions.Count(function => function.Definer).Should().Be(15); + functions.Should().HaveCount(30, "the closed set includes three provider definers, one target transition guard, the federation connection guard, the operator resolver and the identity authority key guard"); + functions.Count(function => function.Definer).Should().Be(16); functions.Single(function => function.Name == "fn_tenancy_own_field_consent_scope").Signature .Should().Be("public.fn_tenancy_own_field_consent_scope(uuid,uuid,uuid,text,uuid,uuid,integer)", nameof(MembershipFieldConsentStorageTests.Definer_scope_is_subject_and_host_capped_with_a_closed_bounded_interface)); - functions.SelectMany(function => function.Triggers).Should().HaveCount(29); + functions.SelectMany(function => function.Triggers).Should().HaveCount(30); var globalNames = EffectiveFunctionDeclarations(migrationSql[0]) .Select(match => match.Groups["name"].Value.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); globalNames.Should().NotBeEmpty("the first Identity migration installs its confined global functions"); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs index ac5f86918..8791bc8b1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs @@ -55,7 +55,7 @@ SELECT set_config('app.identity_authority_id','not-a-uuid',true), } [Fact] - public async Task Applied_census_has_sixty_six_tables_and_exactly_fifteen_confined_definers() + public async Task Applied_census_has_sixty_six_tables_and_exactly_sixteen_confined_definers() { await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); await SchemaTableClasses.AssertCompleteAsync(owner); @@ -66,7 +66,7 @@ public async Task Applied_census_has_sixty_six_tables_and_exactly_fifteen_confin """, null); names.Should().Equal("fn_identity_admin_admission_state", "fn_identity_audit_creation_guard", "fn_identity_audit_evidence", "fn_identity_creation_attempt_admission", "fn_identity_invitation_entry", "fn_identity_membership_admission_guard", - "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", + "fn_identity_operator_resolve_user", "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", "fn_identity_self_membership_scopes", "fn_identity_user_capacity_guard", "fn_identity_user_creation_audit_guard", "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope"); (await ScalarAsync(owner, null, """ @@ -76,7 +76,7 @@ SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace AND r.rolname='learnstack_migration' AND NOT r.rolbypassrls AND 'search_path=pg_catalog'=ANY(p.proconfig) AND NOT EXISTS (SELECT 1 FROM aclexplode(p.proacl) acl WHERE acl.grantee=0) - """)).Should().Be(15); + """)).Should().Be(16); (await ScalarAsync(owner, null, """ SELECT count(*) FROM pg_class WHERE oid IN ('public.users'::regclass,'public.identity_authority'::regclass) AND relrowsecurity AND relforcerowsecurity diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs index 29dae3ef2..5d9f02c1b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs @@ -17,9 +17,10 @@ namespace LearnStack.Tests.Integration.Database; [Collection(SharedSchema.Name)] public sealed class GlobalIdentityUnitOfWorkTests(SchemaFixture schema) { + // The authority the shared schema fixture installed: a creation owner reads the stored authority and issuer after the + // rebind lock (ADR-0104 § 5), so a subject under any other pair is a process that qualified against other facts. private static readonly GlobalIdentitySubject Subject = new( - IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501")), - "https://identity.example/realms/learnstack", "unit-owner-proof-subject"); + IdentityMembershipFixture.Authority.AuthorityId, IdentityMembershipFixture.Authority.Issuer, "unit-owner-proof-subject"); [Fact] public async Task Read_only_global_owner_announces_only_self_authority_and_clears_unrelated_session_values() diff --git a/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs b/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs index c32793c9f..77958cb6c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/HangfireGenerationPhaseHarness.cs @@ -76,6 +76,7 @@ internal static async Task RunAsync(string scenario, st .WithEnvironment("LEARNSTACK_PLATFORM_PW", Guid.NewGuid().ToString("N")) .WithEnvironment("LEARNSTACK_OUTBOX_PW", outboxPassword) .WithEnvironment("LEARNSTACK_IDENTITY_INGRESS_PW", Guid.NewGuid().ToString("N")) + .WithEnvironment("LEARNSTACK_IDENTITY_REBIND_PW", Guid.NewGuid().ToString("N")) // Module commands append to its existing PostgreSQL arguments; // an extra executable token would become an invalid argument. .WithCommand("-c", "log_min_messages=panic", "-c", "log_min_error_statement=panic", diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs new file mode 100644 index 000000000..8ac1ec748 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindLockTests.cs @@ -0,0 +1,260 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The freeze of ADR-0104 § 5 against real PostgreSQL: authority qualification and the User-creation admission +/// take the shared form of the rebind lock, wait for a running rebind and then read the value it left. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindLockTests(PublicReadFixture parent) +{ + private const string OldIssuer = "https://old.example.test/realms/learnstack"; + private const string NewIssuer = "https://new.example.test/realms/learnstack"; + + [Fact] + public async Task A_start_that_overlaps_a_rebind_waits_for_it_and_then_fails_on_the_new_issuer() + { + await using var proof = await Proof.CreateAsync(parent); + var qualification = proof.Qualification(proof.Old); + await using var rebind = await proof.BeginRebindAsync(); + + var start = qualification.QualifyAsync(); + await proof.WaitForSharedWaiterAsync(); + start.IsCompleted.Should().BeFalse("the start waits for the lock and does not read the old value"); + + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + + var act = async () => await start; + (await act.Should().ThrowAsync()) + .Which.Message.Should().Be("Identity authority startup qualification is unavailable or does not match deployment configuration."); + qualification.Current.Should().BeNull("a failed qualification stays failed until the process restarts"); + + await proof.Qualification(proof.Renamed).QualifyAsync(); + } + + [Fact] + public async Task A_start_that_overlaps_a_rebind_that_rolls_back_qualifies_against_the_unchanged_issuer() + { + await using var proof = await Proof.CreateAsync(parent); + var qualification = proof.Qualification(proof.Old); + await using var rebind = await proof.BeginRebindAsync(); + await rebind.ChangeIssuerAsync(NewIssuer); + + var start = qualification.QualifyAsync(); + await proof.WaitForSharedWaiterAsync(); + await rebind.RollbackAsync(); + + await start; + qualification.Current.Should().Be(proof.Old); + } + + [Fact] + public async Task A_start_that_follows_a_committed_rebind_with_the_old_configuration_is_refused_without_waiting() + { + await using var proof = await Proof.CreateAsync(parent); + await using (var rebind = await proof.BeginRebindAsync()) + { + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + } + + var act = async () => await proof.Qualification(proof.Old).QualifyAsync(); + await act.Should().ThrowAsync(); + await proof.Qualification(proof.Renamed).QualifyAsync(); + } + + [Fact] + public async Task A_creation_during_a_rebind_is_refused_within_its_lock_timeout_and_binds_nobody() + { + await using var proof = await Proof.CreateAsync(parent); + var person = UserId.From(Guid.CreateVersion7()); + var subject = "locked-" + person.Value.ToString("N"); + RebindSession? rebind = null; + try + { + var timing = Stopwatch.StartNew(); + var result = await proof.Database.TryAdoptAsync(proof.Old, person, subject, async () => + { + rebind = await proof.BeginRebindAsync(); + timing.Restart(); + }); + timing.Stop(); + + result.IsBound.Should().BeFalse("the creation owner's 2 s lock timeout refuses it while the rebind runs"); + timing.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(15)); + } + finally + { + if (rebind is not null) await rebind.DisposeAsync(); + } + + (await proof.CountUsersAsync()).Should().Be(2, "no user was created"); + } + + [Fact] + public async Task A_process_that_qualified_before_a_rebind_cannot_create_a_user_after_it() + { + await using var proof = await Proof.CreateAsync(parent); + var person = UserId.From(Guid.CreateVersion7()); + + var result = await proof.Database.TryAdoptAsync(proof.Old, person, "straggler-" + person.Value.ToString("N"), async () => + { + await using var rebind = await proof.BeginRebindAsync(); + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + }); + + result.IsBound.Should().BeFalse("it would otherwise create a person from the old realm under the new issuer"); + (await proof.CountUsersAsync()).Should().Be(2); + } + + [Fact] + public async Task A_process_started_after_a_rebind_creates_users_under_the_new_issuer_with_the_same_authority() + { + await using var proof = await Proof.CreateAsync(parent); + await using (var rebind = await proof.BeginRebindAsync()) + { + await rebind.ChangeIssuerAsync(NewIssuer); + await rebind.CommitAsync(); + } + + var person = UserId.From(Guid.CreateVersion7()); + var result = await proof.Database.TryAdoptAsync(proof.Renamed, person, "after-" + person.Value.ToString("N")); + + result.IsBound.Should().BeTrue(); + result.Actor.Should().Be(person); + (await proof.CountUsersAsync()).Should().Be(3); + } + + private sealed class Proof : IAsyncDisposable + { + private readonly List _sources = []; + + private Proof(IdentityPublicReadFixture database) + { + Database = database; + Old = database.Registration; + Renamed = new IdentityAuthorityRegistration(Old.AuthorityId, NewIssuer); + } + + internal IdentityPublicReadFixture Database { get; } + + internal IdentityAuthorityRegistration Old { get; } + + /// The same stable authority under the new issuer, which is what the deployment configures afterwards. + internal IdentityAuthorityRegistration Renamed { get; } + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var first = UserId.From(Guid.CreateVersion7()); + var second = UserId.From(Guid.CreateVersion7()); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, OldIssuer, + new Dictionary + { + [first] = "lock-proof-" + first.Value.ToString("N"), + [second] = "lock-proof-" + second.Value.ToString("N"), + }); + return new Proof(database); + } + + internal IdentityAuthorityQualification Qualification(IdentityAuthorityRegistration registration) + { + var source = NpgsqlDataSource.Create(Database.AppConnectionString); + _sources.Add(source); + return new IdentityAuthorityQualification(new Lazy(() => source), registration); + } + + internal async Task BeginRebindAsync() + { + var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.IdentityRebindConnectionString); + var transaction = await connection.BeginTransactionAsync(); + var session = new RebindSession(connection, transaction); + await session.TakeLockAsync(); + return session; + } + + /// Observed from outside: a start's shared request is queued behind the exclusive holder. + internal async Task WaitForSharedWaiterAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.MigrationConnectionString); + var key = IdentityAdvisoryLockKey.ForAuthorityRebind(); + var deadline = Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(20)) + { + await using var command = new NpgsqlCommand( + """ + SELECT count(*) FROM pg_catalog.pg_locks + WHERE locktype = 'advisory' AND NOT granted AND mode = 'ShareLock' AND objsubid = 1 + AND ((classid::bigint << 32) | objid::bigint) = @key + """, connection); + command.Parameters.AddWithValue("key", key); + if ((long)(await command.ExecuteScalarAsync())! > 0) return; + await Task.Delay(50); + } + + throw new TimeoutException("No shared waiter queued behind the rebind lock."); + } + + internal async Task CountUsersAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.IdentityRebindConnectionString); + await using var command = new NpgsqlCommand("SELECT count(*) FROM public.users", connection); + return (long)(await command.ExecuteScalarAsync())!; + } + + public async ValueTask DisposeAsync() + { + foreach (var source in _sources) await source.DisposeAsync(); + await Database.DisposeAsync(); + } + } + + private sealed class RebindSession(NpgsqlConnection connection, NpgsqlTransaction transaction) : IAsyncDisposable + { + private bool _finished; + + internal async Task TakeLockAsync() + { + await using var command = new NpgsqlCommand("SELECT pg_catalog.pg_advisory_xact_lock(@key)", connection, transaction); + command.Parameters.AddWithValue("key", IdentityAdvisoryLockKey.ForAuthorityRebind()); + await command.ExecuteNonQueryAsync(); + } + + internal async Task ChangeIssuerAsync(string issuer) + { + await using var command = new NpgsqlCommand( + "UPDATE public.identity_authority SET issuer = @issuer WHERE id = 1", connection, transaction); + command.Parameters.AddWithValue("issuer", issuer); + (await command.ExecuteNonQueryAsync()).Should().Be(1); + } + + internal async Task CommitAsync() + { + await transaction.CommitAsync(); + _finished = true; + } + + internal async Task RollbackAsync() + { + await transaction.RollbackAsync(); + _finished = true; + } + + public async ValueTask DisposeAsync() + { + if (!_finished) await transaction.RollbackAsync(); + await transaction.DisposeAsync(); + await connection.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs new file mode 100644 index 000000000..be3efd5b0 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindStorageTests.cs @@ -0,0 +1,408 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; +using NpgsqlTypes; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The storage contract of learnstack_identity_rebind against real PostgreSQL (ADR-0104 § 2, § 7, § 8, +/// Database Standards § Controlled issuer rebind storage). +/// +/// +/// Table-level views do not show column grants, so every privilege is read from the column view, and every +/// refusal is exercised as the role itself rather than asserted from the grant text. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindStorageTests(PublicReadFixture parent) +{ + private const string Sentinel = "00000000-0000-7000-8000-000000000002"; + private const string NewIssuer = "https://new.example.test/realms/learnstack"; + + [Fact] + public async Task The_Role_Holds_Exactly_The_Declared_Column_Privileges_And_Nothing_Else() + { + await using var proof = await Proof.CreateAsync(parent); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString); + + var columns = await ReadAsync(owner, """ + SELECT table_name || '.' || column_name || ' ' || privilege_type + FROM information_schema.column_privileges + WHERE grantee = 'learnstack_identity_rebind' AND table_schema = 'public' + AND table_name NOT IN ('audit_log') + ORDER BY 1 + """); + columns.Should().Equal( + "identity_authority.authority_id SELECT", + "identity_authority.id SELECT", + "identity_authority.issuer SELECT", + "identity_authority.issuer UPDATE", + "users.authority_id SELECT", + "users.provider_subject SELECT", + "users.status SELECT", + "users.subject_key SELECT"); + + var audit = await ReadAsync(owner, """ + SELECT DISTINCT privilege_type FROM information_schema.column_privileges + WHERE grantee = 'learnstack_identity_rebind' AND table_schema = 'public' AND table_name = 'audit_log' + """); + audit.Should().Equal(["INSERT"], "the role writes audit rows and reads, changes and removes none"); + + var auditColumns = await ReadAsync(owner, """ + SELECT count(*)::text FROM information_schema.column_privileges p + JOIN information_schema.columns c USING (table_schema, table_name, column_name) + WHERE p.grantee = 'learnstack_identity_rebind' AND p.table_name = 'audit_log' AND p.privilege_type = 'INSERT' + """); + var allAuditColumns = await ReadAsync(owner, """ + SELECT count(*)::text FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'audit_log' + """); + auditColumns.Should().Equal(allAuditColumns, "the policy, not the column list, bounds the audit row"); + + var beyond = await ReadAsync(owner, """ + SELECT 'function ' || p.oid::regprocedure::text FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = 'public' + AND EXISTS (SELECT 1 FROM aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) a + WHERE a.grantee = 'learnstack_identity_rebind'::regrole) + UNION ALL SELECT 'schema create' WHERE has_schema_privilege('learnstack_identity_rebind', 'public', 'CREATE') + UNION ALL SELECT 'database create' WHERE has_database_privilege('learnstack_identity_rebind', current_database(), 'CREATE') + UNION ALL SELECT 'sequence ' || c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind = 'S' + AND CASE WHEN c.relkind = 'S' + THEN has_sequence_privilege('learnstack_identity_rebind', c.oid, 'USAGE,SELECT,UPDATE') END + """); + beyond.Should().BeEmpty("no function, schema CREATE, database CREATE or sequence privilege is granted to the role itself"); + } + + [Fact] + public async Task The_Role_Changes_The_Issuer_And_Nothing_Else_On_The_Authority_Row() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.Rebind.ScalarAsync("SELECT issuer FROM public.identity_authority WHERE id = 1")) + .Should().Be(proof.OldIssuer); + + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET authority_id = uuidv7() WHERE id = 1")) + .Should().Be("42501", "no column grant covers the stable key"); + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET id = 2 WHERE id = 1")) + .Should().Be("42501", "no column grant covers the singleton id"); + (await proof.Rebind.RefusalAsync("DELETE FROM public.identity_authority")).Should().Be("42501"); + (await proof.Rebind.RefusalAsync("INSERT INTO public.identity_authority (id, authority_id, issuer) VALUES (2, uuidv7(), 'https://x.example.test/realms/learnstack')")) + .Should().Be("42501"); + (await proof.Rebind.RefusalAsync("TRUNCATE public.identity_authority")).Should().Be("42501"); + (await proof.Rebind.RefusalAsync($"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1")) + .Should().BeNull("the one admitted change"); + + (await proof.ReadIssuerAsync()).Should().Be(NewIssuer); + (await proof.ReadAuthorityAsync()).Should().Be(proof.AuthorityId, "the stable key is untouched"); + } + + [Fact] + public async Task No_Other_Role_Can_Change_The_Issuer() + { + await using var proof = await Proof.CreateAsync(parent); + + foreach (var (name, connectionString) in new (string, string)[] + { + ("learnstack_app", proof.AppConnectionString), + ("learnstack_platform", proof.PlatformConnectionString), + ("learnstack_outbox_admin", proof.OutboxConnectionString), + }) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand( + $"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1", connection); + var act = async () => await command.ExecuteNonQueryAsync(); + (await act.Should().ThrowAsync(name)).Which.SqlState.Should().Be("42501", name); + } + + // The owner holds the privilege and no policy admits it: the row security filters its target away. + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString)) + { + await using var command = new NpgsqlCommand( + $"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1", owner); + (await command.ExecuteNonQueryAsync()).Should().Be(0, "no policy admits an owner update"); + } + + (await proof.ReadIssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task The_Key_Trigger_Refuses_A_Change_Of_The_Id_Or_The_Authority_Id_Whoever_Holds_The_Grant() + { + await using var proof = await Proof.CreateAsync(parent); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString)) + { + await IdentityMembershipFixture.ExecuteAsync(owner, null, + "GRANT UPDATE (id, authority_id) ON public.identity_authority TO learnstack_identity_rebind"); + } + + // The trigger is the second line behind the missing column grant, so it is proved with the grant present. + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET authority_id = uuidv7() WHERE id = 1")) + .Should().Be("23514"); + (await proof.Rebind.RefusalAsync("UPDATE public.identity_authority SET id = 2 WHERE id = 1")).Should().Be("23514"); + (await proof.Rebind.RefusalAsync($"UPDATE public.identity_authority SET issuer = '{NewIssuer}' WHERE id = 1")) + .Should().BeNull("an issuer change is not a key change"); + + (await proof.ReadAuthorityAsync()).Should().Be(proof.AuthorityId); + } + + [Fact] + public async Task The_Role_Reads_Four_User_Columns_Without_Any_Announcement_And_Writes_None() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.Rebind.ScalarAsync("SELECT count(*) FROM public.users WHERE authority_id = @authority", ("authority", proof.AuthorityId))) + .Should().Be(2, "the continuity proof reads every user of the stored authority"); + (await proof.Rebind.ScalarAsync( + "SELECT count(*) FROM public.users WHERE status = 'Active' AND provider_subject IS NOT NULL AND octet_length(subject_key) = 32")) + .Should().Be(2); + + foreach (var statement in new[] + { + "SELECT id FROM public.users", + "SELECT creation_audit_id FROM public.users", + "INSERT INTO public.users (id, authority_id, subject_key, provider_subject, status) VALUES (uuidv7(), uuidv7(), '\\x00', 'x', 'Active')", + "UPDATE public.users SET status = 'Closed'", + "DELETE FROM public.users", + }) + { + (await proof.Rebind.RefusalAsync(statement)).Should().Be("42501", statement); + } + + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.AppConnectionString); + await using var control = new NpgsqlCommand("SELECT count(*) FROM public.users", app); + (await control.ExecuteScalarAsync()).Should().Be(0L, "the control: the application role without its announcement sees no user"); + } + + [Fact] + public async Task The_Role_Inserts_The_Two_Rebind_Rows_And_Nothing_Else_Into_The_Audit_Log() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.Rebind.RefusalAsync(AuditInsert(Row()))).Should().BeNull("the intent row"); + (await proof.Rebind.RefusalAsync(AuditInsert(Row(operation: "identity.authority.rebind", outcome: "success")))) + .Should().BeNull("the result row"); + + await using (var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.PlatformConnectionString)) + { + await using var count = new NpgsqlCommand( + $"SELECT count(*) FROM public.audit_log WHERE tenant_id = '{Sentinel}' AND module = 'identity' AND operation LIKE 'identity.authority.rebind%'", + platform); + (await count.ExecuteScalarAsync()).Should().Be(2L); + } + + var refused = new (string Why, string Insert)[] + { + ("a real tenant", AuditInsert(Row(tenant: Guid.CreateVersion7().ToString("D")))), + ("an organization", AuditInsert(Row(organization: Guid.CreateVersion7().ToString("D")))), + ("another module", AuditInsert(Row(module: "tenancy"))), + ("the result slug with the intent outcome", AuditInsert(Row(operation: "identity.authority.rebind"))), + ("the intent slug with the result outcome", AuditInsert(Row(outcome: "success"))), + ("a failed outcome", AuditInsert(Row(outcome: "failed"))), + ("a Should row", AuditInsert(Row(operationClass: "Should"))), + ("another operation type", AuditInsert(Row(operationType: "Create"))), + ("another entity type", AuditInsert(Row(entityType: "User"))), + ("another reason", AuditInsert(Row(reason: "host_map"))), + ("an actor", AuditInsert(Row(actor: Guid.CreateVersion7().ToString("D")))), + ("a mail address", AuditInsert(Row(email: "operator@example.test"))), + ("a network address", AuditInsert(Row(ip: "203.0.113.7"))), + ("a user agent", AuditInsert(Row(agent: "rebind-tool"))), + ("no operator attribution", AuditInsert(Row(metadata: "{}"))), + }; + foreach (var (why, insert) in refused) + { + (await proof.Rebind.RefusalAsync(insert)).Should().Be("42501", why); + } + + // The creation witness guard of ADR-0072 refuses the one operation it governs, and the policy would refuse it too. + (await proof.Rebind.RefusalAsync(AuditInsert(Row(operation: "identity.user.create")))) + .Should().Be("23514", "the global creation guard answers before the policy"); + (await proof.Rebind.RefusalAsync(AuditInsert(Row(operation: "identity.authority.rebind_other")))) + .Should().Be("42501", "another operation of the identity module"); + + foreach (var statement in new[] + { + "SELECT count(*) FROM public.audit_log", + "UPDATE public.audit_log SET reason = 'x'", + "DELETE FROM public.audit_log", + "TRUNCATE public.audit_log", + }) + { + (await proof.Rebind.RefusalAsync(statement)).Should().Be("42501", statement); + } + } + + [Fact] + public async Task The_Role_Cannot_Widen_Its_Row_By_Announcing_A_Tenant_Of_Its_Own_Choosing() + { + // Any session can set the tenant setting the ordinary arm reads, so the arm must not admit this role at all: + // otherwise the policy that is meant to bound the role's rows would be whatever the role announced. + await using var proof = await Proof.CreateAsync(parent); + var victim = Guid.CreateVersion7().ToString("D"); + + foreach (var (why, tenant, operation, module) in new[] + { + ("a tenant's own trail", victim, "tenancy.tenant.suspend", "tenancy"), + ("the sentinel under another operation", Sentinel, "platform.killswitch.toggle", "platform"), + ("the sentinel under an identity operation", Sentinel, "identity.role.initialize", "identity"), + }) + { + var announce = $"SELECT set_config('app.tenant_id', '{tenant}', true); "; + var insert = AuditInsert(Row(tenant: tenant, module: module, operation: operation, outcome: "success")); + (await proof.Rebind.RefusalAsync(announce + insert)).Should().Be("42501", why); + } + } + + [Fact] + public async Task The_Rebind_Arm_Admits_The_Rebind_Role_And_No_Other_Role() + { + // The owner holds the privilege and no tenant or application arm applies to it, so only the role predicate of + // the rebind arm stands between it and a platform-sentinel row of exactly the admitted shape. + await using var proof = await Proof.CreateAsync(parent); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await using var command = new NpgsqlCommand(AuditInsert(Row()), owner, transaction); + + var act = async () => await command.ExecuteNonQueryAsync(); + + (await act.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + } + + [Fact] + public async Task The_Application_And_Ingress_Roles_Cannot_Write_The_Rebind_Rows() + { + await using var proof = await Proof.CreateAsync(parent); + + // The application role announces no tenant here and the sentinel guard of ADR-0072 refuses its attribution + // before the policy; the ingress role holds no audit privilege at all. + foreach (var (name, connectionString, expected) in new (string, string, string)[] + { + ("learnstack_app", proof.AppConnectionString, "23514"), + ("learnstack_identity_ingress", parent.Postgres.IdentityIngressConnectionString, "42501"), + }) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await using var command = new NpgsqlCommand(AuditInsert(Row()), connection, transaction); + var act = async () => await command.ExecuteNonQueryAsync(); + (await act.Should().ThrowAsync(name)).Which.SqlState.Should().Be(expected, name); + } + } + + private static async Task ReadAsync(NpgsqlConnection connection, string sql) + { + await using var command = new NpgsqlCommand(sql, connection); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(reader.GetString(0)); + } + + return [.. rows]; + } + + private static string Row( + string tenant = Sentinel, string? organization = null, string module = "identity", + string operation = "identity.authority.rebind_attempt", string operationType = "SecurityEvent", + string operationClass = "Must", string entityType = "IdentityAuthority", string outcome = "indeterminate", + string reason = "issuer_rebind", string? actor = null, string? email = null, + string metadata = """{"operator":{"issuer":"https://operator.example.test/realms/learnstack-hub"}}""", + string? ip = null, string? agent = null) => + string.Join('\u001f', tenant, organization ?? string.Empty, module, operation, operationType, operationClass, + entityType, outcome, reason, actor ?? string.Empty, email ?? string.Empty, metadata, ip ?? string.Empty, + agent ?? string.Empty); + + private static string AuditInsert(string row) + { + var f = row.Split('\u001f'); + string Nullable(string value) => value.Length == 0 ? "NULL" : $"'{value}'"; + return $""" + INSERT INTO public.audit_log + (id, tenant_id, organization_id, actor_user_id, actor_email, module, operation, operation_type, + operation_class, entity_type, entity_id, outcome, reason, metadata, ip_address, user_agent, timestamp) + VALUES (uuidv7(), '{f[0]}', {Nullable(f[1])}, {Nullable(f[9])}, {Nullable(f[10])}, '{f[2]}', '{f[3]}', '{f[4]}', + '{f[5]}', '{f[6]}', 'authority', '{f[7]}', '{f[8]}', '{f[11]}'::jsonb, + {(f[12].Length == 0 ? "NULL" : $"'{f[12]}'::inet")}, {Nullable(f[13])}, now()) + """; + } + + /// An installed authority, two bound users and a role session on its own connection each time. + private sealed class Proof : IAsyncDisposable + { + private readonly IdentityPublicReadFixture _database; + + private Proof(IdentityPublicReadFixture database) => _database = database; + + internal string OldIssuer => _database.Registration.Issuer; + internal Guid AuthorityId => _database.Registration.AuthorityId.Value; + internal string MigrationConnectionString => _database.MigrationConnectionString; + internal string AppConnectionString => _database.AppConnectionString; + internal string PlatformConnectionString => _database.PlatformConnectionString; + internal string OutboxConnectionString => _database.OutboxConnectionString; + internal RoleSession Rebind => new(_database.IdentityRebindConnectionString); + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var first = UserId.From(Guid.CreateVersion7()); + var second = UserId.From(Guid.CreateVersion7()); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, "https://old.example.test/realms/learnstack", + new Dictionary + { + [first] = "rebind-storage-" + first.Value.ToString("N"), + [second] = "rebind-storage-" + second.Value.ToString("N"), + }); + return new Proof(database); + } + + internal async Task ReadIssuerAsync() => await ReadAsApplicationAsync("SELECT issuer FROM public.identity_authority"); + + internal async Task ReadAuthorityAsync() => await ReadAsApplicationAsync("SELECT authority_id FROM public.identity_authority"); + + // Read through the application role, whose policy admits the one authority row. + private async Task ReadAsApplicationAsync(string sql) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var command = new NpgsqlCommand(sql, connection); + return (T)(await command.ExecuteScalarAsync())!; + } + + public ValueTask DisposeAsync() => _database.DisposeAsync(); + } + + private sealed class RoleSession(string connectionString) + { + /// The SQLSTATE the statement raises as the role, or null when it succeeds. + internal async Task RefusalAsync(string sql) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await connection.BeginTransactionAsync(); + try + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + await command.ExecuteNonQueryAsync(); + await transaction.CommitAsync(); + return null; + } + catch (PostgresException failure) + { + return failure.SqlState; + } + } + + internal async Task ScalarAsync(string sql, params (string Name, object Value)[] values) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand(sql, connection); + foreach (var (name, value) in values) + { + command.Parameters.Add(new NpgsqlParameter(name, value is Guid ? NpgsqlDbType.Uuid : NpgsqlDbType.Text) { Value = value }); + } + + return (T)(await command.ExecuteScalarAsync())!; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs new file mode 100644 index 000000000..17ee047e3 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindTests.cs @@ -0,0 +1,797 @@ +using System.Data.Common; +using System.Diagnostics.Metrics; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The controlled issuer rebind end to end on real PostgreSQL as the confined role (ADR-0104): the positive run, +/// every refusal class with its state and audit trail, the continuity rules, the freeze, and the failure windows. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindTests(PublicReadFixture parent) +{ + private const string NewIssuer = "https://new.example.test/realms/learnstack"; + + [Fact] + public async Task A_Rebind_Changes_Only_The_Issuer_And_Records_An_Intent_And_A_Result_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 3); + var before = await proof.UsersAsync(); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting([.. proof.Subjects, "brand-new-person"])); + + outcome.Result.Should().Be(IdentityRebindResult.Applied); + outcome.Continuity.Should().BeEquivalentTo(new IdentityRebindContinuityResult(3, 0, 0, 4, 0, 0, 0, 1)); + (await proof.IssuerAsync()).Should().Be(NewIssuer); + (await proof.AuthorityAsync()).Should().Be(proof.Authority); + (await proof.UsersAsync()).Should().Equal(before, "no actor id, key or subject moved"); + + var rows = await proof.AuditRowsAsync(admission); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + ("identity.authority.rebind_attempt", "indeterminate"), ("identity.authority.rebind", "success")); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null + && row.Reason == "issuer_rebind" && row.Entity == proof.Authority.ToString("D")); + rows.Should().OnlyContain(row => row.Operator.GetProperty("ticket").GetString() == "CHG-104" + && row.Operator.GetProperty("subjectDigest").GetString() == admission.Operator.SubjectDigest); + rows[1].Before.GetProperty("issuer").GetString().Should().Be(proof.OldIssuer); + rows[1].After.GetProperty("issuer").GetString().Should().Be(NewIssuer); + rows[1].Continuity.GetProperty("active").GetInt32().Should().Be(3); + rows[1].Continuity.GetProperty("unbootstrapped").GetInt32().Should().Be(1); + rows[1].Raw.Should().NotContain(proof.Subjects[0], "no subject reaches an audit row"); + } + + [Fact] + public async Task A_Run_Whose_Target_Already_Equals_The_Stored_Issuer_Writes_Nothing_Not_Even_A_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var first = RebindProofSupport.Admit(); + (await proof.RunAsync(first, FixedRealm.Reporting(proof.Subjects))).Result.Should().Be(IdentityRebindResult.Applied); + + var again = RebindProofSupport.Admit(); + var realm = FixedRealm.Reporting(proof.Subjects); + var outcome = await proof.RunAsync(again, realm); + + outcome.Result.Should().Be(IdentityRebindResult.AlreadyApplied); + realm.Reads.Should().Be(0, "the new realm is not even read"); + (await proof.AuditRowsAsync(again)).Should().BeEmpty(); + (await proof.AuditRowsAsync(first)).Should().HaveCount(2); + } + + [Fact] + public async Task An_Admission_For_Another_Operation_Or_A_Stale_Or_A_Reused_One_Is_Refused_Before_Any_Connection() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + + var killswitch = TestPlatformAdmissions.Admission(PlatformOperations.KillswitchToggle, correlationId: "00-x"); + (await proof.RunAsync(killswitch, FixedRealm.Reporting(proof.Subjects))).Refusal.Should().Be(IdentityRebindRefusal.NotAdmitted); + + var stale = RebindProofSupport.Admit(issuedAt: DateTimeOffset.UtcNow.AddMinutes(-5)); + (await proof.RunAsync(stale, FixedRealm.Reporting(proof.Subjects))).Refusal.Should().Be(IdentityRebindRefusal.NotAdmitted); + + var used = RebindProofSupport.Admit(); + (await proof.RunAsync(used, FixedRealm.Reporting(proof.Subjects))).Result.Should().Be(IdentityRebindResult.Applied); + (await proof.RunAsync(used, FixedRealm.Reporting(proof.Subjects))).Refusal.Should().Be(IdentityRebindRefusal.NotAdmitted, + "an admission is spent by its first run"); + } + + [Theory] + [InlineData("learnstack_app")] + [InlineData("learnstack_migration")] + [InlineData("learnstack_platform")] + public async Task Any_Role_But_The_Rebind_Role_Is_Refused_Before_Its_First_Statement(string role) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var connection = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Username = role }.ConnectionString; + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: connection); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Theory] + // Role attributes and memberships are cluster-wide and need the superuser; object grants are this database's own. + [InlineData(true, "ALTER ROLE learnstack_identity_rebind CREATEDB", "ALTER ROLE learnstack_identity_rebind NOCREATEDB")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind INHERIT", "ALTER ROLE learnstack_identity_rebind NOINHERIT")] + [InlineData(true, "GRANT learnstack_migration TO learnstack_identity_rebind", "REVOKE learnstack_migration FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT ON public.tenants TO learnstack_identity_rebind", "REVOKE SELECT ON public.tenants FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT UPDATE (authority_id) ON public.identity_authority TO learnstack_identity_rebind", "REVOKE UPDATE (authority_id) ON public.identity_authority FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT (id) ON public.users TO learnstack_identity_rebind", "REVOKE SELECT (id) ON public.users FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT ON public.audit_log TO learnstack_identity_rebind", "REVOKE SELECT ON public.audit_log FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT CREATE ON SCHEMA public TO learnstack_identity_rebind", "REVOKE CREATE ON SCHEMA public FROM learnstack_identity_rebind")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind CREATEROLE", "ALTER ROLE learnstack_identity_rebind NOCREATEROLE")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind REPLICATION", "ALTER ROLE learnstack_identity_rebind NOREPLICATION")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind BYPASSRLS", "ALTER ROLE learnstack_identity_rebind NOBYPASSRLS")] + [InlineData(true, "ALTER ROLE learnstack_identity_rebind SUPERUSER", "ALTER ROLE learnstack_identity_rebind NOSUPERUSER")] + [InlineData(true, "GRANT learnstack_identity_rebind TO learnstack_app", "REVOKE learnstack_identity_rebind FROM learnstack_app")] + [InlineData(false, "GRANT UPDATE (status) ON public.users TO learnstack_identity_rebind", "REVOKE UPDATE (status) ON public.users FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT (deleted_by) ON public.users TO learnstack_identity_rebind", "REVOKE SELECT (deleted_by) ON public.users FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT UPDATE (id) ON public.identity_authority TO learnstack_identity_rebind", "REVOKE UPDATE (id) ON public.identity_authority FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT INSERT ON public.identity_authority TO learnstack_identity_rebind", "REVOKE INSERT ON public.identity_authority FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT SELECT (before_state) ON public.audit_log TO learnstack_identity_rebind", "REVOKE SELECT (before_state) ON public.audit_log FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT UPDATE (outcome) ON public.audit_log TO learnstack_identity_rebind", "REVOKE UPDATE (outcome) ON public.audit_log FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT DELETE ON public.tenants TO learnstack_identity_rebind", "REVOKE DELETE ON public.tenants FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT TRUNCATE ON public.tenants TO learnstack_identity_rebind", "REVOKE TRUNCATE ON public.tenants FROM learnstack_identity_rebind")] + // PostgreSQL 17 added a privilege that locks, vacuums and reindexes a table; it is a grant like any other. + [InlineData(false, "GRANT MAINTAIN ON public.tenants TO learnstack_identity_rebind", "REVOKE MAINTAIN ON public.tenants FROM learnstack_identity_rebind")] + [InlineData(false, "GRANT MAINTAIN ON public.users TO learnstack_identity_rebind", "REVOKE MAINTAIN ON public.users FROM learnstack_identity_rebind")] + // A declared grant that is missing is drift too: the proof reads users through four columns and changes one. + [InlineData(false, "REVOKE UPDATE (issuer) ON public.identity_authority FROM learnstack_identity_rebind", "GRANT UPDATE (issuer) ON public.identity_authority TO learnstack_identity_rebind")] + [InlineData(false, "REVOKE INSERT ON public.audit_log FROM learnstack_identity_rebind", "GRANT INSERT ON public.audit_log TO learnstack_identity_rebind")] + [InlineData(false, "REVOKE SELECT (status) ON public.users FROM learnstack_identity_rebind", "GRANT SELECT (status) ON public.users TO learnstack_identity_rebind")] + public async Task A_Role_That_Holds_Anything_Beyond_Its_Grants_Is_Refused_Before_The_Lock(bool clusterWide, string escalate, string restore) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + // The collection runs serially against its own container, and every escalation is undone in the same test. + await Apply(clusterWide, escalate); + try + { + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid, escalate); + outcome.Detail.Should().NotBe(IdentityRebindDetail.None, "the refusal names which check failed: " + escalate); + } + finally + { + await Apply(clusterWide, restore); + } + + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + + async Task Apply(bool superuser, string sql) + { + if (superuser) + { + await parent.Postgres.ExecuteAsSuperuserAsync(sql); + return; + } + + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.OwnerConnection); + await IdentityMembershipFixture.ExecuteAsync(owner, null, sql); + } + } + + [Theory] + // What only the superuser can put there, in this test's own database: a sequence the role may use, and the + // ownership of a function or a schema, which carry every privilege without any grant to read. + [InlineData("CREATE SEQUENCE public.rebind_probe_seq; GRANT USAGE ON SEQUENCE public.rebind_probe_seq TO learnstack_identity_rebind", + "DROP SEQUENCE public.rebind_probe_seq")] + [InlineData("CREATE FUNCTION public.rebind_probe_fn() RETURNS int LANGUAGE sql AS 'SELECT 1'; ALTER FUNCTION public.rebind_probe_fn() OWNER TO learnstack_identity_rebind", + "DROP FUNCTION public.rebind_probe_fn()")] + [InlineData("CREATE SCHEMA rebind_probe_schema AUTHORIZATION learnstack_identity_rebind", + "DROP SCHEMA rebind_probe_schema")] + [InlineData("CREATE VIEW public.rebind_probe_view AS SELECT 1 AS one; GRANT SELECT ON public.rebind_probe_view TO PUBLIC", + "DROP VIEW public.rebind_probe_view")] + public async Task A_Sequence_An_Owned_Object_Or_A_Public_Readable_Relation_The_Deployment_Added_Is_Refused(string add, string remove) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + await parent.Postgres.ExecuteAsSuperuserAsync(add, proof.Database); + try + { + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid, add); + outcome.Detail.Should().Be(IdentityRebindDetail.RoleGrants, add); + } + finally + { + await parent.Postgres.ExecuteAsSuperuserAsync(remove, proof.Database); + } + + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task The_Public_Readable_Views_Of_An_Extension_In_The_Public_Schema_Do_Not_Lock_The_Tool_Out() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + // pg_stat_statements is the extension a production database most often carries, and it grants its views to PUBLIC. + await parent.Postgres.ExecuteAsSuperuserAsync("CREATE EXTENSION pg_stat_statements SCHEMA public", proof.Database); + try + { + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcome.Result.Should().Be(IdentityRebindResult.Applied, "an extension's relations are not the deployment's own"); + } + finally + { + await parent.Postgres.ExecuteAsSuperuserAsync("DROP EXTENSION pg_stat_statements", proof.Database); + } + } + + [Fact] + public async Task A_Session_That_Appears_During_The_Realm_Read_Freezes_The_Run_Before_The_Change() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + IAsyncDisposable? late = null; + var realm = new FixedRealm(async (issuer, _) => + { + // A host that never takes the rebind lock starts while the proof runs. The server serves the activity + // view from one snapshot per transaction, so only a count that refreshes it can see this session. + late = await proof.OpenSessionAsync("learnstack_outbox_admin"); + return new NewRealmSnapshot(issuer, 2, true, proof.Subjects); + }); + + try + { + var outcome = await proof.RunAsync(admission, realm, settle: false); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.LiveSessions); + outcome.LiveSessions.Should().Be(1); + outcome.Continuity.Should().NotBeNull("the proof had run: it is the last-moment question that refused"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle("only the intent row").Which.Operation + .Should().Be("identity.authority.rebind_attempt"); + } + finally + { + if (late is not null) await late.DisposeAsync(); + } + } + + [Fact] + public async Task The_Idle_Main_Transaction_Is_Never_Touched_By_A_Client_Keepalive_Whatever_The_Connection_String_Asks() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + // A client keepalive sends a message on the idle connection, and every message the server receives restarts its + // idle-in-transaction clock: the fence that frees a hung tool's lock would never fire. The tool turns it off. + var asked = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { KeepAlive = 1 }.ConnectionString; // leakwatch:ignore:database-connection-string + DateTime? first = null; + DateTime? second = null; + var realm = new FixedRealm(async (issuer, token) => + { + await using var probe = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.RebindConnection, token); + first = await StateChangeOfTheMainSessionAsync(probe); + await Task.Delay(TimeSpan.FromSeconds(3.5), token); + second = await StateChangeOfTheMainSessionAsync(probe); + return new NewRealmSnapshot(issuer, 2, true, proof.Subjects); + }); + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), realm, connection: asked); + + outcome.Result.Should().Be(IdentityRebindResult.Applied); + first.Should().NotBeNull("the main transaction sits idle while the realm is read"); + second.Should().Be(first, "nothing reached the idle transaction in between"); + + static async Task StateChangeOfTheMainSessionAsync(NpgsqlConnection probe) + { + await using var command = new NpgsqlCommand( + """ + SELECT state_change FROM pg_catalog.pg_stat_activity + WHERE usename = current_user AND application_name = 'learnstack-identity-rebind' + AND state = 'idle in transaction' AND pid <> pg_catalog.pg_backend_pid() + """, probe); + return (DateTime?)await command.ExecuteScalarAsync() is { } at ? at : null; + } + } + + [Fact] + public async Task A_Rebind_That_Is_Already_Running_Makes_The_Second_One_Wait_Then_Refuse_Without_A_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + await using var held = await proof.HoldRebindLockAsync(); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), lockWait: TimeSpan.FromSeconds(1)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.RebindInProgress); + (await proof.AuditRowsAsync(admission)).Should().BeEmpty("the lock is the first statement, so nothing was decided yet"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task A_Stored_Authority_That_Is_Not_The_Configured_One_Is_Refused_After_The_Intent_Row() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var other = new IdentityAuthorityRegistration(IdentityAuthorityId.From(Guid.CreateVersion7()), NewIssuer); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), target: other); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuthorityMismatch); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuthorityAsync()).Should().Be(proof.Authority, "a changed AuthorityId would re-key every person"); + } + + [Fact] + public async Task The_Same_Issuer_Under_Another_Authority_Is_Not_Already_Applied_It_Is_A_Misconfiguration() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var other = new IdentityAuthorityRegistration(IdentityAuthorityId.From(Guid.CreateVersion7()), proof.OldIssuer); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), target: other); + + outcome.Result.Should().Be(IdentityRebindResult.Refused, "equal issuers do not make the run a no-op when the authority differs"); + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuthorityMismatch); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle(); + } + + [Theory] + [InlineData("learnstack_app")] + [InlineData("learnstack_outbox_admin")] + [InlineData("learnstack_identity_ingress")] + [InlineData("learnstack_platform")] + public async Task A_Live_Session_Of_A_Runtime_Role_Freezes_The_Rebind_And_Its_Disappearance_Lifts_It(string role) + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var realm = FixedRealm.Reporting(proof.Subjects); + + int? seen; + await using (var session = await proof.OpenSessionAsync(role)) + { + var refused = await proof.RunAsync(admission, realm, settle: false); + refused.Refusal.Should().Be(IdentityRebindRefusal.LiveSessions); + seen = refused.LiveSessions; + } + + seen.Should().Be(1, "the count is reported, never a session's identity"); + realm.Reads.Should().Be(0, "the freeze is checked before the new realm is read"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + + var retry = await proof.RunAsync(RebindProofSupport.Admit(), realm); + retry.Result.Should().Be(IdentityRebindResult.Applied, "a retry repeats the whole proof against the quiet database"); + } + + [Fact] + public async Task The_New_Realm_Must_Be_Readable_Name_Its_Own_Issuer_Publish_Keys_And_Be_Complete() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + + var cases = new (string Why, FixedRealm Realm, IdentityRebindRefusal Expected)[] + { + ("unreadable", FixedRealm.Failing(), IdentityRebindRefusal.NewRealmUnavailable), + ("another discovery issuer", FixedRealm.Reporting(proof.Subjects, "https://elsewhere.example.test/realms/learnstack"), IdentityRebindRefusal.NewRealmIssuerMismatch), + ("no signing keys", FixedRealm.Reporting(proof.Subjects, keys: 0), IdentityRebindRefusal.NewRealmIncomplete), + ("a partial enumeration", FixedRealm.Reporting(proof.Subjects, complete: false), IdentityRebindRefusal.NewRealmIncomplete), + }; + foreach (var (why, realm, expected) in cases) + { + var admission = RebindProofSupport.Admit(); + var outcome = await proof.RunAsync(admission, realm); + + outcome.Refusal.Should().Be(expected, why); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer, why); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle(why).Which.Operation.Should().Be("identity.authority.rebind_attempt"); + } + } + + [Fact] + public async Task An_Active_User_The_New_Realm_Does_Not_Report_Refuses_And_Names_Only_Counts() + { + await using var proof = await Proof.CreateAsync(parent, active: 3); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects.Take(2))); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.ContinuityBroken); + outcome.Continuity!.MissingActive.Should().Be(1); + outcome.ToString().Should().NotContain(proof.Subjects[2], "a refusal reports counts and never identifiers"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle("only the intent row: no change, no result"); + } + + [Fact] + public async Task A_Subject_That_Differs_In_Case_Or_By_Whitespace_Is_Not_The_Same_Subject() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var changed = new[] { proof.Subjects[0].ToUpperInvariant(), " " + proof.Subjects[0] }; + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(changed)); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.ContinuityBroken, "the exact opaque sub is the identity"); + } + + [Fact] + public async Task A_Closed_Persons_Key_Reappearing_Refuses_And_An_Absent_One_Does_Not() + { + await using var proof = await Proof.CreateAsync(parent, active: 2); + await proof.CloseAsync(proof.Users[1], closed: true); + + var reappears = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + reappears.Refusal.Should().Be(IdentityRebindRefusal.ContinuityBroken, "a closed person must not reappear"); + reappears.Continuity.Should().BeEquivalentTo(new IdentityRebindContinuityResult(1, 0, 1, 2, 0, 0, 1, 0)); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + + var absent = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects.Take(1))); + absent.Result.Should().Be(IdentityRebindResult.Applied, "the tombstone's subject is simply not in the new realm"); + absent.Continuity!.StoredClosed.Should().Be(1); + } + + [Fact] + public async Task A_Closing_User_Retaining_Its_Subject_Is_Judged_By_Neither_Rule() + { + await using var proof = await Proof.CreateAsync(parent, active: 2); + await proof.CloseAsync(proof.Users[1], closed: false); + + var outcome = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects.Take(1))); + + outcome.Result.Should().Be(IdentityRebindResult.Applied); + outcome.Continuity!.StoredClosing.Should().Be(1); + } + + [Fact] + public async Task A_Forced_Audit_Failure_Rolls_The_Issuer_Change_Back() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), configure: store => store.FailResult = true); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuditFailed); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer, "the issuer change and its audit row commit together or not at all"); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); + } + + [Fact] + public async Task A_Run_Cancelled_During_The_Realm_Read_Leaves_The_Intent_Row_And_No_Change() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + using var cancellation = new CancellationTokenSource(); + var realm = new FixedRealm(async (_, token) => + { + await cancellation.CancelAsync(); + token.ThrowIfCancellationRequested(); + return null!; + }); + + var outcome = await proof.RunAsync(admission, realm, cancellation: cancellation.Token); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.Cancelled); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle().Which.Operation.Should().Be("identity.authority.rebind_attempt"); + } + + [Fact] + public async Task An_Intent_Row_That_Cannot_Be_Written_Refuses_The_Run_Before_Any_Proof() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + var realm = FixedRealm.Reporting(proof.Subjects); + + var outcome = await proof.RunAsync(admission, realm, configure: store => store.FailIntent = true); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.AuditFailed); + realm.Reads.Should().Be(0, "an attempt that cannot be recorded is not made"); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + (await proof.AuditRowsAsync(admission)).Should().BeEmpty(); + } + + [Fact] + public async Task A_Database_That_Cannot_Be_Reached_And_A_Malformed_Connection_String_Are_Refused_Without_A_Throw() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var closedPort = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Host = "127.0.0.1", Port = 1, Timeout = 2 }.ConnectionString; + + var wrongPassword = new NpgsqlConnectionStringBuilder(proof.RebindConnection) { Password = "not-the-password" }.ConnectionString; // leakwatch:ignore:database-connection-string + + var unreachable = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: closedPort); + unreachable.Refusal.Should().Be(IdentityRebindRefusal.DatabaseUnavailable); + unreachable.Detail.Should().Be(IdentityRebindDetail.DatabaseConnection); + + var refused = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: wrongPassword); + refused.Refusal.Should().Be(IdentityRebindRefusal.DatabaseUnavailable); + refused.Detail.Should().Be(IdentityRebindDetail.DatabaseAuthentication, "a credential the server refuses is not an outage"); + + var malformed = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects), connection: "Host=;;=Username"); + malformed.Refusal.Should().Be(IdentityRebindRefusal.RoleInvalid); + malformed.Detail.Should().Be(IdentityRebindDetail.RoleSession); + } + + [Fact] + public async Task A_Commit_Reconciliation_Waits_For_The_Original_Transaction_And_Never_Reports_A_False_Unchanged() + { + // The session dies at COMMIT and something still holds the rebind lock when the run asks what became of it: the + // answer is not knowable yet, so the run says so instead of reading the old issuer and claiming "unchanged". + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + IAsyncDisposable? held = null; + try + { + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), lockWait: TimeSpan.FromSeconds(1), + configure: store => store.AfterResult = async connection => + { + await parent.Postgres.ExecuteAsSuperuserAsync( + $"SELECT pg_terminate_backend({((NpgsqlConnection)connection).ProcessID})"); + held = await proof.HoldRebindLockAsync(); + }); + + outcome.Result.Should().Be(IdentityRebindResult.Unknown); + } + finally + { + if (held is not null) await held.DisposeAsync(); + } + + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer); + } + + [Fact] + public async Task A_Session_Killed_Before_Commit_Is_Reconciled_As_Not_Applied() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), configure: store => + store.AfterResult = async connection => + await parent.Postgres.ExecuteAsSuperuserAsync( + $"SELECT pg_terminate_backend({((NpgsqlConnection)connection).ProcessID})")); + + outcome.Refusal.Should().Be(IdentityRebindRefusal.CommitFailed); + outcome.Result.Should().Be(IdentityRebindResult.Refused); + (await proof.IssuerAsync()).Should().Be(proof.OldIssuer, "the transaction died with its connection"); + (await proof.AuditRowsAsync(admission)).Should().ContainSingle("no result row either").Which.Operation + .Should().Be("identity.authority.rebind_attempt"); + + var retry = await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + retry.Result.Should().Be(IdentityRebindResult.Applied); + } + + [Fact] + public async Task A_Commit_Whose_Acknowledgement_Is_Lost_Is_Reconciled_By_Reading_The_Issuer() + { + await using var proof = await Proof.CreateAsync(parent, active: 1); + await using var proxy = new CommitAckDroppingProxy(proof.RebindConnection); + var admission = RebindProofSupport.Admit(); + + var outcome = await proof.RunAsync(admission, FixedRealm.Reporting(proof.Subjects), connection: proxy.Through(proof.RebindConnection)); + + proxy.Dropped.Should().BeTrue("the server received the COMMIT and its answer never arrived"); + outcome.Result.Should().Be(IdentityRebindResult.Applied, "the issuer read back is the target, so the commit applied"); + (await proof.IssuerAsync()).Should().Be(NewIssuer); + (await proof.AuditRowsAsync(admission)).Select(row => row.Operation).Should().Equal( + "identity.authority.rebind_attempt", "identity.authority.rebind"); + } + + [Fact] + public async Task Runs_Are_Counted_By_Outcome_And_The_Continuity_Counts_By_Class() + { + var outcomes = new System.Collections.Concurrent.ConcurrentBag(); + var classes = new System.Collections.Concurrent.ConcurrentDictionary(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == IdentityRebindMetrics.MeterName) l.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((instrument, value, tags, _) => + { + foreach (var tag in tags) + { + if (instrument.Name == IdentityRebindMetrics.RunCounterName && tag.Key == "outcome") outcomes.Add((string)tag.Value!); + if (instrument.Name == IdentityRebindMetrics.ContinuityCounterName && tag.Key == "class") + classes.AddOrUpdate((string)tag.Value!, value, (_, current) => current + value); + } + }); + listener.Start(); + await using var proof = await Proof.CreateAsync(parent, active: 2); + + await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects.Take(1))); + await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + await proof.RunAsync(RebindProofSupport.Admit(), FixedRealm.Reporting(proof.Subjects)); + + outcomes.Should().Contain(["refused_continuity_broken", "applied", "already_applied"]); + classes.Should().ContainKey("missing_active").WhoseValue.Should().BeGreaterThanOrEqualTo(1); + classes.Should().ContainKey("active"); + } + + private sealed record AuditRow( + Guid Tenant, string Operation, string Outcome, Guid? Actor, string? Reason, string Entity, + JsonElement Operator, JsonElement Before, JsonElement After, JsonElement Continuity, string Raw); + + private sealed record StoredUser(Guid Id, string KeyHex, string? Subject, string Status); + + private sealed class Proof : IAsyncDisposable + { + private readonly IdentityPublicReadFixture _database; + private readonly PublicReadFixture _parent; + + private Proof(PublicReadFixture parent, IdentityPublicReadFixture database, UserId[] users, string[] subjects) + { + _parent = parent; + _database = database; + Users = users; + Subjects = subjects; + } + + internal string[] Subjects { get; } + + internal UserId[] Users { get; } + + internal Guid Authority => _database.Registration.AuthorityId.Value; + + internal string OldIssuer => _database.Registration.Issuer; + + internal string RebindConnection => _database.IdentityRebindConnectionString; + + internal string OwnerConnection => _database.MigrationConnectionString; + + internal string Database => RebindProofSupport.DatabaseOf(RebindConnection); + + internal static async Task CreateAsync(PublicReadFixture parent, int active) + { + var users = Enumerable.Range(0, active).Select(_ => UserId.From(Guid.CreateVersion7())).ToArray(); + var subjects = users.Select(user => "rebind-proof-" + user.Value.ToString("N")).ToArray(); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, "https://old.example.test/realms/learnstack", + users.Zip(subjects).ToDictionary(pair => pair.First, pair => pair.Second)); + return new Proof(parent, database, users, subjects); + } + + internal async Task RunAsync( + PlatformAdmission admission, + INewRealmContinuitySource realm, + string? connection = null, + IdentityAuthorityRegistration? target = null, + TimeSpan? lockWait = null, + Action? configure = null, + bool settle = true, + CancellationToken cancellation = default) + { + // A session this test's own reads opened is gone before the next run asks the freeze question, unless the + // test keeps one open on purpose and says so. + if (settle) await SettleAsync(); + await using var scope = RebindProofSupport.Store(); + var store = new FaultingAuditStore(scope.ServiceProvider.GetRequiredService()); + configure?.Invoke(store); + return await new IdentityIssuerRebind(store, new SystemClock()).RunAsync( + connection ?? RebindConnection, + target ?? new IdentityAuthorityRegistration(_database.Registration.AuthorityId, NewIssuer), + admission, realm, lockWait, cancellation); + } + + internal async Task IssuerAsync() => await ReadAsync("SELECT issuer FROM public.identity_authority"); + + internal async Task AuthorityAsync() => await ReadAsync("SELECT authority_id FROM public.identity_authority"); + + // Read as the owner: the owner is not a runtime role, so a read between two runs is never a session the freeze counts. + private async Task ReadAsync(string sql) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + await using var command = new NpgsqlCommand(sql, connection); + return (T)(await command.ExecuteScalarAsync())!; + } + + /// Waits until no session of a runtime role is left on the database, as a stopped fleet leaves none. + internal async Task SettleAsync() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + var deadline = System.Diagnostics.Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(15)) + { + var remaining = await IdentityMembershipFixture.ScalarAsync(owner, null, + """ + SELECT count(*) FROM pg_catalog.pg_stat_activity + WHERE datname = current_database() AND pid <> pg_catalog.pg_backend_pid() + AND usename IN ('learnstack_app', 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'learnstack_platform') + """); + if (remaining == 0) return; + await Task.Delay(50); + } + } + + internal async Task> UsersAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + await using var command = new NpgsqlCommand( + "SELECT id, encode(subject_key, 'hex'), provider_subject, status FROM public.users ORDER BY id", connection); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new StoredUser(reader.GetGuid(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2), reader.GetString(3))); + } + + return rows; + } + + internal async Task> AuditRowsAsync(PlatformAdmission admission) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + """ + SELECT tenant_id, operation, outcome, actor_user_id, reason, entity_id, metadata::text, + COALESCE(before_state::text, 'null'), COALESCE(after_state::text, 'null') + FROM public.audit_log WHERE correlation_id = @correlation ORDER BY timestamp, operation + """, connection); + command.Parameters.AddWithValue("correlation", admission.Operator.CorrelationId!); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + var metadata = JsonDocument.Parse(reader.GetString(6)).RootElement.Clone(); + rows.Add(new AuditRow(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), + reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? null : reader.GetString(4), + reader.GetString(5), metadata.GetProperty("operator"), + JsonDocument.Parse(reader.GetString(7)).RootElement.Clone(), + JsonDocument.Parse(reader.GetString(8)).RootElement.Clone(), + metadata.TryGetProperty("continuity", out var continuity) ? continuity : default, + reader.GetString(6) + reader.GetString(7) + reader.GetString(8))); + } + + return rows; + } + + /// A competing rebind: the exclusive lock held by a rebind-role transaction. + internal async Task HoldRebindLockAsync() + { + var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(RebindConnection); + var transaction = await connection.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(connection, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForAuthorityRebind())); + return new Held(connection, transaction); + } + + internal async Task OpenSessionAsync(string role) + { + var template = role switch + { + "learnstack_app" => _database.AppConnectionString, + "learnstack_outbox_admin" => _database.OutboxConnectionString, + "learnstack_platform" => _database.PlatformConnectionString, + _ => RebindProofSupport.In(IngressConnection, Database), + }; + // Unpooled: a disposed pooled connection stays a live session of its role, which is what the freeze sees. + return new Session(await PostgresFixture.OpenAsync( + new NpgsqlConnectionStringBuilder(template) { Pooling = false }.ConnectionString)); + } + + private string IngressConnection => _parent.Postgres.IdentityIngressConnectionString; + + /// The fixture's one corruption: a user closed (or closing) the way closure will, then the controls restored. + internal async Task CloseAsync(UserId user, bool closed) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(OwnerConnection); + var check = await IdentityMembershipFixture.ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + await using var transaction = await owner.BeginTransactionAsync(); + var status = closed ? "Closed" : "Closing"; + var subject = closed ? ", provider_subject=NULL" : string.Empty; + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{user.Value:D}'::uuid AND status='{status}' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='{status}'{subject} WHERE id='{user.Value:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + await transaction.CommitAsync(); + } + + public ValueTask DisposeAsync() => _database.DisposeAsync(); + + private sealed class Held(NpgsqlConnection connection, NpgsqlTransaction transaction) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + await transaction.RollbackAsync(); + await transaction.DisposeAsync(); + await connection.DisposeAsync(); + } + } + + private sealed class Session(DbConnection connection) : IAsyncDisposable + { + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs new file mode 100644 index 000000000..235282f3b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorityRebindToolTests.cs @@ -0,0 +1,388 @@ +using System.Diagnostics; +using System.Reflection; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The offline tool as an operator runs it (ADR-0104 § 3): a child process, every value from its environment and one +/// line of standard input, a real operator issuer, a real database and a loopback new realm. +/// +/// +/// What an operator sees is one fixed line of classes and counts, so every case also asserts that no credential, +/// token, issuer, authority or subject reached the output, and that a refusal left the issuer where it was. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityAuthorityRebindToolTests(PublicReadFixture parent) +{ + private const string OperatorSubject = "operator-sub-9"; + private const string Grant = "platform.identity_authority.admin"; + + [Fact] + public async Task The_Tool_Rebinds_With_A_Token_On_Standard_Input_And_Prints_One_Line_Without_Identifiers() + { + await using var run = await Run.StartAsync(parent); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: true); + + result.Code.Should().Be(0, result.Text); + result.Out.Should().StartWith("rebind: outcome=applied correlation=rebind-") + .And.Contain("active=2").And.Contain("unbootstrapped=0"); + result.Out.Trim().Split('\n').Should().ContainSingle("one fixed line"); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.NewIssuer); + + var correlation = result.Out.Split("correlation=")[1].Split(' ')[0].Trim(); + (await run.OperationsAsync(correlation)).Should().Equal( + "identity.authority.rebind_attempt", "identity.authority.rebind"); + } + + [Fact] + public async Task The_Tool_Rebinds_With_A_Token_In_The_Environment_And_A_Repeat_Is_Already_Applied() + { + await using var run = await Run.StartAsync(parent); + + (await run.ExecuteAsync(token: run.Token(), tokenOnInput: false)).Code.Should().Be(0); + var repeat = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + repeat.Code.Should().Be(0); + repeat.Out.Should().StartWith("rebind: outcome=already_applied"); + } + + [Theory] + [InlineData("no-token", "refused_input detail=operator_token")] + [InlineData("argument", "refused_input detail=arguments")] + [InlineData("no-realm-credential", "refused_input detail=realm_client")] + [InlineData("no-mode", "refused_input detail=deployment_mode")] + [InlineData("wrong-audience", "refused_operator_token_token_audience")] + [InlineData("wrong-issuer", "refused_operator_token_token_issuer")] + [InlineData("expired", "refused_operator_token_token_expired")] + [InlineData("stale-authentication", "refused_operator_token_profile_auth_age")] + [InlineData("single-factor", "refused_operator_token_profile_acr")] + [InlineData("other-client", "refused_operator_token_profile_azp")] + [InlineData("no-grant", "refused_operator_missing_permission")] + [InlineData("another-grant", "refused_operator_missing_permission")] + [InlineData("no-operator-issuer", "refused_operator_issuer_not_configured")] + public async Task A_Refusal_Before_The_Database_Leaves_The_Issuer_And_Writes_No_Row(string scenario, string expected) + { + await using var run = await Run.StartAsync(parent); + + var result = await run.ExecuteAsync(scenario); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=" + expected); + result.Out.Trim().Split('\n').Should().ContainSingle("one fixed line, on standard output and nowhere else"); + result.Error.Should().BeEmpty(); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + (await run.RebindRowsAsync()).Should().Be(0, "a refusal at the gate writes no durable row: the line and the counter are its record"); + } + + [Fact] + public async Task A_Database_Role_That_Is_Not_The_Rebind_Role_Is_Refused() + { + await using var run = await Run.StartAsync(parent); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false, connection: run.AppConnection); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_input detail=connection_string", "the string is not the rebind role's"); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + } + + [Fact] + public async Task A_New_Realm_Missing_An_Active_User_Refuses_With_Counts_And_Keeps_The_Intent_Row() + { + await using var run = await Run.StartAsync(parent, reportedUsers: 1); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_continuity_broken").And.Contain("missing_active=1"); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + var correlation = result.Out.Split("correlation=")[1].Split(' ')[0].Trim(); + (await run.OperationsAsync(correlation)).Should().Equal("identity.authority.rebind_attempt"); + } + + [Fact] + public async Task A_Rebind_Role_Session_Beside_A_Live_Application_Session_Is_Frozen_With_A_Count() + { + await using var run = await Run.StartAsync(parent); + await using var application = (NpgsqlConnection)await PostgresFixture.OpenAsync(run.AppConnection); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_live_sessions").And.Contain("sessions=1"); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + } + + [Fact] + public async Task A_New_Realm_That_Refuses_The_Client_Names_The_Step_And_Never_The_Address() + { + await using var run = await Run.StartAsync(parent); + run.Realm.Fail("token-denied"); + + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false); + + result.Code.Should().Be(2); + result.Out.Should().StartWith("rebind: outcome=refused_new_realm_unavailable correlation=rebind-") + .And.EndWith(" detail=realm_token" + Environment.NewLine.TrimEnd('\r'), "the step is named, nothing else"); + result.Error.Should().BeEmpty(); + run.AssertNoValueLeaked(result); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + } + + [Theory] + [InlineData("TERM")] + [InlineData("HUP")] + public async Task A_Signal_During_The_Realm_Read_Rolls_Back_Reports_Cancelled_And_Keeps_The_Intent_Row(string signal) + { + await using var run = await Run.StartAsync(parent); + run.Realm.Fail("discovery-hang"); + + // The tool asks the realm only after its handlers are in place, its intent row is written and the sessions of + // every runtime role are counted, so the realm's hung request arriving is the instant the signal is meant for: + // no sleep guesses how long the runtime takes to start. The intent row is not that instant. It is written + // before the count, and a test that polls for it as the platform role holds a session of a runtime role that the + // count can see, which refuses the run as live sessions instead of cancelling it. + // A process started under `nohup` inherits an ignored hang-up and keeps ignoring it, as it should, so the case + // starts the tool with the default disposition restored: a tool the operator runs in tmux has it. + var result = await run.ExecuteAsync(token: run.Token(), tokenOnInput: false, resetHangUp: signal == "HUP", whileRunning: async child => + { + await run.Realm.DiscoveryHung.WaitAsync(TimeSpan.FromSeconds(60)); + using var kill = Process.Start("kill", ["-" + signal, child.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)])!; + await kill.WaitForExitAsync(); + }); + + result.Code.Should().Be(2, result.Text); + result.Out.Should().StartWith("rebind: outcome=refused_cancelled correlation=rebind-"); + result.Out.Trim().Split('\n').Should().ContainSingle(); + result.Error.Should().BeEmpty(); + (await run.IssuerAsync()).Should().Be(run.OldIssuer); + var correlation = result.Out.Split("correlation=")[1].Split(' ')[0].Trim(); + (await run.OperationsAsync(correlation)).Should().Equal("identity.authority.rebind_attempt"); + } + + private sealed record Result(int Code, string Out, string Error) + { + internal string Text => Out + Error; + } + + private sealed class Run : IAsyncDisposable + { + private readonly IdentityPublicReadFixture _database; + private readonly TenantAuthenticationIssuer _operator; + private readonly FakeKeycloakRealm _realm; + private readonly string[] _subjects; + + private Run(IdentityPublicReadFixture database, TenantAuthenticationIssuer @operator, FakeKeycloakRealm realm, string[] subjects) + { + _database = database; + _operator = @operator; + _realm = realm; + _subjects = subjects; + } + + internal string OldIssuer => _database.Registration.Issuer; + + internal string NewIssuer => _realm.Issuer; + + internal string AppConnection => _database.AppConnectionString; + + internal FakeKeycloakRealm Realm => _realm; + + internal static async Task StartAsync(PublicReadFixture parent, int reportedUsers = 2) + { + var users = new[] { UserId.From(Guid.CreateVersion7()), UserId.From(Guid.CreateVersion7()) }; + var subjects = users.Select(user => "tool-proof-" + user.Value.ToString("N")).ToArray(); + var database = await IdentityPublicReadFixture.CreateAsync( + parent, "https://old.example.test/realms/learnstack", users.Zip(subjects).ToDictionary(pair => pair.First, pair => pair.Second)); + var @operator = await TenantAuthenticationIssuer.StartAsync(); + var realm = await FakeKeycloakRealm.StartAsync(subjects.Take(reportedUsers)); + return new Run(database, @operator, realm, subjects); + } + + internal string Token(params (string Name, object? Value)[] replacements) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var claims = new Dictionary(StringComparer.Ordinal) + { + ["iss"] = _operator.Issuer, + ["sub"] = OperatorSubject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + }; + foreach (var (name, value) in replacements) claims[name] = value; + return _operator.Token(JsonSerializer.Serialize(claims)); + } + + internal Task ExecuteAsync(string scenario) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + return scenario switch + { + "no-token" => ExecuteAsync(token: null, tokenOnInput: false), + "argument" => ExecuteAsync(token: Token(), tokenOnInput: false, argument: "--force"), + "no-realm-credential" => ExecuteAsync(token: Token(), tokenOnInput: false, realmCredential: false), + "no-mode" => ExecuteAsync(token: Token(), tokenOnInput: false, mode: null), + "wrong-audience" => ExecuteAsync(token: Token(("aud", "learnstack-api")), tokenOnInput: false), + "wrong-issuer" => ExecuteAsync(token: Token(("iss", "https://elsewhere.example.test/realms/x")), tokenOnInput: false), + "expired" => ExecuteAsync(token: Token(("exp", now - 3600), ("iat", now - 3700), ("auth_time", now - 3700)), tokenOnInput: false), + "stale-authentication" => ExecuteAsync(token: Token(("auth_time", now - 7200)), tokenOnInput: false), + "single-factor" => ExecuteAsync(token: Token(("acr", "pwd")), tokenOnInput: false), + "other-client" => ExecuteAsync(token: Token(("azp", "learnstack-web")), tokenOnInput: false), + "no-grant" => ExecuteAsync(token: Token(), tokenOnInput: false, grant: null), + "another-grant" => ExecuteAsync(token: Token(), tokenOnInput: false, grant: "platform.killswitch.write"), + "no-operator-issuer" => ExecuteAsync(token: Token(), tokenOnInput: false, operatorIssuer: false), + _ => throw new ArgumentOutOfRangeException(nameof(scenario)), + }; + } + + internal async Task ExecuteAsync( + string? token, bool tokenOnInput, string? argument = null, bool realmCredential = true, string? mode = "Development", + string? grant = Grant, bool operatorIssuer = true, string? connection = null, + Func? whileRunning = null, bool resetHangUp = false) + { + var start = new ProcessStartInfo(resetHangUp ? "perl" : "dotnet") + { + WorkingDirectory = AppContext.BaseDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + UseShellExecute = false, + }; + if (resetHangUp) + { + start.ArgumentList.Add("-e"); + start.ArgumentList.Add("$SIG{HUP} = 'DEFAULT'; exec @ARGV"); + start.ArgumentList.Add("dotnet"); + } + + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.deps.json")); + start.ArgumentList.Add(Assembly.Load("LearnStack.Tools.IdentityAuthorityRebind").Location); + if (argument is not null) start.ArgumentList.Add(argument); + start.Environment.Clear(); + foreach (var key in new[] { "PATH", "SystemRoot", "DOTNET_ROOT", "HOME" }) + if (Environment.GetEnvironmentVariable(key) is { } value) start.Environment[key] = value; + start.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + start.Environment["ConnectionStrings__IdentityRebind"] = connection ?? _database.IdentityRebindConnectionString; + start.Environment["Identity__AuthorityId"] = _database.Registration.AuthorityId.Value.ToString("D"); + start.Environment["Authentication__Tenant__Issuer"] = _realm.Issuer; + if (mode is not null) start.Environment["Deployment__Mode"] = mode; + if (operatorIssuer) + { + start.Environment["PlatformOperator__Issuer"] = _operator.Issuer; + start.Environment["PlatformOperator__AuthorizedParties__0"] = "learnstack-operator"; + start.Environment["PlatformOperator__AcceptedAcr__0"] = "mfa"; + if (grant is not null) + { + start.Environment["PlatformOperator__Grants__0__Subject"] = OperatorSubject; + start.Environment["PlatformOperator__Grants__0__Permissions__0"] = grant; + } + } + + if (realmCredential) + { + start.Environment["LEARNSTACK_REBIND_REALM_CLIENT_ID"] = FakeKeycloakRealm.ClientId; + start.Environment["LEARNSTACK_REBIND_REALM_CLIENT_SECRET"] = FakeKeycloakRealm.ClientSecret; + } + + start.Environment["LEARNSTACK_REBIND_TICKET"] = "CHG-104"; + if (token is not null && !tokenOnInput) start.Environment["LEARNSTACK_OPERATOR_TOKEN"] = token; + _token = token; + + using var child = new Process { StartInfo = start }; + child.Start().Should().BeTrue(); + var output = child.StandardOutput.ReadToEndAsync(); + var errors = child.StandardError.ReadToEndAsync(); + if (token is not null && tokenOnInput) await child.StandardInput.WriteLineAsync(token); + child.StandardInput.Close(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(90)); + try + { + if (whileRunning is not null) await whileRunning(child); + await child.WaitForExitAsync(deadline.Token); + } + finally + { + if (!child.HasExited) + { + child.Kill(entireProcessTree: true); + await child.WaitForExitAsync(CancellationToken.None); + } + } + + return new Result(child.ExitCode, await output, await errors); + } + + private string? _token; + + internal void AssertNoValueLeaked(Result result) + { + var forbidden = new List + { + FakeKeycloakRealm.ClientSecret, _database.IdentityRebindConnectionString, _database.AppConnectionString, + OldIssuer, NewIssuer, _operator.Issuer, _database.Registration.AuthorityId.Value.ToString("D"), OperatorSubject, + }; + forbidden.AddRange(_subjects); + if (_token is not null) forbidden.Add(_token); + foreach (var value in forbidden) + { + result.Text.Should().NotContain(value); + } + + result.Text.Length.Should().BeLessThan(1024); + } + + internal async Task IssuerAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var command = new NpgsqlCommand("SELECT issuer FROM public.identity_authority", connection); + return (string)(await command.ExecuteScalarAsync())!; + } + + internal async Task RebindRowsAsync() + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT count(*) FROM public.audit_log WHERE operation LIKE 'identity.authority.rebind%'", connection); + return (long)(await command.ExecuteScalarAsync())!; + } + + internal async Task> OperationsAsync(string correlation) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT operation FROM public.audit_log WHERE correlation_id = @c ORDER BY timestamp", connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) rows.Add(reader.GetString(0)); + return rows; + } + + public async ValueTask DisposeAsync() + { + await _realm.DisposeAsync(); + await _operator.DisposeAsync(); + await _database.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs index 7daa7e189..6d678129c 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs @@ -159,8 +159,8 @@ await FluentActions.Awaiting(() => firstHelper.AcquireAsync(new([], Tenant, Iden [Fact] public async Task Actual_global_subject_acquisition_emits_a_positive_finite_measurement_and_releases_on_rollback() { - var subject = new GlobalIdentitySubject(IdentityAuthorityId.From(Guid.Parse("01930000-0000-7000-8000-00000000f001")), - "https://lock-metrics.invalid/realms/learnstack", "subject-canary-must-not-be-a-metric-tag"); + var subject = new GlobalIdentitySubject(IdentityMembershipFixture.Authority.AuthorityId, + IdentityMembershipFixture.Authority.Issuer, "subject-canary-must-not-be-a-metric-tag"); await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); await using var unit = Unit(source); var descriptor = SubjectSignalMint.Create(subject); @@ -269,10 +269,10 @@ private void AssertFinite() signal.Instrument.Should().BeOneOf("learnstack_identity_lock_wait_seconds", "learnstack_identity_lock_refusals_total"); signal.Tags.Keys.Should().BeEquivalentTo(signal.Instrument == "learnstack_identity_lock_wait_seconds" ? WaitTagNames : RefusalTagNames); - signal.Tags["lock_kind"].Should().BeOneOf("subject", "user", "tenant"); + signal.Tags["lock_kind"].Should().BeOneOf("subject", "user", "tenant", "authority"); if (signal.Instrument == "learnstack_identity_lock_wait_seconds") signal.Tags["outcome"].Should().BeOneOf("acquired", "timeout", "cancelled", "fault"); - else signal.Tags["reason"].Should().BeOneOf("timeout", "cancelled", "fault"); + else signal.Tags["reason"].Should().BeOneOf("timeout", "cancelled", "fault", "mismatch"); } } private void Record(Instrument instrument, double value, ReadOnlySpan> tags) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs index 9ba48be88..eec329465 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs @@ -132,6 +132,23 @@ internal async Task AdoptAsync(UserId actor, string opaqueSubject) result.Actor.Should().Be(actor); } + /// + /// One process of the given registration: it qualifies, runs while it is + /// up (a rebind, for instance), and then it tries one adoption. The result is returned, never asserted. + /// + internal async Task TryAdoptAsync(IdentityAuthorityRegistration registration, UserId actor, + string opaqueSubject, Func? afterQualification = null) + { + var subject = new GlobalIdentitySubject(registration.AuthorityId, registration.Issuer, opaqueSubject); + await using var source = ApplicationDataSource.Build(AppConnectionString); + await using var provider = SeedComposition.Build(source, null, NullLoggerFactory.Instance, + identityAuthority: registration, seedAdmission: new ExactBindingAdmission(subject, actor)); + await provider.GetRequiredService().QualifyAsync(); + if (afterQualification is not null) await afterQualification(); + await using var scope = provider.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().AdoptAsync(subject, actor); + } + protected override void ConfigureTestHost(IWebHostBuilder builder) { base.ConfigureTestHost(builder); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs new file mode 100644 index 000000000..fedf92e78 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityRebindAuditStoreTests.cs @@ -0,0 +1,251 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The two witness-bound audit methods of the controlled issuer rebind (ADR-0104 § 8) against real PostgreSQL, +/// written on the rebind role's own connection exactly as the offline tool writes them. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class IdentityRebindAuditStoreTests(PublicReadFixture parent) +{ + private static readonly PlatformOperation Rebind = PlatformOperations.IdentityAuthorityRebind; + + [Fact] + public async Task The_Intent_And_The_Result_Rows_Are_Written_Bound_To_The_Admission_And_Carry_The_Ticket() + { + await using var scope = RebindProofSupport.Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(ticket: "CHG-104"); + var authority = Guid.CreateVersion7(); + var intent = Intent(admission, authority); + var result = Result(admission, authority); + + await using (var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString)) + { + await using var transaction = await connection.BeginTransactionAsync(); + await audit.WriteIdentityRebindIntentAsync(intent, admission, connection, transaction); + await transaction.CommitAsync(); + } + + await using (var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString)) + { + await using var transaction = await connection.BeginTransactionAsync(); + await audit.WriteIdentityRebindResultAsync(result, admission, connection, transaction); + await transaction.CommitAsync(); + } + + var rows = await ReadAsync(admission.Operator.CorrelationId!); + rows.Select(row => (row.Operation, row.Outcome)).Should().BeEquivalentTo( + [("identity.authority.rebind_attempt", "indeterminate"), ("identity.authority.rebind", "success")]); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null + && row.Reason == "issuer_rebind" && row.Module == "identity" && row.Entity == "IdentityAuthority" + && OperatorNode(row.Metadata).GetProperty("ticket").GetString() == "CHG-104" + && OperatorNode(row.Metadata).GetProperty("subjectDigest").GetString() == admission.Operator.SubjectDigest); + } + + [Fact] + public async Task The_Result_Row_Commits_With_The_Transaction_Or_Not_At_All() + { + await using var scope = RebindProofSupport.Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(); + + await using (var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString)) + { + await using var transaction = await connection.BeginTransactionAsync(); + await audit.WriteIdentityRebindResultAsync(Result(admission, Guid.CreateVersion7()), admission, connection, transaction); + await transaction.RollbackAsync(); + } + + (await ReadAsync(admission.Operator.CorrelationId!)).Should().BeEmpty(); + } + + [Fact] + public async Task A_Row_That_Differs_From_Its_Admission_Or_Its_Declaration_Is_Refused_Before_The_Database() + { + await using var scope = RebindProofSupport.Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(ticket: "CHG-104"); + var authority = Guid.CreateVersion7(); + var good = Result(admission, authority); + var digest = admission.Operator.SubjectDigest; + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.IdentityRebindConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + + var refused = new Dictionary + { + ["a real tenant"] = good with { TenantId = TenantId.From(Guid.CreateVersion7()) }, + ["the nil tenant"] = good with { TenantId = TenantId.From(Guid.Empty) }, + ["an organization"] = good with { OrganizationId = OrganizationId.From(Guid.CreateVersion7()) }, + ["another module"] = good with { ModuleName = "tenancy" }, + ["another operation"] = good with { Operation = "identity.user.create" }, + ["the intent slug for a result"] = good with { Operation = "identity.authority.rebind_attempt" }, + ["a failed outcome"] = good with { Outcome = AuditOutcome.Failed }, + ["the intent outcome for a result"] = good with { Outcome = AuditOutcome.Indeterminate }, + ["a SHOULD class"] = good with { OperationClass = OperationClass.Should }, + ["another operation type"] = good with { OperationType = OperationType.Create }, + ["another entity"] = good with { EntityType = "User" }, + ["another reason"] = good with { Reason = "host_map" }, + ["an actor"] = good with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + ["a mail address"] = good with { ActorEmail = "operator@example.test" }, + ["an address"] = good with { IpAddress = System.Net.IPAddress.Parse("203.0.113.7") }, + ["a user agent"] = good with { UserAgent = "tool" }, + ["another correlation id"] = good with { CorrelationId = "another" }, + ["no metadata"] = good with { Metadata = null }, + ["no operator attribution"] = good with { Metadata = "{}" }, + ["the digest in the wrong place"] = good with + { + Metadata = "{\"note\":\"" + digest + "\",\"operator\":{\"issuer\":\"" + admission.Operator.Issuer + "\"}}", + }, + ["another operator issuer"] = good with { Metadata = Metadata(admission, "https://elsewhere.example.test/realms/x", "CHG-104") }, + ["a ticket the admission never held"] = good with { Metadata = Metadata(admission, admission.Operator.Issuer, "CHG-999") }, + }; + + foreach (var (attribute, draft) in refused) + { + var act = async () => await audit.WriteIdentityRebindResultAsync(draft, admission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + + // Without a ticket the metadata check is silent about the tenant, so the tenant rule must stand on its own. + var untickedAdmission = Admit(); + var unticked = Result(untickedAdmission, authority); + foreach (var (attribute, draft) in new Dictionary + { + ["a real tenant, no ticket"] = unticked with { TenantId = TenantId.From(Guid.CreateVersion7()) }, + ["the nil tenant, no ticket"] = unticked with { TenantId = TenantId.From(Guid.Empty) }, + }) + { + var act = async () => await audit.WriteIdentityRebindResultAsync(draft, untickedAdmission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + + // The intent method refuses the result's slug and outcome in turn. + var intentOfResult = async () => await audit.WriteIdentityRebindIntentAsync(good, admission, connection, transaction); + await intentOfResult.Should().ThrowAsync("the result slug is not the attempt slug"); + + // Another operation's admission binds no rebind row, and the other operations have no attempt slug. + var killswitch = TestPlatformAdmissions.Admission(PlatformOperations.KillswitchToggle, correlationId: admission.Operator.CorrelationId); + var other = async () => await audit.WriteIdentityRebindResultAsync(good, killswitch, connection, transaction); + await other.Should().ThrowAsync("another operation's admission"); + var noAttempt = async () => await audit.WriteIdentityRebindIntentAsync( + Intent(killswitch, authority), killswitch, connection, transaction); + await noAttempt.Should().ThrowAsync("only the rebind operation has an attempt slug"); + } + + [Fact] + public async Task A_Database_Refusal_Is_An_Audit_Write_Failure_So_The_Rebind_Cannot_Commit() + { + await using var scope = RebindProofSupport.Store(); + var audit = scope.ServiceProvider.GetRequiredService(); + var admission = Admit(); + + // The application role announces no tenant and the policy refuses the row. + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + + var act = async () => await audit.WriteIdentityRebindResultAsync( + Result(admission, Guid.CreateVersion7()), admission, connection, transaction); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task The_Identity_Catalogue_Declares_Both_Slugs_Off_Path_As_Must_Security_Events() + { + var catalog = new AuditCatalog([new IdentityAuditCatalogSource()]); + + foreach (var slug in new[] { "identity.authority.rebind_attempt", "identity.authority.rebind" }) + { + catalog.TryGetOffPath(slug, out var declared).Should().BeTrue(slug); + declared.ModuleName.Should().Be("identity"); + declared.OperationClass.Should().Be(OperationClass.Must); + declared.OperationType.Should().Be(OperationType.SecurityEvent); + declared.EntityType!.Name.Should().Be("IdentityAuthority"); + } + + Rebind.AuditSlug.Should().Be("identity.authority.rebind"); + Rebind.AttemptAuditSlug.Should().Be("identity.authority.rebind_attempt"); + Rebind.ReasonSlug.Should().Be("issuer_rebind"); + Rebind.NeedsPlatformRole.Should().BeFalse("the tool uses its own role and never the platform scope"); + Rebind.Permission.Key.Should().Be("platform.identity_authority.admin"); + } + + private static System.Text.Json.JsonElement OperatorNode(string metadata) => + System.Text.Json.JsonDocument.Parse(metadata).RootElement.GetProperty("operator"); + + private static PlatformAdmission Admit(string? ticket = null) => + TestPlatformAdmissions.Admission(Rebind, ticket, correlationId: "00-rebind-" + Guid.NewGuid().ToString("N")); + + private static string Metadata(PlatformAdmission admission, string issuer, string? ticket) => + "{\"operator\":{\"issuer\":\"" + issuer + "\",\"subjectDigest\":\"" + admission.Operator.SubjectDigest + + "\",\"kind\":\"human\"" + (ticket is null ? string.Empty : ",\"ticket\":\"" + ticket + "\"") + "}}"; + + private static AuditEntryDraft Intent(PlatformAdmission admission, Guid authority) => + Draft(admission, authority, admission.Operation.AttemptAuditSlug ?? "identity.authority.rebind_attempt", AuditOutcome.Indeterminate); + + private static AuditEntryDraft Result(PlatformAdmission admission, Guid authority) => + Draft(admission, authority, admission.Operation.AuditSlug, AuditOutcome.Success); + + private static AuditEntryDraft Draft(PlatformAdmission admission, Guid authority, string operation, AuditOutcome outcome) => new() + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "identity", + Operation = operation, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = "IdentityAuthority", + EntityId = authority.ToString("D"), + Outcome = outcome, + ErrorKey = null, + Reason = Rebind.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = "{\"operator\":" + PlatformOperatorAttribution.From(admission).ToOperatorJson(admission.Ticket) + "}", + }; + + private sealed record Row(Guid Tenant, string Operation, string Outcome, Guid? Actor, string? Reason, string Module, string Entity, string Metadata); + + private async Task> ReadAsync(string correlationId) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.Postgres.PlatformConnectionString); + await using var command = new NpgsqlCommand( + """ + SELECT tenant_id, operation, outcome, actor_user_id, reason, module, entity_type, metadata::text + FROM public.audit_log WHERE correlation_id = @correlation ORDER BY timestamp, operation + """, connection); + command.Parameters.AddWithValue("correlation", correlationId); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new Row(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), + reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? null : reader.GetString(4), + reader.GetString(5), reader.GetString(6), reader.GetString(7))); + } + + return rows; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs index 89aac9d36..a2aaf53be 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs @@ -16,15 +16,15 @@ public sealed class InvitationSmtpStorageTests(InvitationSmtpStorageFixture fixt { "fn_identity_admin_admission_state", "fn_identity_audit_creation_guard", "fn_identity_audit_evidence", "fn_identity_creation_attempt_admission", "fn_identity_invitation_entry", "fn_identity_membership_admission_guard", - "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", + "fn_identity_operator_resolve_user", "fn_identity_provider_event_accept", "fn_identity_provider_event_claim", "fn_identity_provider_event_retire", "fn_identity_self_membership_scopes", "fn_identity_user_capacity_guard", "fn_identity_user_creation_audit_guard", "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", }; private static readonly string[] AppExecutableDefinerFunctions = new[] { "fn_identity_admin_admission_state", "fn_identity_audit_evidence", "fn_identity_creation_attempt_admission", - "fn_identity_invitation_entry", "fn_identity_self_membership_scopes", "fn_invitation_smtp_claim_or_read", - "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", + "fn_identity_invitation_entry", "fn_identity_operator_resolve_user", "fn_identity_self_membership_scopes", + "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", "fn_tenancy_own_field_consent_scope", }; [Fact] diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index a63cd991d..891cf7d22 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -103,8 +103,8 @@ public async Task Reversible_chain_prefixes_reverse_to_empty_and_current_heads_r (await CountAsync(connection, AuditFunctionQuery)).Should().Be(2L); (await CountAsync(connection, EducationFunctionQuery)).Should().Be(3L); (await CountAsync(connection, InboxFunctionQuery)).Should().Be(1L); - (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(23L, - "current Identity also installs three provider definers, one target transition guard and the federation connection guard"); + (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(25L, + "current Identity also installs three provider definers, one target transition guard, the federation connection guard, the operator subject resolver and the authority key guard"); await _fixture.AssertCurrentHeadsRefuseReversalAsync(); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); @@ -211,16 +211,24 @@ public async Task AssertCurrentHeadsRefuseReversalAsync() recoveryAnchor.Should().Throw().WithMessage("Provider recovery continuity requires a forward repair."); Action collision = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.classify_retained_provider_collision().DownOperations; collision.Should().Throw().WithMessage("Provider receipt collision classification requires a forward repair."); + Action federation = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_federation_connections().DownOperations; + federation.Should().Throw().WithMessage("Federation connection storage requires a reviewed forward migration."); Action releaseV4 = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.role_registry_release_v4().DownOperations; releaseV4.Should().Throw().WithMessage("Role release adoption requires a reviewed forward migration."); + Action operatorResolver = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_operator_subject_resolver().DownOperations; + operatorResolver.Should().Throw().WithMessage("Operator subject resolution requires a reviewed forward migration."); + Action authorityRebind = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_identity_authority_rebind().DownOperations; + authorityRebind.Should().Throw().WithMessage("The issuer-rebind storage requires a reviewed forward migration."); + Action protectedReceipts = () => _ = new LearnStack.Infrastructure.Persistence.Migrations.add_custom_field_protected_receipts().DownOperations; + protectedReceipts.Should().Throw().WithMessage("Retained custom field receipts require a reviewed forward migration."); foreach (var (context, immediate, historical, head, reason) in new (DbContext, string, string, string, string)[] { (tenancy, "20261029112940_guard_retained_tenancy_defaults", TenancyReversibleHead, "20261109230237_membership_field_consent_evidence", "Retained consent evidence requires a reviewed forward migration."), - (platform, "20261105020229_lock_invitation_envelope_parent", PlatformReversibleHead, - "20261110013140_add_custom_field_protected_receipts", "Retained custom field receipts require a reviewed forward migration."), - (identity, "20261113114919_role_registry_release_v4", IdentityReversibleHead, - "20261113120259_add_federation_connections", "Federation connection storage requires a reviewed forward migration."), + (platform, "20261110013140_add_custom_field_protected_receipts", PlatformReversibleHead, + "20261120120000_grant_platform_delivery_inspection", "The platform role's column grants require a reviewed forward migration."), + (identity, "20261120090000_add_identity_authority_rebind", IdentityReversibleHead, + "20261120160000_grant_platform_federation_projection", "The platform federation projection grant requires a reviewed forward migration."), (customization, CustomizationReversibleHead, CustomizationReversibleHead, "20261109230218_membership_custom_field_definitions", "Retained custom field definitions require a reviewed forward migration."), }) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs new file mode 100644 index 000000000..4c495ecef --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryAuditDecorator.cs @@ -0,0 +1,47 @@ +using System.Data.Common; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Persistence; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// Wraps the real audit store and hands the operator-recovery row to a test before it is written, so a test can +/// substitute a field of the draft or the transaction and watch the real store refuse it. +/// +internal sealed class OperatorRecoveryAuditDecorator( + IAuditStore inner, + Func recovery) : IAuditStore +{ + public Task WriteGlobalIdentityPendingAsync(IUnitOfWork unitOfWork, GlobalIdentityCreationReference creation, + CancellationToken cancellationToken = default) => + inner.WriteGlobalIdentityPendingAsync(unitOfWork, creation, cancellationToken); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + + public Task WritePendingAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => + inner.WritePendingAsync(unitOfWork, cancellationToken); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => + inner.WriteStandaloneAsync(entry, cancellationToken); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => + inner.WriteBestEffortAsync(entry, cancellationToken); + + public Task WritePlatformScopeAsync(AuditEntryDraft entry, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken = default) => + inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => + inner.WriteEventTerminalAsync(entry, transition, connection, transaction, cancellationToken); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => + inner.WriteJobTerminalAsync(entry, transition, connection, transaction, cancellationToken); + + public Task WriteOperatorRecoveryAsync(AuditEntryDraft entry, OperatorRecoveryTransition transition, + DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) => + recovery(entry, transition, connection, transaction, cancellationToken); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs new file mode 100644 index 000000000..ccb0b6baf --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorRecoveryMeterProbe.cs @@ -0,0 +1,51 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using LearnStack.Infrastructure.PlatformOperator; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// Captures the operator recovery counters while it lives. The counters are process-wide, so a test reads the +/// difference its own calls made and filters by operation, and no other test calls the recovery owner. +/// +internal sealed class OperatorRecoveryMeterProbe : IDisposable +{ + private readonly MeterListener _listener = new(); + private readonly ConcurrentBag<(string Counter, string Operation, string? Outcome, long Value)> _measurements = []; + + public OperatorRecoveryMeterProbe() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName + && instrument.Name is PlatformOperatorMetrics.RecoveryCounterName or PlatformOperatorMetrics.ResultCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => + { + string? operation = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "operation") operation = tag.Value?.ToString(); + if (tag.Key == "outcome") outcome = tag.Value?.ToString(); + } + + _measurements.Add((instrument.Name, operation ?? string.Empty, outcome, value)); + }); + _listener.Start(); + } + + /// The recoveries counted for the operation under the outcome label. + public long Recoveries(string operation, string outcome) => _measurements + .Where(m => m.Counter == PlatformOperatorMetrics.RecoveryCounterName && m.Operation == operation && m.Outcome == outcome) + .Sum(m => m.Value); + + /// The MUST result rows counted for the operation. + public long Results(string operation) => _measurements + .Where(m => m.Counter == PlatformOperatorMetrics.ResultCounterName && m.Operation == operation) + .Sum(m => m.Value); + + public void Dispose() => _listener.Dispose(); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs new file mode 100644 index 000000000..79111a242 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OperatorSubjectResolverTests.cs @@ -0,0 +1,177 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The contract of fn_identity_operator_resolve_user against real PostgreSQL as the application role +/// (ADR-0102 § 5, Database Standards § Operator subject resolution). +/// +/// +/// The definer is the one place an operator act reads users, which a tenant announcement blanks for the +/// application role, so each refusal it promises is asserted here rather than left to the handler above it. +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class OperatorSubjectResolverTests(PublicReadFixture parent) +{ + private const string Resolve = "SELECT public.fn_identity_operator_resolve_user(@authority, @key)"; + + [Fact] + public async Task An_Active_User_Is_Found_And_An_Unknown_Subject_Is_Not() + { + await using var proof = await Proof.CreateAsync(parent); + + (await proof.ResolveAsync(proof.Subject)).Should().Be(proof.Person.Value); + (await proof.ResolveAsync("nobody-has-signed-in")).Should().BeNull(); + } + + [Fact] + public async Task A_User_Who_Is_No_Longer_Active_Is_Not_Found() + { + await using var proof = await Proof.CreateAsync(parent); + await proof.CloseUserAsync(); + + (await proof.ResolveAsync(proof.Subject)).Should().BeNull("the Active filter is part of the contract, not a courtesy"); + } + + [Fact] + public async Task The_Definer_Refuses_Every_Caller_And_Argument_It_Does_Not_Admit() + { + await using var proof = await Proof.CreateAsync(parent); + var key = proof.Key(proof.Subject); + + (await proof.RefusalAsync(authority: Guid.NewGuid(), key: key)).Should().Be("23514", "another authority"); + (await proof.RefusalAsync(key: key[..31])).Should().Be("23514", "a key that is not 32 bytes"); + (await proof.RefusalAsync(key: [])).Should().Be("23514", "an empty key"); + (await proof.RefusalAsync(key: key, announceTenant: false)).Should().Be("23514", "no tenant announcement"); + (await proof.RefusalAsync(key: key, readOnly: true)).Should().Be("23514", "a read-only transaction"); + (await proof.RefusalAsync(key: key, asOwner: true)).Should().Be("23514", "a session that is not the application role"); + (await proof.RefusalAsync(key: key, repeatableRead: true)).Should().Be("23514", "a transaction that is not READ COMMITTED"); + (await proof.RefusalAsync(key: key, nullAuthority: true)).Should().Be("23514", "a null authority"); + (await proof.RefusalAsync(nullKey: true)).Should().Be("23514", "a null key"); + (await proof.RefusalAsync(key: key)).Should().BeNull("the control: the same call, admitted"); + } + + private sealed class Proof : IAsyncDisposable + { + private readonly TenantAuthenticationIssuer _issuer; + private readonly IdentityPublicReadFixture _database; + + private Proof(TenantAuthenticationIssuer issuer, IdentityPublicReadFixture database, UserId person, string subject) + { + _issuer = issuer; + _database = database; + Person = person; + Subject = subject; + } + + internal UserId Person { get; } + + internal string Subject { get; } + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var issuer = await TenantAuthenticationIssuer.StartAsync(); + var person = UserId.From(Guid.CreateVersion7()); + var subject = "resolver-person-" + person.Value.ToString("N"); + try + { + var database = await IdentityPublicReadFixture.CreateAsync( + parent, issuer.Issuer, new Dictionary { [person] = subject }); + return new Proof(issuer, database, person, subject); + } + catch + { + await issuer.DisposeAsync(); + throw; + } + } + + internal byte[] Key(string subject) => + IdentitySubjectKey.Compute(_database.Registration.AuthorityId, subject).ToByteArray(); + + /// One call as the application role under a tenant announcement, the way an act makes it. + internal async Task ResolveAsync(string subject) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, Guid.CreateVersion7()); + await using var command = Command(app, transaction, _database.Registration.AuthorityId.Value, Key(subject)); + return await command.ExecuteScalarAsync() is Guid found ? found : null; + } + + /// The SQLSTATE the definer raises for the call, or null when it answers. + internal async Task RefusalAsync( + Guid? authority = null, byte[]? key = null, bool announceTenant = true, bool readOnly = false, bool asOwner = false, + bool repeatableRead = false, bool nullAuthority = false, bool nullKey = false) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync( + asOwner ? _database.MigrationConnectionString : _database.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync( + repeatableRead ? System.Data.IsolationLevel.RepeatableRead : System.Data.IsolationLevel.ReadCommitted); + if (readOnly) + { + await IdentityMembershipFixture.ExecuteAsync(connection, transaction, "SET TRANSACTION READ ONLY"); + } + + if (announceTenant) + { + await IdentityMembershipFixture.ScopeAsync(connection, transaction, Guid.CreateVersion7()); + } + + try + { + await using var command = Command( + connection, transaction, authority ?? _database.Registration.AuthorityId.Value, key ?? Key(Subject)); + if (nullAuthority) command.Parameters["authority"].Value = DBNull.Value; + if (nullKey) command.Parameters["key"].Value = DBNull.Value; + await command.ExecuteScalarAsync(); + return null; + } + catch (PostgresException failure) + { + return failure.SqlState; + } + } + + /// + /// The fixture's one corruption: the user closed, with the immutability trigger and the insert check stepped + /// around exactly as the administration-eligibility cases do, and restored before the definer is called. + /// + internal async Task CloseUserAsync() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.MigrationConnectionString); + var check = await IdentityMembershipFixture.ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + await using var transaction = await owner.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{Person.Value:D}'::uuid AND status='Closing' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='Closing' WHERE id='{Person.Value:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + await transaction.CommitAsync(); + } + + private static NpgsqlCommand Command(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid authority, byte[] key) + { + var command = new NpgsqlCommand(Resolve, connection, transaction); + command.Parameters.AddWithValue("authority", authority); + command.Parameters.AddWithValue("key", key); + return command; + } + + public async ValueTask DisposeAsync() + { + await _database.DisposeAsync(); + await _issuer.DisposeAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs index 79e30fc96..4b84b0587 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs @@ -11,7 +11,10 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Messaging; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Time; +using LearnStack.Modules.Tenancy.Infrastructure.Jobs; +using LearnStack.Tests.Fixtures; using LearnStack.Tools.Seeder; using MediatR; using Microsoft.Extensions.DependencyInjection; @@ -938,16 +941,416 @@ public sealed record DispatchEventV1 : IntegrationEventBase public override string PartitionKey => SubjectId.ToString("D"); } + private const string DeadLetterRetryExhausted = + "attempts = 6, terminal_reason = 'retry_exhausted', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"; + + private static PlatformAdmission ResetAdmission(DateTimeOffset? issuedAt = null, PlatformOperation? operation = null) => + TestPlatformAdmissions.Admission( + operation ?? PlatformOperations.DeliveryReset, null, + correlationId: "00-recovery-" + Guid.NewGuid().ToString("N"), issuedAt: issuedAt ?? Occurred); + + /// A reset under the fence the row shows now, as an operator would present what inspection returned. + private static async Task ResetAsync( + OutboxDispatchStore store, TestDatabase test, Guid id, Func? change = null, + PlatformAdmission? admission = null, Guid? tenant = null) + { + var row = await test.ReadAsync(id); + var request = new OutboxResetRequest(tenant ?? SchemaFixture.TenantA, id, row.Attempts, row.DeadLetteredAt ?? DateTimeOffset.UnixEpoch); + return await store.ResetAsync(change?.Invoke(request) ?? request, admission ?? ResetAdmission()); + } + + [Fact] + public async Task Reset_under_the_current_fence_renews_the_budget_writes_one_operator_row_and_returns_the_row_to_the_dispatcher() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.SetStateAsync(id, DeadLetterRetryExhausted + ", last_error = 'terminal:retry_exhausted:closed'"); + var store = test.Store(); + var admission = ResetAdmission(); + + var result = await ResetAsync(store, test, id, admission: admission); + + result.Should().Be(new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, 0)); + var row = await test.ReadAsync(id); + (row.Attempts, row.TerminalReason, row.DeadLetteredAt, row.LastError, row.Token, row.LockedUntil, row.ProcessedAt) + .Should().Be((0, null, null, null, null, null, null)); + var audit = (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().ContainSingle().Which; + audit.Tenant.Should().Be(SchemaFixture.TenantA); + audit.ActorIsNull.Should().BeTrue(); + audit.Reason.Should().Be("delivery_reset"); + audit.Class.Should().Be("Must"); + audit.Type.Should().Be("SecurityEvent"); + audit.Correlation.Should().Be(admission.Operator.CorrelationId); + var metadata = JsonNode.Parse(audit.Metadata)!.AsObject(); + metadata.Select(pair => pair.Key).Should().BeEquivalentTo(["operator", "event_id", "fence"]); + metadata["operator"]!.AsObject().ContainsKey("ticket").Should().BeFalse(); + metadata["event_id"]!.GetValue().Should().Be(id); + metadata["fence"]!["before"]!["attempts"]!.GetValue().Should().Be(6); + metadata["fence"]!["before"]!["dead_lettered_at"]!.GetValue().Should().Be("2026-10-01T12:00:00.1234560Z"); + metadata["fence"]!["before"]!["terminal_reason"]!.GetValue().Should().Be("retry_exhausted"); + metadata["fence"]!["after"]!["attempts"]!.GetValue().Should().Be(0); + var claim = (await store.TryClaimAsync(NoBlockedPartitions))!; + claim.Id.Should().Be(id); + claim.Attempts.Should().Be(1, "the six-attempt budget is renewed, and the runbook says so"); + (await test.DeliveryRowCountAsync()).Should().Be(0, "a producer reset writes no delivery row: acceptance reaches subscriptions on the next dispatch"); + } + + [Theory] + [InlineData("attempts")] + [InlineData("instant-after-one-microsecond")] + [InlineData("instant-before-one-microsecond")] + public async Task Reset_with_any_part_of_the_fence_changed_is_stale_and_changes_nothing(string change) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + + var result = await ResetAsync(test.Store(), test, id, request => change switch + { + "attempts" => request with { Attempts = request.Attempts + 1 }, + "instant-after-one-microsecond" => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(10) }, + _ => request with { DeadLetteredAt = request.DeadLetteredAt.AddTicks(-10) }, + }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + } + + [Theory] + [InlineData("unknown_type")] + [InlineData("retired_type")] + [InlineData("invalid_envelope")] + public async Task Reset_refuses_every_reason_but_retry_exhaustion(string reason) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, $"terminal_reason = '{reason}', dead_lettered_at = '2026-10-01 12:00:00.123456+00'"); + var before = await test.ReadAsync(id); + + var refused = await ResetAsync(test.Store(), test, id); + + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "reason_refused")); + + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + } + + [Fact] + public async Task Reset_reports_a_stale_fence_before_it_reports_a_refused_state() + { + // The fence is compared before the state: an operator who read an older row is told to read it again, and is not + // told the row is refused, even when the tenant has since stopped serving. + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + await test.SetTenantStatusAsync("Suspended"); + var before = await test.ReadAsync(id); + + var result = await ResetAsync(test.Store(), test, id, change: request => request with { Attempts = request.Attempts + 1 }); + + result.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + (await test.ReadAsync(id)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + } + + [Theory] + [InlineData("pending")] + [InlineData("processed")] + public async Task Reset_treats_a_row_that_is_not_dead_lettered_as_a_stale_fence(string state) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, state == "pending" ? "attempts = 6, terminal_reason = 'retry_exhausted'" : "processed_at = now()"); + var before = await test.ReadAsync(id); + + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + + (await test.ReadAsync(id)).Should().Be(before); + } + + [Fact] + public async Task Reset_of_a_row_whose_type_the_registry_no_longer_knows_is_not_recoverable() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var gone = await test.InsertAsync(type: "No.Such.Type, Nowhere"); + var retired = await test.InsertAsync(type: "retired.type"); + foreach (var id in new[] { gone, retired }) + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var registry = OutboxEventRegistry.Create( + [OutboxEventRegistration.IntentionallyUnsubscribed(typeof(DispatchEventV1))], ["retired.type"], + IntegrationEventHandlerRegistry.Discover(), [typeof(DispatchEventV1).Assembly]); + + foreach (var id in new[] { gone, retired }) + { + var before = await test.ReadAsync(id); + var refused = await ResetAsync(test.Store(registry), test, id); + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "type_not_dispatchable"), + "a reset would only dead-letter the row again with a second MUST row"); + (await test.ReadAsync(id)).Should().Be(before); + } + } + + [Fact] + public async Task Reset_names_the_tenant_and_a_row_of_another_tenant_or_a_missing_one_is_not_found() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + var store = test.Store(); + + (await ResetAsync(store, test, id, tenant: SchemaFixture.TenantB)).Outcome.Should().Be(OperatorRecoveryOutcome.NotFound); + (await store.ResetAsync(new OutboxResetRequest(SchemaFixture.TenantA, Guid.CreateVersion7(), 6, Occurred), ResetAdmission())) + .Outcome.Should().Be(OperatorRecoveryOutcome.NotFound); + + (await test.ReadAsync(id)).Should().Be(before); + } + + [Fact] + public async Task Reset_of_a_row_whose_tenant_is_not_serving_is_not_recoverable_until_it_serves_again() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + await test.SetTenantStatusAsync("Suspended"); + var before = await test.ReadAsync(id); + + var refused = await ResetAsync(test.Store(), test, id); + + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "tenant_not_serving")); + (await test.ReadAsync(id)).Should().Be(before); + await test.SetTenantStatusAsync("Active"); + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task A_failed_operator_audit_write_rolls_the_reset_back_and_the_spent_admission_cannot_retry() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + var admission = ResetAdmission(); + await test.AuditInsertGrantAsync(false); + + var attempt = () => ResetAsync(test.Store(), test, id, admission: admission); + + await attempt.Should().ThrowAsync(); + (await test.ReadAsync(id)).Should().Be(before); + await test.AuditInsertGrantAsync(true); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + var again = () => ResetAsync(test.Store(), test, id, admission: admission); + await again.Should().ThrowAsync(); + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + } + + [Fact] + public async Task Reset_refuses_an_admission_for_another_operation_or_a_stale_one_and_leaves_every_other_row_alone() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + var other = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + await test.SetStateAsync(other, DeadLetterRetryExhausted); + var before = await test.ReadAsync(id); + var untouched = await test.ReadAsync(other); + var store = test.Store(); + + foreach (var admission in new[] + { + ResetAdmission(operation: PlatformOperations.DeliveryReplay), + ResetAdmission(operation: PlatformOperations.IdentityAuthorityRebind), + ResetAdmission(issuedAt: Occurred.AddSeconds(-31)), + }) + { + var act = () => ResetAsync(store, test, id, admission: admission); + await act.Should().ThrowAsync(); + } + + (await test.ReadAsync(id)).Should().Be(before); + (await ResetAsync(store, test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + (await test.ReadAsync(other)).Should().Be(untouched, "another dead-lettered row is not the one the fence names"); + } + + [Fact] + public async Task A_reset_whose_commit_acknowledgement_is_lost_is_unknown_and_a_repeat_is_a_stale_fence() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var fence = await test.ReadAsync(id); + await using var proxy = new CommitResponseDroppingProxy(test.OutboxConnectionString, rejectReconciliationConnections: false); + await using var source = OutboxDispatcherDataSource.Build(proxy.ConnectionString); + + var attempt = () => ResetAsync(test.Store(dispatchSource: source), test, id); + + (await attempt.Should().ThrowAsync()).Which.CommitOutcomeUnknown.Should().BeTrue(); + (await test.ReadAsync(id)).Attempts.Should().Be(0, "the commit landed although its answer did not"); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().ContainSingle(); + var repeat = await test.Store().ResetAsync( + new OutboxResetRequest(SchemaFixture.TenantA, id, fence.Attempts, fence.DeadLetteredAt!.Value), ResetAdmission()); + repeat.Outcome.Should().Be(OperatorRecoveryOutcome.StaleFence); + } + private sealed record Row( Guid Id, int Attempts, string? Token, DateTimeOffset? LockedUntil, DateTimeOffset AvailableAfter, DateTimeOffset? ProcessedAt, string? TerminalReason, DateTimeOffset? DeadLetteredAt, string? LastError, string Type, string Payload, string? Metadata); + private sealed record OperatorAuditRow( + Guid Tenant, bool ActorIsNull, string Operation, string? Reason, string Correlation, string Metadata, string Class, string Type); + private sealed record AuditRow( Guid Tenant, Guid? Organization, Guid Actor, string Module, string Operation, string Type, string Class, string Outcome, string? Reason, string Correlation, string Metadata); + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + [InlineData("operation")] + [InlineData("reason")] + [InlineData("metadata")] + [InlineData("correlation")] + [InlineData("actor")] + [InlineData("class")] + [InlineData("type")] + [InlineData("transaction")] + public async Task Substituting_a_field_of_the_reset_row_or_its_transaction_is_refused_by_the_real_seam_and_rolls_the_reset_back( + string substitution) + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(organization: SchemaFixture.OrgA1); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var calls = 0; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + calls++; + witness.Kind.Should().Be("reset"); + witness.EventId.Should().Be(id); + witness.TenantId.Should().Be(SchemaFixture.TenantA); + witness.OrganizationId.Should().Be(SchemaFixture.OrgA1); + if (substitution == "transaction") + { + await using var otherConnection = await test.DispatchSource.OpenConnectionAsync(cancellationToken); + await using var otherTransaction = await otherConnection.BeginTransactionAsync(cancellationToken); + await inner.WriteOperatorRecoveryAsync(draft, witness, otherConnection, otherTransaction, cancellationToken); + return; + } + + var changed = substitution switch + { + "tenant" => draft with { TenantId = TenantId.From(SchemaFixture.TenantB) }, + "organization" => draft with { OrganizationId = OrganizationId.From(SchemaFixture.OrgA2) }, + "operation" => draft with { Operation = PlatformOperations.DeliveryReplay.AuditSlug }, + "reason" => draft with { Reason = PlatformOperations.DeliveryReplay.ReasonSlug }, + "metadata" => draft with { Metadata = draft.Metadata + " " }, + "correlation" => draft with { CorrelationId = "00-forged" }, + "actor" => draft with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + "class" => draft with { OperationClass = OperationClass.Should }, + "type" => draft with { OperationType = OperationType.Update }, + _ => throw new ArgumentOutOfRangeException(nameof(substitution)), + }; + await inner.WriteOperatorRecoveryAsync(changed, witness, connection, transaction, cancellationToken); + })); + var before = await test.ReadAsync(id); + + var attempt = () => ResetAsync(store, test, id); + await attempt.Should().ThrowAsync(); + + calls.Should().Be(1, "the refusal must come from the real audit seam, after a successful UPDATE"); + (await test.ReadAsync(id)).Should().Be(before, "the reset and its row commit together or not at all"); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().BeEmpty(); + (await ResetAsync(test.Store(), test, id)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the same fence succeeds through the unmodified seam"); + } + + [Fact] + public async Task A_witness_from_an_earlier_reset_cannot_be_reused_on_a_later_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + OperatorRecoveryTransition? previous = null; + var store = test.Store(decorate: inner => new OperatorRecoveryAuditDecorator(inner, + async (draft, witness, connection, transaction, cancellationToken) => + { + await inner.WriteOperatorRecoveryAsync(draft, previous ?? witness, connection, transaction, cancellationToken); + previous = witness; + })); + var first = await test.InsertAsync(); + await test.SetStateAsync(first, DeadLetterRetryExhausted); + (await ResetAsync(store, test, first)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + var second = await test.InsertAsync(); + await test.SetStateAsync(second, DeadLetterRetryExhausted); + var before = await test.ReadAsync(second); + + var attempt = () => ResetAsync(store, test, second); + await attempt.Should().ThrowAsync(); + + (await test.ReadAsync(second)).Should().Be(before); + (await test.ReadOperatorAuditAsync("platform.delivery.reset")).Should().ContainSingle("only the first reset committed"); + } + + [Fact] + public async Task The_recovery_owner_resets_through_the_outbox_store_and_counts_each_outcome_under_the_reset_operation() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var id = await test.InsertAsync(); + await test.SetStateAsync(id, DeadLetterRetryExhausted); + var fence = await test.ReadAsync(id); + var request = new OutboxResetRequest(SchemaFixture.TenantA, id, fence.Attempts, fence.DeadLetteredAt!.Value); + var owner = new OperatorRecovery(test.DeliveryStore(), test.Store()); + using var meters = new OperatorRecoveryMeterProbe(); + + var applied = await owner.ResetOutboxAsync(ResetAdmission(), request); + var stale = await owner.ResetOutboxAsync(ResetAdmission(), request); + var unknown = await owner.ResetOutboxAsync(ResetAdmission(), request with { EventId = Guid.CreateVersion7() }); + + (applied.Outcome, stale.Outcome, unknown.Outcome).Should().Be( + (OperatorRecoveryOutcome.Applied, OperatorRecoveryOutcome.StaleFence, OperatorRecoveryOutcome.NotFound)); + (await test.ReadAsync(id)).Attempts.Should().Be(0, "the owner reached the outbox store and no other"); + var reset = PlatformOperations.DeliveryReset.AuditSlug; + var replay = PlatformOperations.DeliveryReplay.AuditSlug; + (meters.Recoveries(reset, "applied"), meters.Recoveries(reset, "stale_fence"), meters.Recoveries(reset, "not_found")) + .Should().Be((1, 1, 1)); + meters.Results(reset).Should().Be(1, "only an applied reset committed a result row"); + meters.Recoveries(replay, "applied").Should().Be(0, "a producer reset is never counted as a delivery replay"); + } + + [Fact] + public async Task The_operator_lane_is_its_own_slot_so_a_busy_operator_never_costs_the_dispatcher_one() + { + await using var test = await TestDatabase.CreateAsync(schema.Postgres); + var first = await test.InsertAsync(); + var second = await test.InsertAsync(); + await test.SetStateAsync(first, DeadLetterRetryExhausted); + await test.SetStateAsync(second, DeadLetterRetryExhausted); + var store = test.Store(); + + // Hold the first row's lock, so the first reset waits inside the operator lane. + await using var holder = await test.DispatchSource.OpenConnectionAsync(); + await using var holding = await holder.BeginTransactionAsync(); + await using (var hold = new NpgsqlCommand("SELECT 1 FROM outbox_messages WHERE id = @id FOR UPDATE", holder, holding)) + { + hold.Parameters.AddWithValue("id", first); + await hold.ExecuteScalarAsync(); + } + + var waiting = ResetAsync(store, test, first); + await test.WaitForLockWaitAsync(); + + var busy = () => ResetAsync(store, test, second); + await busy.Should().ThrowAsync("one operator call at a time per store"); + (await store.ReadSnapshotAsync(NoBlockedPartitions)).Should().NotBeNull("the dispatcher's own slots are untouched"); + + await holding.CommitAsync(); + (await waiting).Outcome.Should().Be(OperatorRecoveryOutcome.Applied); + (await ResetAsync(store, test, second)).Outcome.Should().Be(OperatorRecoveryOutcome.Applied, + "the lane is free again once the first call ends"); + } + private sealed class TestDatabase : IAsyncDisposable { private readonly DisposableSchemaDatabase _database; @@ -962,6 +1365,19 @@ private TestDatabase(DisposableSchemaDatabase database) } public NpgsqlDataSource DispatchSource { get; } + + public async Task WaitForLockWaitAsync() + { + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(3)); + await using var connection = await DispatchSource.OpenConnectionAsync(); + while (true) + { + await using var command = new NpgsqlCommand( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock')", connection); + if (await command.ExecuteScalarAsync(deadline.Token) is true) return; + await Task.Delay(10, deadline.Token); + } + } public ServiceProvider Provider { get; } public string OutboxConnectionString => _database.OutboxConnectionString; @@ -980,13 +1396,20 @@ public static async Task CreateAsync(PostgresFixture postgres, boo } } + /// The subscriber store beside the producer store, for a test that builds the recovery owner over both. + public DeliveryDispatchStore DeliveryStore() => new( + new PrivilegedDataSource(() => DispatchSource), EligibleRegistry(), new DeliveryDispatchOptions(), + new SystemGuidFactory(), new FixedClock(Occurred), Provider.GetRequiredService(), + BackgroundJobLifecycleProjectionDeclaration.Create()); + public OutboxDispatchStore Store( OutboxEventRegistry? registry = null, IClock? clock = null, Func? decorate = null, NpgsqlDataSource? dispatchSource = null) => new( new PrivilegedDataSource(() => dispatchSource ?? DispatchSource), registry ?? EligibleRegistry(), new OutboxDispatchOptions(), new SystemGuidFactory(), clock ?? new FixedClock(Occurred), decorate is null ? Provider.GetRequiredService() - : new DecoratingScopeFactory(Provider.GetRequiredService(), decorate)); + : new DecoratingScopeFactory(Provider.GetRequiredService(), decorate), + BackgroundJobLifecycleProjectionDeclaration.Create()); public async Task InsertAsync( Guid? id = null, Guid? organization = null, int attempts = 0, @@ -1100,6 +1523,42 @@ public async Task AuditCountAsync(Guid? tenant = null) return (long)(await command.ExecuteScalarAsync())!; } + public async Task SetTenantStatusAsync(string status) + { + await using var connection = await _appSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.ExecuteAsync(connection, transaction, + "UPDATE tenants SET status = @status WHERE id = @tenant", ("status", status), ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + public async Task DeliveryRowCountAsync() + { + await using var connection = await DispatchSource.OpenConnectionAsync(); + await using var command = new NpgsqlCommand("SELECT count(*) FROM event_deliveries", connection); + return (long)(await command.ExecuteScalarAsync())!; + } + + public async Task> ReadOperatorAuditAsync(string operation) + { + await using var connection = await _appSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SchemaFixture.TenantA); + await SchemaQueries.SetSettingAsync(connection, transaction, "app.organization_id", SchemaFixture.OrgA1.ToString("D")); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, actor_user_id IS NULL, operation, reason, correlation_id, metadata::text, operation_class, operation_type + FROM audit_log WHERE operation = @operation ORDER BY timestamp + """, connection, transaction); + command.Parameters.AddWithValue("operation", operation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + rows.Add(new(reader.GetGuid(0), reader.GetBoolean(1), reader.GetString(2), Text(reader, 3), reader.GetString(4), + reader.GetString(5), reader.GetString(6), reader.GetString(7))); + return rows; + } + public async Task ReadAuditAsync() { await using var connection = await _appSource.OpenConnectionAsync(); @@ -1151,6 +1610,7 @@ INSERT INTO tenants (id, slug, display_name, status, created_at, created_by, row VALUES (@tenant, 'dispatch-probe', 'Dispatch probe', 'Trial', now(), @actor, 0); INSERT INTO organizations (id, tenant_id, slug, display_name, status, created_at, created_by, row_version) VALUES (@organization, @tenant, 'hq', 'HQ', 'Active', now(), @actor, 0); + UPDATE tenants SET default_organization_id = @organization WHERE id = @tenant; """, ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), ("actor", UserId.SystemActor.Value)); await transaction.CommitAsync(); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index 984230053..8a12dae2e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -12,6 +12,11 @@ using Microsoft.Extensions.Logging; using Npgsql; using Xunit; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using LearnStack.Modules.Tenancy.Infrastructure; +using LearnStack.SharedKernel.Entitlements; +using System.Diagnostics.Metrics; namespace LearnStack.Tests.Integration.Database; @@ -64,10 +69,9 @@ public async Task The_Scope_Sees_What_An_Application_Connection_Cannot() await using var platformSource = PlatformSource(_schema.Postgres.PlatformConnectionString); await using var appSource = NpgsqlDataSource.Create(_schema.Postgres.AppConnectionString); - await using var handle = await Build(platformSource).EnterAsync( - "test:cross-tenant-visibility", CancellationToken.None); + await using var handle = await Build(platformSource).EnterAsync(Admission(), CancellationToken.None); - var seenByPlatform = await CountOrganizationsAsync(handle.Connection, handle.Transaction); + var seenByPlatform = await ScalarAsync(handle, "SELECT count(*) FROM organizations"); await using var appConnection = await appSource.OpenConnectionAsync(CancellationToken.None); var seenByApplication = await CountOrganizationsAsync(appConnection, transaction: null); @@ -91,11 +95,10 @@ public async Task The_Scope_Connects_As_The_Platform_Role_On_Its_Own_Connection( var appBackend = await ScalarAsync(appConnection, null, "SELECT pg_backend_pid()"); var appUser = await ScalarAsync(appConnection, null, "SELECT current_user"); - await using var handle = await Build(platformSource).EnterAsync( - "test:provenance", CancellationToken.None); + await using var handle = await Build(platformSource).EnterAsync(Admission(), CancellationToken.None); - var scopeUser = await ScalarAsync(handle.Connection, handle.Transaction, "SELECT current_user"); - var scopeBackend = await ScalarAsync(handle.Connection, handle.Transaction, "SELECT pg_backend_pid()"); + var scopeUser = await ScalarAsync(handle, "SELECT current_user"); + var scopeBackend = await ScalarAsync(handle, "SELECT pg_backend_pid()"); appUser.Should().Be("learnstack_app"); scopeUser.Should().Be("learnstack_platform"); @@ -113,27 +116,17 @@ public async Task Disposing_Without_Committing_Rolls_Back() var scope = Build(dataSource); var host = $"rollback-{Guid.NewGuid():N}.example.com"; - await using (var handle = await scope.EnterAsync( - "test:rollback", CancellationToken.None)) - { - await using var insert = handle.Connection.CreateCommand(); - insert.Transaction = handle.Transaction; - insert.CommandText = - """ - INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) - VALUES (@host, @tenant, true, true) - """; - insert.Parameters.Add(new NpgsqlParameter("host", host)); - insert.Parameters.Add(new NpgsqlParameter("tenant", SchemaFixture.TenantA)); - await insert.ExecuteNonQueryAsync(CancellationToken.None); + await using (var handle = await scope.EnterAsync(Admission(), CancellationToken.None)) + { + await handle.ExecuteAsync( + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", + [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], + CancellationToken.None); } - await using var check = await scope.EnterAsync( - "test:rollback-check", CancellationToken.None); + await using var check = await scope.EnterAsync(Admission(), CancellationToken.None); var survivors = await ScalarAsync( - check.Connection, - check.Transaction, - "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", + check, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", [("host", (object)host)]); survivors.Should().Be(0, "disposal without a commit rolls the transaction back"); @@ -148,13 +141,12 @@ public async Task Two_Concurrent_Entries_Get_Independent_Connections() await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); var scope = Build(dataSource); - await using var first = await scope.EnterAsync("test:one", CancellationToken.None); - await using var second = await scope.EnterAsync("test:two", CancellationToken.None); + await using var first = await scope.EnterAsync(Admission(), CancellationToken.None); + await using var second = await scope.EnterAsync(Admission(), CancellationToken.None); - first.Connection.Should().NotBeSameAs(second.Connection); - (await ScalarAsync(first.Connection, first.Transaction, "SELECT pg_backend_pid()")) + (await ScalarAsync(first, "SELECT pg_backend_pid()")) .Should().NotBe( - await ScalarAsync(second.Connection, second.Transaction, "SELECT pg_backend_pid()")); + await ScalarAsync(second, "SELECT pg_backend_pid()")); } [Fact] @@ -239,27 +231,33 @@ await _schema.Postgres.ExecuteAsSuperuserAsync( } [Fact] - public async Task A_Resolved_Handle_Cannot_Be_Used_Again() + public async Task A_Resolved_Handle_Cannot_Be_Used_Again_And_Exposes_No_Connection() { - // Measured before the fence existed: after a successful commit the connection is - // still Open, so a plain SELECT on it returned every tenant's rows — in - // autocommit, on a BYPASSRLS credential, with no transaction left to undo - // anything. A write issued there SURVIVED DisposeAsync, which is the exact - // opposite of what this type's contract promises. + // The hazard the facade closes: a connection reference captured before the commit + // would run in autocommit afterwards on a role that sees every tenant. The handle + // therefore has no Connection or Transaction member to capture, refuses every call once + // resolved, and closes the underlying connection at completion (ADR-0101 § 8). + typeof(IPlatformAdminScopeHandle).GetProperties().Select(property => property.PropertyType) + .Should().NotContain(type => typeof(System.Data.Common.DbConnection).IsAssignableFrom(type) + || typeof(System.Data.Common.DbTransaction).IsAssignableFrom(type), + "a raw provider object is exactly what could be captured"); + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); - await using var handle = await Build(dataSource).EnterAsync( - "test:terminal", CancellationToken.None); + await using var handle = await Build(dataSource).EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(handle, "SELECT pg_backend_pid()")).Should().BeGreaterThan(0); - await handle.CommitAsync(CancellationToken.None); + await CompleteAsync(handle); - var readConnection = () => handle.Connection; - var readTransaction = () => handle.Transaction; + var execute = async () => await handle.ExecuteAsync("SELECT 1", null, CancellationToken.None); + var query = async () => await ScalarAsync(handle, "SELECT 1"); + var result = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, null, null, null, null), CancellationToken.None); var commitAgain = async () => await handle.CommitAsync(CancellationToken.None); - readConnection.Should().Throw( - "fencing Transaction alone would leave the autocommit hole open"); - readTransaction.Should().Throw(); - await commitAgain.Should().ThrowAsync(); + await execute.Should().ThrowAsync("a statement after the commit would be an autocommit bypass"); + await query.Should().ThrowAsync(); + await result.Should().ThrowAsync(); + await commitAgain.Should().ThrowAsync(); } [Fact] @@ -274,41 +272,28 @@ public async Task Committing_Persists_And_Disposal_Leaves_It_Alone() try { - await using (var handle = await scope.EnterAsync( - "test:commit", CancellationToken.None)) + await using (var handle = await scope.EnterAsync(Admission(), CancellationToken.None)) { - await using var insert = handle.Connection.CreateCommand(); - insert.Transaction = handle.Transaction; - insert.CommandText = - """ - INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) - VALUES (@host, @tenant, true, true) - """; - insert.Parameters.Add(new NpgsqlParameter("host", host)); - insert.Parameters.Add(new NpgsqlParameter("tenant", SchemaFixture.TenantA)); - await insert.ExecuteNonQueryAsync(CancellationToken.None); - - await handle.CommitAsync(CancellationToken.None); + await handle.ExecuteAsync( + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", + [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], + CancellationToken.None); + + await CompleteAsync(handle); } - await using var check = await scope.EnterAsync("test:check", CancellationToken.None); + await using var check = await scope.EnterAsync(Admission(), CancellationToken.None); (await ScalarAsync( - check.Connection, - check.Transaction, - "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", + check, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @host", [("host", (object)host)])) .Should().Be(1, "a committed write survives the handle that made it"); } finally { // The schema fixture is shared and other classes assert exact row counts. - await using var cleanup = await scope.EnterAsync("test:cleanup", CancellationToken.None); - await using var delete = cleanup.Connection.CreateCommand(); - delete.Transaction = cleanup.Transaction; - delete.CommandText = "DELETE FROM platform_host_to_tenant WHERE host = @host"; - delete.Parameters.Add(new NpgsqlParameter("host", host)); - await delete.ExecuteNonQueryAsync(CancellationToken.None); - await cleanup.CommitAsync(CancellationToken.None); + await using var cleanup = await scope.EnterAsync(Admission(), CancellationToken.None); + await cleanup.ExecuteAsync("DELETE FROM platform_host_to_tenant WHERE host = @host", [new PlatformSqlParameter("host", host)], CancellationToken.None); + await CompleteAsync(cleanup); } } @@ -338,26 +323,20 @@ public async Task A_Faulted_Commit_Returns_The_Connection_And_Is_Left_Indetermin for (var attempt = 0; attempt < 5; attempt++) { - var handle = await scope.EnterAsync("test:faulted", CancellationToken.None); + var handle = await scope.EnterAsync(Admission(), CancellationToken.None); await using (handle) { - await using (var suicide = handle.Connection.CreateCommand()) + // The MUST row is written first so the commit is attempted, and the backend is + // ended from outside the facade, so the statement fault guard does not stop the + // commit short of the wire: this case is about a commit that itself faults. + var pid = await ScalarAsync(handle, "SELECT pg_backend_pid()"); + await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, null), + CancellationToken.None); + await using (var killer = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString)) { - suicide.Transaction = handle.Transaction; - suicide.CommandText = "SELECT pg_terminate_backend(pg_backend_pid())"; - - try - { - await suicide.ExecuteNonQueryAsync(CancellationToken.None); - } - catch (PostgresException) - { - // The server hangs up mid-statement; that is the point. - } - catch (NpgsqlException) - { - } + await ScalarAsync(killer, null, "SELECT pg_terminate_backend(@pid)", ("pid", pid)); } var commit = async () => await handle.CommitAsync(CancellationToken.None); @@ -368,8 +347,8 @@ await commit.Should().ThrowAsync( // Five entries through a pool of three: without the disposal in a finally, this // line blocks until the pool timeout. - await using var afterwards = await scope.EnterAsync("test:after", CancellationToken.None); - afterwards.Connection.State.Should().Be(System.Data.ConnectionState.Open); + await using var afterwards = await scope.EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(afterwards, "SELECT 1")).Should().Be(1); } [Fact] @@ -397,12 +376,10 @@ public async Task An_Abandoned_Handle_On_A_Dead_Connection_Still_Returns_It() for (var attempt = 0; attempt < 5; attempt++) { - var handle = await scope.EnterAsync("test:abandoned", CancellationToken.None); + var handle = await scope.EnterAsync(Admission(), CancellationToken.None); - await using (var suicide = handle.Connection.CreateCommand()) + var suicide = new Terminator(handle); { - suicide.Transaction = handle.Transaction; - suicide.CommandText = "SELECT pg_terminate_backend(pg_backend_pid())"; try { @@ -420,8 +397,8 @@ await dispose.Should().NotThrowAsync( "throwing from disposal replaces whatever the caller was actually failing on"); } - await using var afterwards = await scope.EnterAsync("test:after", CancellationToken.None); - afterwards.Connection.State.Should().Be(System.Data.ConnectionState.Open, + await using var afterwards = await scope.EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(afterwards, "SELECT 1")).Should().Be(1, "every abandoned entry returned its connection through the finally"); logger.Entries.Should().Contain(entry => entry.EventId == 7002, @@ -445,13 +422,13 @@ public async Task Entry_Is_Recorded_At_Warning_With_The_Reason_And_The_Caller() var logger = new CapturingLogger(); var scope = Build(dataSource, logger); - await using var handle = await scope.EnterAsync("test:recorded", CancellationToken.None); + await using var handle = await scope.EnterAsync(Admission(), CancellationToken.None); var entry = logger.Entries.Should().ContainSingle(line => line.EventId == 7001).Subject; entry.Level.Should().Be(LogLevel.Warning, "an operator filtering at Information must still see a cross-tenant bypass"); - entry.Message.Should().Contain("test:recorded"); + entry.Message.Should().Contain(PlatformOperations.KillswitchToggle.ReasonSlug); entry.Message.Should().Contain(nameof(Entry_Is_Recorded_At_Warning_With_The_Reason_And_The_Caller), "the calling member is how 'the caller' is known at all with no principal"); // The property, not a substring of one machine's layout. CallerFilePath is the @@ -537,7 +514,8 @@ public async Task Entry_Is_On_The_Record_Before_The_Operation_Runs() // literal repeated here, except the ones that ARE the decision — the sentinel // tenant, the outcome, and the provenance. await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); - await using var handle = await Build(dataSource).EnterAsync("test:recorded-row"); + var correlation = $"corr-{Guid.NewGuid():N}"; + await using var handle = await Build(dataSource).EnterAsync(Admission(correlation)); await using var independent = await PostgresFixture.OpenAsync( _schema.Postgres.PlatformConnectionString); @@ -546,7 +524,8 @@ public async Task Entry_Is_On_The_Record_Before_The_Operation_Runs() "SELECT tenant_id, organization_id, module, operation, operation_type, " + "operation_class, outcome, actor_user_id, " + "metadata #>> '{caller,member}', metadata #>> '{caller,file}' " - + "FROM audit_log WHERE reason = 'test:recorded-row'"; + + "FROM audit_log WHERE correlation_id = @correlation"; + read.Parameters.Add(new NpgsqlParameter("correlation", correlation)); await using var reader = await read.ExecuteReaderAsync(); @@ -588,14 +567,14 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin // fails is still recorded. Checked on an independent connection, after the handle // is gone, because that is what durable means. await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); - var reason = "test:survives-" + ending; + var correlation = $"corr-{Guid.NewGuid():N}"; var act = async () => { - await using var handle = await Build(dataSource).EnterAsync(reason); + await using var handle = await Build(dataSource).EnterAsync(Admission(correlation)); // Privileged work first, in every ending: the access happened. - (await CountOrganizationsAsync(handle.Connection, handle.Transaction)) + (await ScalarAsync(handle, "SELECT count(*) FROM organizations")) .Should().BeGreaterThanOrEqualTo(0); switch (ending) @@ -603,7 +582,7 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin case "read-then-throw": throw new InvalidOperationException("the work failed after reading"); case "committed": - await handle.CommitAsync(); + await CompleteAsync(handle); break; } }; @@ -621,7 +600,9 @@ public async Task An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does(strin _schema.Postgres.PlatformConnectionString); var survivors = await ScalarAsync( - afterwards, null, "SELECT count(*) FROM audit_log WHERE reason = @reason", ("reason", reason)); + afterwards, null, + "SELECT count(*) FROM audit_log WHERE correlation_id = @correlation AND operation = @entry", + ("correlation", correlation), ("entry", PlatformAdminScope.EnterOperation)); survivors.Should().Be(1, "entry into a cross-tenant scope is recorded whatever the work then does"); } @@ -646,16 +627,15 @@ public async Task An_Entry_That_Cannot_Be_Recorded_Is_Not_Entered() for (var attempt = 0; attempt < 5; attempt++) { - var act = async () => await scope.EnterAsync("test:unrecordable", CancellationToken.None); + var act = async () => await scope.EnterAsync(Admission(), CancellationToken.None); await act.Should().ThrowAsync( "a cross-tenant scope that cannot be recorded must not be entered"); } - await using var afterwards = await Build(dataSource).EnterAsync( - "test:after-unrecordable", CancellationToken.None); + await using var afterwards = await Build(dataSource).EnterAsync(Admission(), CancellationToken.None); - afterwards.Connection.State.Should().Be(System.Data.ConnectionState.Open, + (await ScalarAsync(afterwards, "SELECT 1")).Should().Be(1, "every refused entry returned its connection through the catch"); } @@ -670,6 +650,873 @@ await act.Should().ThrowAsync( /// swapping that initializer for the application one, which refuses every bypassing /// role, left all six cases green. /// + [Fact] + public async Task A_Result_Row_Commits_With_The_Work_And_Carries_The_Operator_But_Not_The_Ticket_For_A_Tenant() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = $"corr-{Guid.NewGuid():N}"; + var admission = TestPlatformAdmissions.Admission(ticket: "INC-7", correlationId: correlation); + + // A throwaway tenant id: the shared fixture tenants must keep the audit rows other classes + // count, and audit_log keeps no foreign key to tenants. + var target = Guid.CreateVersion7(); + + await using (var handle = await Build(dataSource).EnterAsync(admission)) + { + await handle.WriteResultAsync(new PlatformResult( + TenantId.From(target), "PlatformKillswitch", "key-1", "{\"isEnabled\":true}", "{\"isEnabled\":false}")); + await handle.CommitAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Rows(read, correlation); + + rows.Should().HaveCount(2, "the entry row and the result row"); + var entry = rows.Single(row => row.Operation == PlatformAdminScope.EnterOperation); + entry.Tenant.Should().Be(TenantId.PlatformSentinel.Value); + entry.Metadata.Should().Contain("INC-7", "the sentinel row is invisible to every tenant, so it carries the ticket"); + entry.Actor.Should().BeNull("an operator is not a users row"); + + var result = rows.Single(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug); + result.Tenant.Should().Be(target, "a tenant-targeted act is recorded under the real tenant"); + result.Reason.Should().Be(PlatformOperations.KillswitchToggle.ReasonSlug); + result.Actor.Should().BeNull(); + using var metadata = System.Text.Json.JsonDocument.Parse(result.Metadata); + var op = metadata.RootElement.GetProperty("operator"); + op.GetProperty("subjectDigest").GetString().Should().Be(admission.Operator.SubjectDigest); + op.GetProperty("kind").GetString().Should().Be("human"); + op.GetProperty("acr").GetString().Should().Be("mfa"); + op.TryGetProperty("ticket", out _).Should().BeFalse( + "a row a tenant administrator can read never carries the operator's ticket"); + result.After.Should().Contain("false"); + } + + [Fact] + public async Task A_Result_Row_Rolls_Back_With_The_Work_While_The_Entry_Stays() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = $"corr-{Guid.NewGuid():N}"; + + await using (var handle = await Build(dataSource).EnterAsync(TestPlatformAdmissions.Admission(correlationId: correlation))) + { + await handle.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, null)); + // Disposed without a commit: the work and its MUST row go together. + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Rows(read, correlation); + + rows.Should().ContainSingle().Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, + "the entry is on the record whatever the work then did, and the result is not"); + } + + [Fact] + public async Task A_Result_Row_That_Cannot_Be_Written_Fails_The_Act_And_Leaves_No_State() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var scope = Build(dataSource, NullLogger.Instance, FailingResultStore()); + var key = KillswitchKeys.EmailDispatchEnabled; + var removals = new RecordingCache(); + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var before = await ScalarAsync(read, null, + "SELECT coalesce((SELECT is_enabled::text FROM platform_killswitches WHERE key = @k), 'absent')", ("k", key.Value)); + + var act = async () => await new KillswitchToggle(scope, removals, new SystemClock(), NullLogger.Instance) + .ToggleAsync(TestPlatformAdmissions.Admission(), key, before == "false", CancellationToken.None); + + await act.Should().ThrowAsync(); + removals.Removed.Should().Be(0, "nothing committed, so nothing is stale"); + (await ScalarAsync(read, null, + "SELECT coalesce((SELECT is_enabled::text FROM platform_killswitches WHERE key = @k), 'absent')", ("k", key.Value))) + .Should().Be(before, "the state change rolled back with the failed MUST row"); + } + + [Fact] + public async Task The_Killswitch_Toggle_Writes_The_Row_Both_Audit_Rows_And_Then_Drops_The_Cache() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var scope = Build(dataSource); + var key = KillswitchKeys.AnalyticsIngestEnabled; + var cache = new RecordingCache(async () => + { + await using var independent = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + return await ScalarAsync(independent, null, + "SELECT is_enabled::text FROM platform_killswitches WHERE key = @k", ("k", key.Value)); + }); + var toggle = new KillswitchToggle(scope, cache, new SystemClock(), NullLogger.Instance); + var correlation = $"corr-{Guid.NewGuid():N}"; + + try + { + var off = await toggle.ToggleAsync( + TestPlatformAdmissions.Admission(ticket: "INC-9", correlationId: correlation), key, false); + await using (var midway = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString)) + { + (await ScalarAsync(midway, null, + "SELECT coalesce(reason, 'null') FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().Be("null", "the ticket stays out of a table the application role can read"); + } + + var back = await toggle.ToggleAsync( + TestPlatformAdmissions.Admission(correlationId: correlation), key, true); + + off.Outcome.Should().Be(KillswitchToggleOutcome.Applied); + (off.Before, off.After).Should().Be((true, false), "no row yet means the registry default"); + (back.Before, back.After).Should().Be((false, true)); + cache.Removed.Should().Be(2, "one removal after each commit"); + cache.Observed.Should().Equal(["false", "true"], + "each removal happens after its commit, so a concurrent reload cannot repopulate the stale value"); + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT is_enabled FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().BeTrue(); + (await ScalarAsync(read, null, + "SELECT count(*) FROM platform_killswitches WHERE key = @k AND toggled_by IS NULL", ("k", key.Value))) + .Should().Be(1, "an operator is not a users row, so toggled_by stays NULL"); + var results = (await Rows(read, correlation)) + .Where(row => row.Operation == PlatformOperations.KillswitchToggle.AuditSlug).ToList(); + results.Should().HaveCount(2, "one MUST result row per flip"); + results.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null); + results.Should().OnlyContain(row => row.Reason == PlatformOperations.KillswitchToggle.ReasonSlug); + results[0].Before.Should().Contain("true"); + results[0].After.Should().Contain("false"); + results[1].Before.Should().Contain("false"); + results[1].After.Should().Contain("true"); + using var firstMetadata = System.Text.Json.JsonDocument.Parse(results[0].Metadata); + var operatorNode = firstMetadata.RootElement.GetProperty("operator"); + operatorNode.GetProperty("issuer").GetString().Should().Be(TestPlatformAdmissions.Issuer); + operatorNode.GetProperty("executor").GetString().Should().Be("operator.test"); + operatorNode.GetProperty("ticket").GetString().Should().Be("INC-9", + "a sentinel-tenant row is unreadable to every tenant, so it carries the ticket"); + using var secondMetadata = System.Text.Json.JsonDocument.Parse(results[1].Metadata); + secondMetadata.RootElement.GetProperty("operator").TryGetProperty("ticket", out _).Should().BeFalse(); + (await ScalarAsync(read, null, "SELECT toggled_at FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(30)); + (await ScalarAsync(read, null, "SELECT coalesce(reason, 'null') FROM platform_killswitches WHERE key = @k", ("k", key.Value))) + .Should().Be("null"); + } + finally + { + await using var cleanup = await Build(dataSource).EnterAsync(TestPlatformAdmissions.Admission()); + await cleanup.ExecuteAsync("DELETE FROM platform_killswitches WHERE key = @k", [new PlatformSqlParameter("k", key.Value)]); + await CompleteAsync(cleanup); + } + } + + [Fact] + public async Task An_Undeclared_Killswitch_Key_Enters_No_Scope_And_Writes_Nothing() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = $"corr-{Guid.NewGuid():N}"; + var cache = new RecordingCache(); + + var result = await new KillswitchToggle(Build(dataSource), cache, new SystemClock(), NullLogger.Instance).ToggleAsync( + TestPlatformAdmissions.Admission(correlationId: correlation), new KillswitchKey("killswitch.not.declared"), false); + + result.Outcome.Should().Be(KillswitchToggleOutcome.UnknownKey); + cache.Removed.Should().Be(0); + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await Rows(read, correlation)).Should().BeEmpty("an undeclared key is refused before a cross-tenant scope is entered"); + } + + [Fact] + public async Task A_Result_Row_Cannot_Differ_From_Its_Admission_In_Any_Bound_Attribute() + { + // The audit seam is witness-bound: the operation, the closed reason, the correlation id, the + // outcome and class, the module, the tenant, the actor and the operator attribution in + // metadata.operator are all checked against the admission, whatever the caller composed. The + // accepted control comes first so a refusal below is the attribute's, not a broken fixture. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var store = AuditStoreScopeFactory().CreateAsyncScope(); + var audit = store.ServiceProvider.GetRequiredService(); + var admission = TestPlatformAdmissions.Admission(ticket: "INC-1"); + var digest = admission.Operator.SubjectDigest; + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + string Metadata(string issuer, string? ticket = null) => + "{\"operator\":{\"issuer\":\"" + issuer + "\",\"subjectDigest\":\"" + digest + "\",\"kind\":\"human\"" + + (ticket is null ? string.Empty : ",\"ticket\":\"" + ticket + "\"") + "}}"; + + var good = new AuditEntryDraft + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "tenancy", + Operation = admission.Operation.AuditSlug, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = null, + EntityId = null, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = Metadata(admission.Operator.Issuer), + }; + + await audit.WritePlatformOperatorResultAsync(good, admission, connection, transaction); + await audit.WritePlatformOperatorResultAsync( + good with { Id = AuditEntryId.From(Guid.CreateVersion7()), Metadata = Metadata(admission.Operator.Issuer, "INC-1") }, + admission, connection, transaction); + + var refused = new Dictionary + { + ["another operation"] = good with { Operation = "tenancy.other.operation" }, + ["a non-null actor"] = good with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + ["no operator attribution"] = good with { Metadata = "{}" }, + ["no metadata"] = good with { Metadata = null }, + ["the digest in the wrong place"] = good with + { + Metadata = "{\"note\":\"" + digest + "\",\"operator\":{\"issuer\":\"" + admission.Operator.Issuer + "\"}}", + }, + ["another issuer"] = good with { Metadata = Metadata("https://elsewhere.example.test/realms/x") }, + ["an outcome of failure"] = good with { Outcome = AuditOutcome.Failed }, + ["a SHOULD class"] = good with { OperationClass = OperationClass.Should }, + ["another reason"] = good with { Reason = "other_reason" }, + ["the identity module"] = good with { ModuleName = "identity" }, + ["the nil tenant"] = good with { TenantId = TenantId.From(Guid.Empty) }, + ["another correlation id"] = good with { CorrelationId = "another" }, + ["a ticket on a tenant row"] = good with + { + TenantId = TenantId.From(Guid.CreateVersion7()), + Metadata = Metadata(admission.Operator.Issuer, "INC-1"), + }, + ["a ticket the admission never held"] = good with { Metadata = Metadata(admission.Operator.Issuer, "INC-2") }, + }; + + foreach (var (attribute, draft) in refused) + { + var act = async () => await audit.WritePlatformOperatorResultAsync(draft, admission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + } + + [Theory] + [InlineData("platform.delivery.replay")] + [InlineData("platform.delivery.reset")] + public async Task An_Admission_For_A_Recovery_Act_Opens_No_Platform_Scope_And_Writes_No_Platform_Result_Row(string slug) + { + // ADR-0103: a replay and a reset run on the dispatcher's outbox role and write their own row through the + // recovery witness. An admission minted for one is not spendable on the platform scope or on the platform + // result writer, whose draft below is otherwise exactly what that writer accepts. + var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == slug); + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var store = AuditStoreScopeFactory().CreateAsyncScope(); + var audit = store.ServiceProvider.GetRequiredService(); + var admission = TestPlatformAdmissions.Admission(operation, null, correlationId: "corr-" + Guid.NewGuid().ToString("N")); + + var enter = async () => await Build(dataSource).EnterAsync(admission); + (await enter.Should().ThrowAsync(slug)).Which.Message.Should().Contain("platform role"); + + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + var draft = new AuditEntryDraft + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.PlatformSentinel, + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "tenancy", + Operation = operation.AuditSlug, + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = null, + EntityId = null, + Outcome = AuditOutcome.Success, + ErrorKey = null, + Reason = operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = "{\"operator\":{\"issuer\":\"" + admission.Operator.Issuer + "\",\"subjectDigest\":\"" + + admission.Operator.SubjectDigest + "\",\"kind\":\"human\"}}", + }; + var write = async () => await audit.WritePlatformOperatorResultAsync(draft, admission, connection, transaction); + (await write.Should().ThrowAsync(slug)).Which.Message.Should().Contain("admission"); + } + + private static PlatformAdmission FederationAdmission(PlatformOperation operation, string? ticket, string correlation) => + TestPlatformAdmissions.Admission(operation, ticket, correlationId: correlation); + + /// + /// The tenant an operator federation row names in these cases. It has no tenants row, as an orphan's owner may + /// not, and it is not a seeded tenant, because audit_log is append-only and the isolation census that shares this + /// database counts the rows each seeded tenant sees. + /// + private static readonly Guid UnseededFederationTenant = Guid.CreateVersion7(); + + private static PlatformResult FederationIntent(Guid connection, string? after = null) => + new(TenantId.From(UnseededFederationTenant), "FederationConnection", connection.ToString("D"), "{\"classes\":[\"orphan\"]}", after); + + private static async Task> Outcomes( + System.Data.Common.DbConnection connection, string correlation) + { + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT operation, outcome::text, tenant_id, metadata::text FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id"; + command.Parameters.Add(new NpgsqlParameter("c", correlation)); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List<(string, string, Guid, string)>(); + while (await reader.ReadAsync()) rows.Add((reader.GetString(0), reader.GetString(1), reader.GetGuid(2), reader.IsDBNull(3) ? string.Empty : reader.GetString(3))); + return rows; + } + + [Fact] + public async Task An_Intent_Row_Commits_Before_The_Effect_And_Stands_When_The_Act_Is_Abandoned() + { + // ADR-0099 Amendment 11: the effect lies outside the database, so the intent must be durable before it starts. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = "corr-" + Guid.NewGuid().ToString("N"); + var host = $"intent-{Guid.NewGuid():N}.example.com"; + await using (var handle = await Build(dataSource).EnterAsync( + FederationAdmission(PlatformOperations.FederationRemove, "CHG-7", correlation))) + { + await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + + // The scope continues in a fresh transaction, and an act that then fails is rolled back by disposal. + (await InsertHostAsync(handle, host)).Should().Be(1); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Outcomes(read, correlation); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, "platform.federation.remove_attempt"); + rows[0].Tenant.Should().Be(TenantId.PlatformSentinel.Value); + rows[0].Metadata.Should().Contain("CHG-7", "the entry row is a sentinel row, which carries the ticket"); + rows[1].Outcome.Should().Be("indeterminate", "the effect had not happened when the row was written"); + rows[1].Tenant.Should().Be(UnseededFederationTenant, "the row names the tenant the caller named, never the sentinel"); + rows[1].Metadata.Should().NotContain("CHG-7", "a tenant can read this row"); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))).Should().Be(0, + "work after the checkpoint is rolled back with the abandoned scope"); + } + + [Fact] + public async Task The_Completion_Row_And_Commit_End_An_Act_With_A_Checkpoint_In_The_Order_Intent_Then_Result() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = "corr-" + Guid.NewGuid().ToString("N"); + var connection = Guid.CreateVersion7(); + await using (var handle = await Build(dataSource).EnterAsync( + FederationAdmission(PlatformOperations.FederationRemove, null, correlation))) + { + await handle.WriteIntentAsync(FederationIntent(connection)); + await handle.WriteResultAsync(FederationIntent(connection, "{\"outcome\":\"applied\"}")); + await handle.CommitAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + var rows = await Outcomes(read, correlation); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + (PlatformAdminScope.EnterOperation, "success"), + ("platform.federation.remove_attempt", "indeterminate"), + ("platform.federation.remove", "success")); + rows.Skip(1).Select(row => row.Tenant).Should().OnlyContain(tenant => tenant == UnseededFederationTenant); + } + + [Fact] + public async Task A_Checkpoint_Is_Refused_Where_It_Does_Not_Belong_And_An_Act_That_Has_One_Cannot_Skip_It() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + + // An operation that declares no attempt slug has no checkpoint. + await using (var plain = await Build(dataSource).EnterAsync(Admission())) + { + var intent = async () => await plain.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + await intent.Should().ThrowAsync().WithMessage("*declares no intent checkpoint*"); + } + + await using var handle = await Build(dataSource).EnterAsync( + FederationAdmission(PlatformOperations.FederationDisable, null, "corr-" + Guid.NewGuid().ToString("N"))); + var early = async () => await handle.WriteResultAsync(FederationIntent(Guid.CreateVersion7())); + await early.Should().ThrowAsync().WithMessage("*intent row before its result row*"); + + await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + var twice = async () => await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + await twice.Should().ThrowAsync().WithMessage("*written once*"); + } + + [Fact] + public async Task A_Failed_Intent_Write_Stops_The_Act_Before_Anything_Commits() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var correlation = "corr-" + Guid.NewGuid().ToString("N"); + await using (var handle = await Build(dataSource, NullLogger.Instance, IntentFailingStore()).EnterAsync( + FederationAdmission(PlatformOperations.FederationRemove, null, correlation))) + { + var intent = async () => await handle.WriteIntentAsync(FederationIntent(Guid.CreateVersion7())); + await intent.Should().ThrowAsync(); + + var after = async () => await handle.WriteResultAsync(FederationIntent(Guid.CreateVersion7())); + await after.Should().ThrowAsync("a faulted scope can only be abandoned"); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await Outcomes(read, correlation)).Select(row => row.Operation).Should().Equal( + [PlatformAdminScope.EnterOperation], "only the entry row stands: the effect never started"); + } + + [Fact] + public async Task An_Intent_Row_Cannot_Differ_From_Its_Admission_In_Any_Bound_Attribute() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var store = AuditStoreScopeFactory().CreateAsyncScope(); + var audit = store.ServiceProvider.GetRequiredService(); + var admission = FederationAdmission(PlatformOperations.FederationRemove, null, "corr-" + Guid.NewGuid().ToString("N")); + var digest = admission.Operator.SubjectDigest; + await using var connection = await dataSource.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + + string Metadata(string issuer, string? ticket = null) => + "{\"operator\":{\"issuer\":\"" + issuer + "\",\"subjectDigest\":\"" + digest + "\",\"kind\":\"human\"" + + (ticket is null ? string.Empty : ",\"ticket\":\"" + ticket + "\"") + "}}"; + + var good = new AuditEntryDraft + { + Id = AuditEntryId.From(Guid.CreateVersion7()), + TenantId = TenantId.From(UnseededFederationTenant), + OrganizationId = null, + ActorUserId = null, + ActorEmail = null, + ModuleName = "platform", + Operation = "platform.federation.remove_attempt", + OperationType = OperationType.SecurityEvent, + OperationClass = OperationClass.Must, + EntityType = "FederationConnection", + EntityId = Guid.CreateVersion7().ToString("D"), + Outcome = AuditOutcome.Indeterminate, + ErrorKey = null, + Reason = admission.Operation.ReasonSlug, + BeforeState = null, + AfterState = null, + Changes = null, + CorrelationId = admission.Operator.CorrelationId, + IpAddress = null, + UserAgent = null, + Timestamp = DateTimeOffset.UtcNow, + Metadata = Metadata(admission.Operator.Issuer), + }; + await audit.WritePlatformOperatorIntentAsync(good, admission, connection, transaction); + + var refused = new Dictionary + { + ["the result slug"] = good with { Operation = "platform.federation.remove" }, + ["another operation"] = good with { Operation = "platform.federation.disable_attempt" }, + ["a success outcome"] = good with { Outcome = AuditOutcome.Success }, + ["a non-null actor"] = good with { ActorUserId = UserId.From(Guid.CreateVersion7()) }, + ["no metadata"] = good with { Metadata = null }, + ["no operator attribution"] = good with { Metadata = "{}" }, + ["another issuer"] = good with { Metadata = Metadata("https://elsewhere.example.test/realms/x") }, + ["another reason"] = good with { Reason = "other_reason" }, + ["a SHOULD class"] = good with { OperationClass = OperationClass.Should }, + ["the identity module"] = good with { ModuleName = "identity" }, + ["the nil tenant"] = good with { TenantId = TenantId.From(Guid.Empty) }, + ["another correlation id"] = good with { CorrelationId = "another" }, + ["a ticket on a tenant row"] = good with { Metadata = Metadata(admission.Operator.Issuer, "INC-1") }, + }; + foreach (var (attribute, draft) in refused) + { + var act = async () => await audit.WritePlatformOperatorIntentAsync(draft, admission, connection, transaction); + (await act.Should().ThrowAsync(attribute)).Which.Message.Should().Contain("admission"); + } + + // An operation with no attempt slug presents no intent, whatever the draft says. + var killswitch = Admission(); + var wrong = async () => await audit.WritePlatformOperatorIntentAsync(good, killswitch, connection, transaction); + await wrong.Should().ThrowAsync(); + + // The offline rebind has an attempt slug too, and writes it on its own role through its own method: its admission + // is not one this writer takes, whatever the draft says. + var rebind = FederationAdmission(PlatformOperations.IdentityAuthorityRebind, null, "corr-" + Guid.NewGuid().ToString("N")); + var offline = good with + { + Operation = "identity.authority.rebind_attempt", + Reason = rebind.Operation.ReasonSlug, + CorrelationId = rebind.Operator.CorrelationId, + Metadata = Metadata(rebind.Operator.Issuer), + }; + var rebound = async () => await audit.WritePlatformOperatorIntentAsync(offline, rebind, connection, transaction); + (await rebound.Should().ThrowAsync()).Which.Message.Should().Contain("admission"); + } + + private static IServiceScopeFactory IntentFailingStore() => + new ServiceCollection() + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + /// Writes the entry row for real and fails the intent row, as an outage at the checkpoint would. + private sealed class IntentFailingAuditStore : IAuditStore + { + private readonly IAuditStore _inner = AuditStoreScopeFactory().CreateScope().ServiceProvider.GetRequiredService(); + + public Task WritePlatformScopeAsync( + AuditEntryDraft entry, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + _inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorIntentAsync( + AuditEntryDraft entry, PlatformAdmission admission, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + throw new AuditWriteFailedException("forced intent failure"); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + + [Fact] + public async Task Commit_Without_A_Result_Row_Is_Refused_And_The_Work_Rolls_Back() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"norow-{Guid.NewGuid():N}.example.com"; + + await using (var handle = await Build(dataSource).EnterAsync(Admission())) + { + await InsertHostAsync(handle, host); + + var commit = async () => await handle.CommitAsync(); + + await commit.Should().ThrowAsync().WithMessage("*MUST result row*"); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(0, "a state change with no MUST row never commits"); + } + + [Fact] + public async Task A_Failed_Statement_Leaves_The_Scope_Only_To_Be_Abandoned_And_The_Work_Rolls_Back() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"faulted-{Guid.NewGuid():N}.example.com"; + + await using (var handle = await Build(dataSource).EnterAsync(Admission())) + { + await InsertHostAsync(handle, host); + var failing = async () => await handle.ExecuteAsync("SELECT 1/0", null, CancellationToken.None); + await failing.Should().ThrowAsync(); + + // PostgreSQL would answer "current transaction is aborted"; the facade says what to do. + var next = async () => await ScalarAsync(handle, "SELECT 1"); + var result = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, null, null, null, null), CancellationToken.None); + var commit = async () => await handle.CommitAsync(); + await next.Should().ThrowAsync().WithMessage("*Dispose the scope*"); + await result.Should().ThrowAsync(); + await commit.Should().ThrowAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(0); + } + + [Theory] + [InlineData("COMMIT")] + [InlineData("ROLLBACK")] + [InlineData("BEGIN")] + [InlineData("SET app.tenant_id = 'x'")] + [InlineData("SELECT 1; COMMIT")] + [InlineData("SELECT 1; SELECT 2")] + [InlineData("DROP TABLE platform_killswitches")] + [InlineData("TRUNCATE platform_killswitches")] + [InlineData("COPY platform_killswitches TO STDOUT")] + [InlineData("DO $$ BEGIN END $$")] + [InlineData("-- comment\nSELECT 1")] + [InlineData(" ")] + [InlineData("SELECT count(*) FROM audit_log")] + [InlineData("DELETE FROM audit_log")] + [InlineData("UPDATE public.\"Audit_Log\" SET reason = 'x'")] + public async Task The_Facade_Refuses_Anything_But_One_Dml_Statement_And_Stays_Usable(string sql) + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + + var refused = async () => await handle.ExecuteAsync(sql, null, CancellationToken.None); + + await refused.Should().ThrowAsync(); + (await ScalarAsync(handle, "SELECT 1")).Should().Be(1, "a statement refused before it ran does not fault the scope"); + } + + [Theory] + [InlineData("select 1")] + [InlineData("SELECT 1;")] + [InlineData(" SELECT\n1")] + [InlineData("WITH x AS (SELECT 1 AS n) SELECT n FROM x")] + public async Task The_Facade_Accepts_One_Statement_Whatever_Its_Case_Or_Spacing(string sql) + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + + var rows = await handle.QueryAsync(sql, null, reader => reader.GetInt32(0), CancellationToken.None); + + rows.Should().Equal(1); + } + + [Fact] + public async Task The_Result_Row_Is_The_Last_Write_Of_A_Scope() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"after-{Guid.NewGuid():N}.example.com"; + await using var handle = await Build(dataSource).EnterAsync(Admission()); + await handle.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, null, null, null, null)); + + var write = async () => await InsertHostAsync(handle, host); + var read = async () => await ScalarAsync(handle, "SELECT 1"); + + await write.Should().ThrowAsync().WithMessage("*last write*"); + await read.Should().ThrowAsync("a statement after the row could change state it does not describe"); + var commit = async () => await handle.CommitAsync(); + await commit.Should().NotThrowAsync("the refused statements did not fault the scope"); + } + + [Theory] + [InlineData("{")] + [InlineData("not json")] + [InlineData("")] + public async Task A_Result_State_That_Is_Not_Json_Is_A_Programming_Error_Not_An_Audit_Outage(string state) + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + + var bad = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, state)); + + await bad.Should().ThrowAsync("not an AuditWriteFailedException, which the endpoint would report as a 503"); + await handle.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", null, "{\"ok\":true}")); + var commit = async () => await handle.CommitAsync(); + await commit.Should().NotThrowAsync("a refused argument leaves the transaction intact"); + } + + [Fact] + public async Task An_Oversized_Result_State_Is_Refused_Before_It_Reaches_The_Database() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + await using var handle = await Build(dataSource).EnterAsync(Admission()); + var oversized = "{\"padding\":\"" + new string('x', 40 * 1024) + "\"}"; + + var bad = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "k", oversized, null)); + + await bad.Should().ThrowAsync().WithMessage("*larger than*"); + } + + [Fact] + public async Task The_Connection_Is_Returned_At_Commit_Not_At_Disposal() + { + // A pool of one: the second entry can only succeed if the first scope's commit already + // returned its connection. A handle that held it until disposal would block here. + var builder = new NpgsqlConnectionStringBuilder(_schema.Postgres.PlatformConnectionString) + { + MaxPoolSize = 1, + Timeout = 3, + }; + await using var dataSource = PlatformSource(builder.ConnectionString); + var scope = Build(dataSource); + + var first = await scope.EnterAsync(Admission(), CancellationToken.None); + await CompleteAsync(first); + + await using var second = await scope.EnterAsync(Admission(), CancellationToken.None); + (await ScalarAsync(second, "SELECT 1")).Should().Be(1); + await first.DisposeAsync(); + } + + [Fact] + public async Task The_Result_Counter_Counts_A_Committed_Result_And_Not_A_Rolled_Back_One() + { + long total = 0; + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.MeterName + && instrument.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.ResultCounterName) + { + l.EnableMeasurementEvents(instrument); + } + }; + listener.SetMeasurementEventCallback((_, value, _, _) => Interlocked.Add(ref total, value)); + listener.Start(); + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var scope = Build(dataSource); + + await using (var abandoned = await scope.EnterAsync(Admission())) + { + await abandoned.WriteResultAsync(new PlatformResult(TenantId.PlatformSentinel, null, null, null, null)); + } + + Interlocked.Read(ref total).Should().Be(0, "a result that rolled back is not a result"); + + await using (var completed = await scope.EnterAsync(Admission())) + { + await CompleteAsync(completed); + } + + Interlocked.Read(ref total).Should().Be(1); + } + + [Fact] + public async Task Two_First_Toggles_Of_One_Key_Serialise_On_The_Row_Lock() + { + // SELECT ... FOR UPDATE locks nothing when no row exists, so two first toggles used to read the + // registry default as their before state. The row is created first, so exactly one of two + // concurrent first toggles sees the default and the other sees the first one's result. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var key = KillswitchKeys.EmailDispatchEnabled; + var registryDefault = KillswitchKeys.All[key]; + var toggle = new KillswitchToggle( + Build(dataSource), new RecordingCache(), new SystemClock(), NullLogger.Instance); + + for (var attempt = 0; attempt < 5; attempt++) + { + try + { + var results = await Task.WhenAll( + toggle.ToggleAsync(TestPlatformAdmissions.Admission(), key, !registryDefault), + toggle.ToggleAsync(TestPlatformAdmissions.Admission(), key, !registryDefault)); + + results.Count(result => result.Before == registryDefault).Should().Be(1, + "one toggle saw the default and the other saw the first one's committed state"); + results.Count(result => result.Before == !registryDefault).Should().Be(1); + } + finally + { + await using var cleanup = await Build(dataSource).EnterAsync(Admission()); + await cleanup.ExecuteAsync("DELETE FROM platform_killswitches WHERE key = @k", [new PlatformSqlParameter("k", key.Value)]); + await CompleteAsync(cleanup); + } + } + } + + private static Task InsertHostAsync(IPlatformAdminScopeHandle handle, string host) => + handle.ExecuteAsync( + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", + [new PlatformSqlParameter("host", host), new PlatformSqlParameter("tenant", SchemaFixture.TenantA)], + CancellationToken.None); + + private static async Task> Rows(System.Data.Common.DbConnection connection, string correlation) + { + await using var command = connection.CreateCommand(); + command.CommandText = + "SELECT tenant_id, operation, reason, actor_user_id, metadata::text, after_state::text, before_state::text " + + "FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id"; + command.Parameters.Add(new NpgsqlParameter("c", correlation)); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new AuditRow( + reader.GetGuid(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetString(2), + reader.IsDBNull(3) ? null : reader.GetGuid(3), reader.IsDBNull(4) ? string.Empty : reader.GetString(4), + reader.IsDBNull(5) ? string.Empty : reader.GetString(5), + reader.IsDBNull(6) ? string.Empty : reader.GetString(6))); + } + + return rows; + } + + private sealed record AuditRow(Guid Tenant, string Operation, string? Reason, Guid? Actor, string Metadata, string After, string Before); + + private sealed class RecordingCache(Func>? observe = null) : LearnStack.SharedKernel.Caching.ICacheService + { + public int Removed { get; private set; } + + /// What an independent connection saw at the moment of each removal. + public List Observed { get; } = []; + + public async Task RemoveAsync(string key, CancellationToken cancellationToken = default) + { + Removed++; + if (observe is not null) + { + Observed.Add(await observe()); + } + } + + public Task GetAsync(string key, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task GetOrSetAsync( + string key, Func> factory, LearnStack.SharedKernel.Caching.CacheOptions? options = null, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task SetAsync( + string key, T value, LearnStack.SharedKernel.Caching.CacheOptions? options = null, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + } + + private static IServiceScopeFactory FailingResultStore() => + new ServiceCollection() + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + /// Writes the entry row for real and fails the result row, as an outage between them would. + private sealed class ResultFailingAuditStore : IAuditStore + { + private readonly IAuditStore _inner = AuditStoreScopeFactory().CreateScope().ServiceProvider.GetRequiredService(); + + public Task WritePlatformScopeAsync( + AuditEntryDraft entry, System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => + _inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorResultAsync( + AuditEntryDraft entry, PlatformAdmission admission, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + throw new AuditWriteFailedException("forced result failure"); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } + private static NpgsqlDataSource PlatformSource(string connectionString) => LearnStack.Api.Composition.PersistenceCompositionExtensions .BuildPlatformDataSource(connectionString); @@ -698,8 +1545,7 @@ private static PlatformAdminScope Build( NpgsqlDataSource dataSource, ILogger logger, IServiceScopeFactory? auditStore = null) => - new(new PermissiveGate(), - new PrivilegedDataSource(() => dataSource), + new(new PrivilegedDataSource(() => dataSource), new AuditCatalog([new TenancyAuditCatalogSource()]), auditStore ?? AuditStoreScopeFactory(), new SystemClock(), @@ -800,11 +1646,34 @@ private static async Task ScalarAsync( return (T)(await command.ExecuteScalarAsync())!; } - /// Permits entry, so the connection is what the case observes. - private sealed class PermissiveGate : IPlatformAdminGate + /// Writes a MUST result row under the sentinel and commits, as a completed act does. + private static async Task CompleteAsync(IPlatformAdminScopeHandle handle) + { + await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, "PlatformKillswitch", "test", null, null), CancellationToken.None); + await handle.CommitAsync(CancellationToken.None); + } + + private static PlatformAdmission Admission(string? correlation = null) => + correlation is null + ? TestPlatformAdmissions.Admission() + : TestPlatformAdmissions.Admission(correlationId: correlation); + + private static async Task ScalarAsync( + IPlatformAdminScopeHandle handle, string sql, params (string Name, object Value)[] parameters) + { + var rows = await handle.QueryAsync( + sql, + parameters.Select(parameter => new PlatformSqlParameter(parameter.Name, parameter.Value)).ToList(), + reader => (T)reader.GetValue(0), + CancellationToken.None); + return rows[0]; + } + + /// Kills the scope's own backend through the facade, as an operator-side fault would. + private sealed class Terminator(IPlatformAdminScopeHandle handle) { - public ValueTask IsPermittedAsync( - string reason, CancellationToken cancellationToken = default) => - ValueTask.FromResult(true); + public Task ExecuteNonQueryAsync(CancellationToken cancellationToken) => + handle.ExecuteAsync("SELECT pg_terminate_backend(pg_backend_pid())", null, cancellationToken); } } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs new file mode 100644 index 000000000..cb8af710b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs @@ -0,0 +1,952 @@ +using System.Diagnostics.Metrics; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Tenancy.Application.Abstractions; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Hosting; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The five operator onboarding acts through the actual Program, the operator bearer scheme and the +/// ordinary pipeline, against PostgreSQL as the application role (ADR-0102). +/// +/// +/// +/// Every state assertion reads as learnstack_app under the tenant's own announcement, so what is +/// observed is what row security shows that tenant. The only owner-credential reads are of +/// platform_host_to_tenant, which has no tenant to announce, and the fixture's one deliberate +/// corruption (an administrator revoked outside the last-admin guard so the recovery has something to +/// recover). +/// +/// +/// An act is a PUT on operator-supplied identifiers, so each case that proves an act also +/// sends it again: a reply lost on the wire must cost nothing and write nothing twice. +/// +/// +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class PlatformOperatorOnboardingTests(PublicReadFixture parent) +{ + private const string Full = "operator-full"; + private const string TenantOnly = "operator-tenant-only"; + private const string BootstrapOnly = "operator-bootstrap-only"; + + [Fact] + public async Task An_Operator_Onboards_A_Tenant_Step_By_Step_And_Every_Act_Is_Audited_And_Repeatable() + { + await using var proof = await Proof.CreateAsync(parent); + using var outcomes = new ActOutcomes(); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var role = Ids.Next(); + var membership = Ids.Next(); + var slug = "onboard-" + Ids.Short(); + var host = slug + ".example.test"; + + // Provision, and send the same act again. + var provision = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization)); + await AssertOkAsync(provision); + using (var answered = JsonDocument.Parse(await provision.Content.ReadAsStringAsync())) + { + var correlation = answered.RootElement.GetProperty("correlationId").GetString(); + (await proof.CorrelationIdsAsync(tenant, "tenancy.tenant.create")).Should().Contain(correlation, + "the runbook finds an act's rows by the correlation id its answer returned"); + } + + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1); + (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + + // An exact repeat answers from what was stored; a repeat that changes any value is a different request. + using (var repeat = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))) + { + using var body = JsonDocument.Parse(await repeat.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("result").GetProperty("defaultOrganizationSlug").GetString().Should().Be("main"); + } + + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization, displayName: "Renamed")), + HttpStatusCode.Conflict, "lockey_identifier_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization, organizationSlug: "elsewhere")), + HttpStatusCode.Conflict, "lockey_identifier_taken"); + + // The host mapping comes second, as the runbook orders the steps, and again on a repeat. + var mapped = await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}"""); + await AssertOkAsync(mapped); + proof.Invalidations.Should().Equal([host], "the first run drops any cached answer for the host"); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":true}""")); + proof.Invalidations.Should().Equal([host, host], "the retry drops it again, which is the repair for a miss cached before the commit"); + (await proof.HostMappingsAsync(host)).Should().Equal(tenant); + + // The first administrator needs the role and the person first; each refusal writes nothing. + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + (await proof.CountAsync(tenant, "roles")).Should().Be(1); + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, "nobody-has-signed-in")), + HttpStatusCode.Conflict, "lockey_bootstrap_required"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject))); + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject))); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + (await proof.CountAsync(tenant, "membership_role_assignments")).Should().Be(1); + + // How each act ended, as the monitoring owner sees it: four first runs, five repeats that found their own + // earlier result (the provisioning twice and each of the others once) and four refusals. + outcomes.Counts.Should().Equal(new Dictionary + { + ["applied"] = 4, + ["replayed"] = 5, + ["refused"] = 4, + }); + + // Who the business columns name, and what the audit rows say. + (await proof.ScalarAsync(tenant, "SELECT created_by FROM public.memberships")).Should().Be(UserId.SystemActor.Value); + (await proof.ScalarAsync(tenant, "SELECT user_id FROM public.memberships")).Should().Be(proof.Person.Value); + var audit = await proof.AuditAsync(tenant); + audit.Where(row => row.Outcome == "success").Select(row => row.Operation).Distinct().Should().BeEquivalentTo( + ["tenancy.tenant.create", "tenancy.organization.create", "identity.role.initialize", + "identity.membership.create_first_admin", "tenancy.hostmapping.write"]); + audit.Should().OnlyContain(row => row.ActorUserId == null, "an operator act names no tenant user; the operator is in metadata"); + audit.Where(row => row.Outcome == "failed").Select(row => row.Operation).Should().BeEquivalentTo( + ["identity.membership.create_first_admin", "identity.membership.create_first_admin", + "tenancy.tenant.create", "tenancy.organization.create", "tenancy.tenant.create", "tenancy.organization.create"], + "the two refused first-administrator attempts and the two changed provisioning repeats are recorded as the " + + "failures they were, and nothing else failed"); + audit.Should().OnlyContain(row => row.Metadata.Contains(proof.Operator.Issuer, StringComparison.Ordinal), + "every row carries the admitted operator's issuer"); + audit.Should().OnlyContain(row => !row.Metadata.Contains(proof.PersonSubject, StringComparison.Ordinal) + && !row.Metadata.Contains(Full, StringComparison.Ordinal), "neither the person's subject nor the operator's raw subject is stored"); + audit.Should().OnlyContain(row => !row.Metadata.Contains("INC-77", StringComparison.Ordinal), "the ticket stays out of rows a tenant can read"); + audit.Select(row => row.Reason).Distinct().Should().BeEquivalentTo( + ["tenant_provision", "role_initialize", "first_admin_create", "host_map"]); + foreach (var row in audit) + { + using var metadata = JsonDocument.Parse(row.Metadata); + var @operator = metadata.RootElement.GetProperty("operator"); + @operator.GetProperty("issuer").GetString().Should().Be(proof.Operator.Issuer); + @operator.GetProperty("acr").GetString().Should().Be("mfa"); + @operator.GetProperty("kind").GetString().Should().Be("human"); + @operator.GetProperty("executor").GetString().Should().NotBeNullOrWhiteSpace(); + @operator.GetProperty("subjectDigest").GetString().Should().MatchRegex("^[A-Za-z0-9_-]{43}$"); + metadata.RootElement.GetProperty("authorization").GetProperty("source").GetString().Should().Be("operator"); + } + } + + [Fact] + public async Task A_Grant_Is_Evaluated_Per_Act_And_A_Refused_Act_Writes_Nothing() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var slug = "grants-" + Ids.Short(); + + // Holding the tenant grant is not holding the bootstrap grant, and the reverse. + (await proof.PutAsync(BootstrapOnly, $"/tenants/{tenant}", ProvisionBody(slug, organization))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + await AssertOkAsync(await proof.PutAsync(TenantOnly, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + + var role = Ids.Next(); + (await proof.PutAsync(TenantOnly, $"/tenants/{tenant}/roles/{role}", RoleBody())).StatusCode.Should().Be(HttpStatusCode.Forbidden); + (await proof.PutAsync(TenantOnly, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + (await proof.PutAsync(TenantOnly, RecoveryPath(tenant, Ids.Next()), AdminBody(role, proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + (await proof.PutAsync("somebody-without-a-grant", $"/tenants/{Ids.Next()}", ProvisionBody("x-" + Ids.Short(), Ids.Next()))).StatusCode + .Should().Be(HttpStatusCode.Forbidden); + + (await proof.CountAsync(tenant, "roles")).Should().Be(0, "a refused act reaches no handler"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + } + + [Fact] + public async Task An_Act_On_A_Tenant_That_Does_Not_Exist_Is_Not_Found_And_A_Taken_Name_Is_Refused() + { + await using var proof = await Proof.CreateAsync(parent); + var missing = Ids.Next(); + + (await proof.PutAsync(Full, $"/tenants/{missing}/host-mappings/missing.example.test", LiveFlags)).StatusCode + .Should().Be(HttpStatusCode.NotFound); + (await proof.PutAsync(Full, $"/tenants/{missing}/roles/{Ids.Next()}", RoleBody())).StatusCode + .Should().Be(HttpStatusCode.NotFound); + (await proof.PutAsync(Full, FirstAdminPath(missing, Ids.Next()), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.NotFound); + + var first = Ids.Next(); + var slug = "taken-" + Ids.Short(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{first}", ProvisionBody(slug, Ids.Next()))); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{Ids.Next()}", ProvisionBody(slug, Ids.Next())), + HttpStatusCode.Conflict, "lockey_slug_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{first}", ProvisionBody("another-" + Ids.Short(), Ids.Next())), + HttpStatusCode.Conflict, "lockey_identifier_taken"); + } + + [Fact] + public async Task Identifiers_That_Are_Not_UuidV7_Are_Refused_Before_Any_Write() + { + await using var proof = await Proof.CreateAsync(parent); + var v4 = Guid.NewGuid(); + var tenant = Ids.Next(); + + (await proof.PutAsync(Full, $"/tenants/{v4}", ProvisionBody("v4-" + Ids.Short(), Ids.Next()))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "the tenant id is the act's identity and must be a UUIDv7"); + (await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("v4-" + Ids.Short(), v4))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "nor may the default organization's"); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{v4}", RoleBody())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, FirstAdminPath(tenant, v4), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(v4, proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, RecoveryPath(tenant, v4), AdminBody(Ids.Next(), proof.PersonSubject))).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.CountAsync(v4, "tenants")).Should().Be(0); + (await proof.CountAsync(tenant, "tenants")).Should().Be(0); + } + + [Fact] + public async Task A_Person_Whose_Binding_Is_No_Longer_Active_Cannot_Be_Named_An_Administrator() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var role = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("closing-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + await proof.CloseUserAsync(proof.Person); + + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_bootstrap_required"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + } + + [Fact] + public async Task A_Reply_Lost_After_The_Commit_Is_Answered_By_Sending_The_Same_Request_Again() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var slug = "lost-" + Ids.Short(); + using var lossy = proof.ClientWith(services => services.Insert(0, ServiceDescriptor.Scoped< + IPipelineBehavior>, LoseTheReplyAfterTheCommit>())); + + using var lost = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization), lossy); + + lost.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the act committed and the operator was told it failed"); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1, "the commit is real whatever the operator was told"); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1); + (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + (await proof.AuditAsync(tenant)).Count(row => row.Operation == "tenancy.tenant.create" && row.Outcome == "success") + .Should().Be(2, "the first run wrote the create; the retry is recorded as the repeated act it is, without a second tenant"); + } + + [Fact] + public async Task An_Act_Interrupted_Between_Its_Writes_Leaves_Nothing_And_The_Retry_Completes_Once() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var organization = Ids.Next(); + var slug = "cut-" + Ids.Short(); + using var failing = proof.ClientWith(services => + { + var registered = services.Last(descriptor => descriptor.ServiceType == typeof(ITenantWriteStore)); + services.Remove(registered); + services.AddScoped(provider => new FailTheLastWrite((ITenantWriteStore)( + registered.ImplementationFactory?.Invoke(provider) + ?? ActivatorUtilities.CreateInstance(provider, registered.ImplementationType!)))); + }); + + using var cut = await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization), failing); + + cut.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await proof.CountAsync(tenant, "tenants")).Should().Be(0, "the tenant and organization inserts rolled back with the act"); + (await proof.CountAsync(tenant, "organizations")).Should().Be(0); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody(slug, organization))); + (await proof.CountAsync(tenant, "tenants")).Should().Be(1); + (await proof.CountAsync(tenant, "organizations")).Should().Be(1); + } + + [Fact] + public async Task A_Lock_The_Act_Could_Not_Take_Answers_503_With_Its_Delay_Like_Every_Other_503() + { + await using var proof = await Proof.CreateAsync(parent); + using var unavailable = proof.ClientWith(services => services.Insert(0, ServiceDescriptor.Scoped< + IPipelineBehavior>, ReportUnavailable>())); + + using var refused = await proof.PutAsync( + Full, $"/tenants/{Ids.Next()}", ProvisionBody("busy-" + Ids.Short(), Ids.Next()), unavailable); + + refused.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + refused.Headers.RetryAfter.Should().NotBeNull("the operator document declares the delay on every 503"); + } + + [Fact] + public async Task The_Platform_Sentinel_And_A_Malformed_Request_Are_Refused_With_The_Status_An_Operator_Can_Act_On() + { + await using var proof = await Proof.CreateAsync(parent); + var sentinel = TenantId.PlatformSentinel.Value; + var tenant = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("shape-" + Ids.Short(), Ids.Next()))); + + (await proof.PutAsync(Full, $"/tenants/{sentinel}/roles/{Ids.Next()}", RoleBody())).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "the sentinel is the platform's own tenant and no act may name it"); + (await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(Ids.Next(), " "))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "a blank subject is a malformed request"); + (await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(Ids.Next(), new string('x', 256)))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "a subject over 255 characters is a malformed request"); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", + """{"builtInKey":"TenantAdmin","capabilityScope":"Tenant","ticket":"has a space"}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "the ticket grammar is enforced at the gate"); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", "{ not json")).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", """{"builtInKey":"Nobody","capabilityScope":"Tenant"}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "an unknown template key is refused before any act"); + foreach (var lenient in new[] { "Instructor,Guardian", "1", " TenantAdmin", "tenantadmin,", "7" }) + { + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", + JsonSerializer.Serialize(new { builtInKey = lenient, capabilityScope = "Tenant" }))).StatusCode + .Should().Be(HttpStatusCode.BadRequest, $"'{lenient}' is not the exact name of a template"); + } + + (await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", """{"builtInKey":"Learner","capabilityScope":"Tenant,Organization"}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest, "nor of a scope"); + (await proof.SendAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", new StringContent(RoleBody(), Encoding.UTF8, "text/plain"))).StatusCode + .Should().Be(HttpStatusCode.UnsupportedMediaType); + (await proof.CountAsync(tenant, "roles")).Should().Be(0); + } + + [Fact] + public async Task A_Host_Mapping_States_Both_Flags_And_Refuses_A_Host_Another_Tenant_Holds_And_A_Foreign_Organization() + { + await using var proof = await Proof.CreateAsync(parent); + var first = Ids.Next(); + var second = Ids.Next(); + var secondOrganization = Ids.Next(); + var host = "shared-" + Ids.Short() + ".example.test"; + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{first}", ProvisionBody("one-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{second}", ProvisionBody("two-" + Ids.Short(), secondOrganization))); + + // No unmap act exists, so a mapping never arrives serving traffic because a field was left out. + (await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", "{}")).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", """{"isActive":true}""")).StatusCode + .Should().Be(HttpStatusCode.BadRequest); + (await proof.HostMappingsAsync(host)).Should().BeEmpty(); + + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", LiveFlags)); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{second}/host-mappings/{host}", LiveFlags), + HttpStatusCode.Conflict, "lockey_host_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/{host}", """{"isActive":true,"isPubliclyLive":false}"""), + HttpStatusCode.Conflict, "lockey_host_taken"); + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{first}/host-mappings/other-{Ids.Short()}.example.test", + JsonSerializer.Serialize(new { organizationId = secondOrganization, isActive = true, isPubliclyLive = true })), + HttpStatusCode.Conflict, "lockey_organization_not_in_tenant"); + (await proof.HostMappingsAsync(host)).Should().Equal(first); + } + + [Fact] + public async Task Organization_Scope_Templates_Are_Initialized_And_Only_A_Tenant_Administrator_Role_Of_This_Tenant_Can_Administer() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var other = Ids.Next(); + var adminRole = Ids.Next(); + var orgAdminRole = Ids.Next(); + var otherRole = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("scoped-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{other}", ProvisionBody("other-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{adminRole}", RoleBody())); + await AssertOkAsync(await proof.PutAsync( + Full, $"/tenants/{tenant}/roles/{orgAdminRole}", """{"builtInKey":"OrgAdmin","capabilityScope":"Organization"}""")); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{other}/roles/{otherRole}", RoleBody())); + (await proof.CountAsync(tenant, "roles")).Should().Be(2); + + // An Organization-scope administrator template and another tenant's administrator template are not this + // tenant's tenant-wide administrator Role. + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(orgAdminRole, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(otherRole, proof.PersonSubject)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(0); + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(adminRole, proof.PersonSubject))); + } + + [Fact] + public async Task A_Retry_Of_The_First_Administrator_Still_Answers_After_The_Role_Template_Was_Edited() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, role, membership) = await proof.OnboardAsync(Full); + await proof.EditRoleOutsideTheActsAsync(tenant, role); + + // The administrator edited the template after the first run, so it is no longer the pristine one the + // act created; the retry of the original act must still find its Membership and answer. + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(role, proof.PersonSubject))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{role}", RoleBody())); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + } + + [Fact] + public async Task The_First_Administrator_Is_Refused_Once_A_Tenant_Has_Had_Any_Member() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, role, _) = await proof.OnboardAsync(Full); + var (_, second) = await proof.AnotherPersonAsync(); + + await AssertRuleAsync( + await proof.PutAsync(Full, FirstAdminPath(tenant, Ids.Next()), AdminBody(role, second)), + HttpStatusCode.Conflict, "lockey_tenant_has_memberships"); + // Nor may a Role template be created once a Membership exists. + await AssertRuleAsync( + await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{Ids.Next()}", RoleBody()), + HttpStatusCode.Conflict, "lockey_tenant_has_memberships"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + } + + [Fact] + public async Task A_Recovery_Is_Refused_While_An_Administrator_Is_Active_And_Succeeds_Once_None_Is() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, role, firstMembership) = await proof.OnboardAsync(Full); + var (secondUser, second) = await proof.AnotherPersonAsync(); + var replacement = Ids.Next(); + + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, replacement), AdminBody(role, second)), + HttpStatusCode.Conflict, "lockey_administrator_exists"); + (await proof.CountAsync(tenant, "memberships")).Should().Be(1); + + // The database never lets the last administrator be revoked, so the state a recovery exists for is + // reached only by an owner-level repair that steps outside the guard; the fixture does exactly that. + await proof.SuspendOutsideTheGuardAsync(tenant, firstMembership); + + await AssertOkAsync(await proof.PutAsync(Full, RecoveryPath(tenant, replacement), AdminBody(role, second))); + await AssertOkAsync(await proof.PutAsync(Full, RecoveryPath(tenant, replacement), AdminBody(role, second))); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(1); + (await proof.AuditAsync(tenant)).Should().Contain(row => + row.Operation == "identity.membership.recover_admin" && row.Reason == "admin_recover" && row.Outcome == "success"); + + // The act is repeatable but not additive: with an administrator active again a third person is refused. + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(role, (await proof.AnotherPersonAsync()).Subject)), + HttpStatusCode.Conflict, "lockey_administrator_exists"); + + // The last-administrator invariant is the database's and the recovery leaves it as it found it: the + // replacement, now the only administrator, cannot be revoked by the application role. + var revoke = () => proof.RevokeAsApplicationRoleAsync(tenant, replacement, secondUser); + (await revoke.Should().ThrowAsync()).Which.SqlState.Should().Be("P0303"); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(1); + } + + [Fact] + public async Task A_Recovery_Names_An_Initialized_Administrator_Role_Of_The_Tenant_And_A_Person_Who_Has_Signed_In() + { + await using var proof = await Proof.CreateAsync(parent); + var (tenant, _, firstMembership) = await proof.OnboardAsync(Full); + await proof.SuspendOutsideTheGuardAsync(tenant, firstMembership); + var (_, second) = await proof.AnotherPersonAsync(); + + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(Ids.Next(), second)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(Ids.Next(), "nobody-has-signed-in")), + HttpStatusCode.Conflict, "lockey_bootstrap_required"); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(0); + } + + [Fact] + public async Task A_Recovery_Is_Refused_For_A_Role_That_Is_Not_An_Administrator_Role_Of_The_Tenant() + { + await using var proof = await Proof.CreateAsync(parent); + var tenant = Ids.Next(); + var adminRole = Ids.Next(); + var learnerRole = Ids.Next(); + var membership = Ids.Next(); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}", ProvisionBody("roles-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await proof.PutAsync(Full, $"/tenants/{tenant}/roles/{adminRole}", RoleBody())); + await AssertOkAsync(await proof.PutAsync( + Full, $"/tenants/{tenant}/roles/{learnerRole}", """{"builtInKey":"Learner","capabilityScope":"Tenant"}""")); + await AssertOkAsync(await proof.PutAsync(Full, FirstAdminPath(tenant, membership), AdminBody(adminRole, proof.PersonSubject))); + await proof.SuspendOutsideTheGuardAsync(tenant, membership); + var (_, second) = await proof.AnotherPersonAsync(); + + await AssertRuleAsync( + await proof.PutAsync(Full, RecoveryPath(tenant, Ids.Next()), AdminBody(learnerRole, second)), + HttpStatusCode.Conflict, "lockey_role_not_initialized"); + (await proof.ScalarAsync(tenant, "SELECT count(*) FROM public.memberships WHERE status='Active'")).Should().Be(0); + } + + private const string LiveFlags = """{"isActive":true,"isPubliclyLive":true}"""; + + private static string ProvisionBody(string slug, Guid organization, string? displayName = null, string organizationSlug = "main") => + JsonSerializer.Serialize(new + { + slug, + displayName = displayName ?? "Onboarded " + slug, + defaultOrganization = new { id = organization, slug = organizationSlug, displayName = "Main" }, + ticket = "INC-77", + }); + + private static string RoleBody() => """{"builtInKey":"TenantAdmin","capabilityScope":"Tenant","ticket":"INC-77"}"""; + + private static string AdminBody(Guid role, string subject) => JsonSerializer.Serialize(new { roleId = role, providerSubject = subject, ticket = "INC-77" }); + + private static string FirstAdminPath(Guid tenant, Guid membership) => $"/tenants/{tenant}/first-administrator/{membership}"; + + private static string RecoveryPath(Guid tenant, Guid membership) => $"/tenants/{tenant}/administrator-recovery/{membership}"; + + private static async Task AssertOkAsync(HttpResponseMessage response) + { + var text = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, text); + using var document = JsonDocument.Parse(text); + document.RootElement.GetProperty("correlationId").GetString().Should().NotBeNullOrWhiteSpace(); + } + + private static async Task AssertRuleAsync(HttpResponseMessage response, HttpStatusCode status, string reason) + { + var text = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(status, text); + text.Should().Contain(reason); + } + + private static class Ids + { + internal static Guid Next() => Guid.CreateVersion7(); + + internal static string Short() => Guid.NewGuid().ToString("N")[..10]; + } + + private sealed record AuditRow(string Operation, string Outcome, Guid? ActorUserId, string? Reason, string Metadata); + + private sealed class Proof : IAsyncDisposable + { + private readonly HttpClient _client; + private readonly Dictionary _tokens = []; + private readonly List _extraClients = []; + + private Proof(TenantAuthenticationIssuer tenantIssuer, TenantAuthenticationIssuer @operator, + IdentityPublicReadFixture database, UserId person, string personSubject, HttpClient client, + List invalidations) + { + Invalidations = invalidations; + TenantIssuer = tenantIssuer; + Operator = @operator; + Database = database; + Person = person; + PersonSubject = personSubject; + _client = client; + } + + internal TenantAuthenticationIssuer TenantIssuer { get; } + + internal TenantAuthenticationIssuer Operator { get; } + + internal IdentityPublicReadFixture Database { get; } + + internal UserId Person { get; } + + internal string PersonSubject { get; } + + /// The hosts whose cached resolution the acts dropped, in order. + internal List Invalidations { get; } + + internal static async Task CreateAsync(PublicReadFixture parent) + { + var tenantIssuer = await TenantAuthenticationIssuer.StartAsync(); + var @operator = await TenantAuthenticationIssuer.StartAsync(); + var person = UserId.From(Guid.CreateVersion7()); + var subject = "onboarding-person-" + person.Value.ToString("N"); + IdentityPublicReadFixture? database = null; + HttpClient? client = null; + var invalidations = new List(); + try + { + database = await IdentityPublicReadFixture.CreateAsync( + parent, tenantIssuer.Issuer, new Dictionary { [person] = subject }); + client = database.ClientFor("localhost", + services => services.AddSingleton(new RecordingInvalidator(invalidations)), + ConfigureOperator(@operator)); + return new Proof(tenantIssuer, @operator, database, person, subject, client, invalidations); + } + catch + { + client?.Dispose(); + if (database is not null) await database.DisposeAsync(); + await @operator.DisposeAsync(); + await tenantIssuer.DisposeAsync(); + throw; + } + } + + private static Action ConfigureOperator(TenantAuthenticationIssuer @operator) => builder => + { + builder.UseSetting("PlatformOperator:Issuer", @operator.Issuer); + builder.UseSetting("PlatformOperator:AcceptedAcr:0", "mfa"); + builder.UseSetting("PlatformOperator:AuthorizedParties:0", "learnstack-operator"); + var grants = new (string Subject, string[] Keys)[] + { + (Full, [PlatformPermissions.TenantWrite.Key, PlatformPermissions.TenantBootstrapWrite.Key]), + (TenantOnly, [PlatformPermissions.TenantWrite.Key]), + (BootstrapOnly, [PlatformPermissions.TenantBootstrapWrite.Key]), + }; + for (var index = 0; index < grants.Length; index++) + { + builder.UseSetting($"PlatformOperator:Grants:{index}:Subject", grants[index].Subject); + for (var key = 0; key < grants[index].Keys.Length; key++) + { + builder.UseSetting($"PlatformOperator:Grants:{index}:Permissions:{key}", grants[index].Keys[key]); + } + } + }; + + /// + /// A second host over the same database whose services changes, for the cases + /// that make an act fail where the production code would not. + /// + internal HttpClient ClientWith(Action configure) + { + var client = Database.ClientFor("localhost", configure, ConfigureOperator(Operator)); + _extraClients.Add(client); + return client; + } + + internal async Task PutAsync(string operatorSubject, string path, string json, HttpClient? client = null) => + await SendAsync(operatorSubject, path, new StringContent(json, Encoding.UTF8, "application/json"), client); + + internal async Task SendAsync( + string operatorSubject, string path, HttpContent content, HttpClient? client = null) + { + if (!_tokens.TryGetValue(operatorSubject, out var token)) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + token = Operator.Token(JsonSerializer.Serialize(new Dictionary + { + ["iss"] = Operator.Issuer, + ["sub"] = operatorSubject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + })); + _tokens[operatorSubject] = token; + } + + using var request = new HttpRequestMessage(HttpMethod.Put, "/api/platform/v1" + path) + { + Headers = { Authorization = new AuthenticationHeaderValue("Bearer", token) }, + Content = content, + }; + return await (client ?? _client).SendAsync(request); + } + + /// The correlation ids of the audit rows of one operation in the tenant. + internal async Task> CorrelationIdsAsync(Guid tenant, string operation) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand( + "SELECT correlation_id FROM public.audit_log WHERE operation=@operation", app, transaction); + command.Parameters.AddWithValue("operation", operation); + await using var reader = await command.ExecuteReaderAsync(); + var ids = new List(); + while (await reader.ReadAsync()) + { + ids.Add(reader.GetString(0)); + } + + return ids; + } + + /// A person who has signed in, so the first-sign-in bootstrap has bound them. + internal async Task<(UserId Person, string Subject)> AnotherPersonAsync() + { + var person = UserId.From(Guid.CreateVersion7()); + var subject = "onboarding-person-" + person.Value.ToString("N"); + await Database.AdoptAsync(person, subject); + return (person, subject); + } + + /// + /// A user closed, with the immutability trigger and the insert check stepped around exactly as the + /// administration-eligibility cases do, and restored before the next act runs. + /// + internal async Task CloseUserAsync(UserId user) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.MigrationConnectionString); + var check = await IdentityMembershipFixture.ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + await using var transaction = await owner.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{user.Value:D}'::uuid AND status='Closing' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='Closing' WHERE id='{user.Value:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """); + await transaction.CommitAsync(); + } + + /// + /// A later edit of the Role by its owner, which bumps the row version the way an administrator's edit does, with + /// the same locks a handler would take. + /// + internal async Task EditRoleOutsideTheActsAsync(Guid tenant, Guid role) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await IdentityMembershipFixture.LockAsync(app, transaction, tenant, null, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, + "UPDATE public.roles SET row_version=row_version+1, updated_at=clock_timestamp(), updated_by=@actor WHERE id=@role", + ("actor", UserId.SystemActor.Value), ("role", role)); + await transaction.CommitAsync(); + } + + /// The whole onboarding through the real routes; returns the tenant, its role and its first membership. + internal async Task<(Guid Tenant, Guid Role, Guid Membership)> OnboardAsync(string operatorSubject) + { + var tenant = Ids.Next(); + var role = Ids.Next(); + var membership = Ids.Next(); + await AssertOkAsync(await PutAsync(operatorSubject, $"/tenants/{tenant}", ProvisionBody("full-" + Ids.Short(), Ids.Next()))); + await AssertOkAsync(await PutAsync(operatorSubject, $"/tenants/{tenant}/roles/{role}", RoleBody())); + await AssertOkAsync(await PutAsync(operatorSubject, FirstAdminPath(tenant, membership), AdminBody(role, PersonSubject))); + return (tenant, role, membership); + } + + internal Task CountAsync(Guid tenant, string table) => + ScalarAsync(tenant, $"SELECT count(*) FROM public.{table}"); + + internal async Task ScalarAsync(Guid tenant, string sql) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand(sql, app, transaction); + return (T)(await command.ExecuteScalarAsync())!; + } + + internal async Task> AuditAsync(Guid tenant) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand( + "SELECT operation,outcome,actor_user_id,reason,metadata::text FROM public.audit_log ORDER BY timestamp", app, transaction); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new( + reader.GetString(0), reader.GetString(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), + reader.IsDBNull(3) ? null : reader.GetString(3), reader.GetString(4))); + } + + return rows; + } + + /// + /// What the resolver itself would read for the host: the application role, announcing only the host + /// it is resolving, which is the one thing row security lets it see of the host index. + /// + internal async Task> HostMappingsAsync(string host) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync( + app, transaction, "SELECT set_config('app.resolving_host', @host, true)", ("host", host)); + await using var command = new NpgsqlCommand( + "SELECT tenant_id FROM public.platform_host_to_tenant WHERE host=@host", app, transaction); + command.Parameters.AddWithValue("host", host); + await using var reader = await command.ExecuteReaderAsync(); + var tenants = new List(); + while (await reader.ReadAsync()) + { + tenants.Add(reader.GetGuid(0)); + } + + return tenants; + } + + /// + /// The fixture's one deliberate corruption: the only administrator suspended with the deferred + /// last-administrator guard stepped around, which is the state a recovery exists for. + /// + /// + /// The owner is subject to forced row security, so it announces the tenant like any other connection and + /// takes the same locks; what it skips is the commit-time guard that refuses a tenant with no administrator. + /// + internal async Task SuspendOutsideTheGuardAsync(Guid tenant, Guid membership) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(owner, transaction, tenant); + await IdentityMembershipFixture.LockAsync(owner, transaction, tenant, Person.Value, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, "ALTER TABLE public.memberships DISABLE TRIGGER tg_memberships_complete_graph"); + await IdentityMembershipFixture.ExecuteAsync( + owner, transaction, "UPDATE public.memberships SET status='Suspended' WHERE id=@membership", ("membership", membership)); + await IdentityMembershipFixture.ExecuteAsync(owner, transaction, "ALTER TABLE public.memberships ENABLE TRIGGER tg_memberships_complete_graph"); + await transaction.CommitAsync(); + } + + /// An ordinary revocation by the application role, under the locks a handler would take. + internal async Task RevokeAsApplicationRoleAsync(Guid tenant, Guid membership, UserId user) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant); + await IdentityMembershipFixture.LockAsync(app, transaction, tenant, user.Value, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@actor WHERE id=@membership + """, ("actor", UserId.SystemActor.Value), ("membership", membership)); + await transaction.CommitAsync(); + } + + public async ValueTask DisposeAsync() + { + foreach (var extra in _extraClients) + { + extra.Dispose(); + } + + _client.Dispose(); + await Database.DisposeAsync(); + await Operator.DisposeAsync(); + await TenantIssuer.DisposeAsync(); + } + } + + /// Counts the outcome label of every onboarding act counted while it is alive. + private sealed class ActOutcomes : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly Dictionary _counts = []; + + public ActOutcomes() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.MeterName + && instrument.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.ActCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag is { Key: "outcome", Value: string outcome }) + { + lock (_counts) + { + _counts[outcome] = _counts.GetValueOrDefault(outcome) + 1; + } + } + } + }); + _listener.Start(); + } + + public IReadOnlyDictionary Counts + { + get + { + lock (_counts) + { + return new Dictionary(_counts); + } + } + } + + public void Dispose() => _listener.Dispose(); + } + + private sealed class RecordingInvalidator(List hosts) : IHostResolutionInvalidator + { + public Task InvalidateAsync(string normalizedHost, CancellationToken cancellationToken = default) + { + hosts.Add(normalizedHost); + return Task.CompletedTask; + } + } + + /// A reply lost after the commit: the outermost behavior fails once the whole act, commit included, is done. + private sealed class LoseTheReplyAfterTheCommit + : IPipelineBehavior> + { + public async Task> Handle( + OperatorProvisionTenantCommand request, + RequestHandlerDelegate> next, + CancellationToken cancellationToken) + { + await next(); + throw new InvalidOperationException("The reply was lost after the commit."); + } + } + + /// A lock the act could not take, as the guard reports it: a failure result and no write. + private sealed class ReportUnavailable + : IPipelineBehavior> + { + public Task> Handle( + OperatorProvisionTenantCommand request, + RequestHandlerDelegate> next, + CancellationToken cancellationToken) => + Task.FromResult(Result.FailFor>(new Error(new LocalizedMessage("lockey_dependency_unavailable")))); + } + + /// The tenant store with its third write, the default-organization back-reference, failing. + private sealed class FailTheLastWrite(ITenantWriteStore inner) : ITenantWriteStore + { + public Task AddAsync(LearnStack.Modules.Tenancy.Domain.Tenant aggregate, CancellationToken cancellationToken = default) => + inner.AddAsync(aggregate, cancellationToken); + + public Task UpdateAsync(LearnStack.Modules.Tenancy.Domain.Tenant aggregate, CancellationToken cancellationToken = default) => + throw new InvalidOperationException("The act was interrupted between its writes."); + + public Task FindAsync(TenantId id, CancellationToken cancellationToken = default) => + inner.FindAsync(id, cancellationToken); + + public Task FindForUpdateAsync(TenantId id, CancellationToken cancellationToken = default) => + inner.FindForUpdateAsync(id, cancellationToken); + } +} + diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs index c7856d592..29d7e0e00 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PostgresFixture.cs @@ -90,6 +90,7 @@ public sealed class PostgresFixture : IAsyncLifetime private const string PlatformPassword = "platform-test"; private const string OutboxPassword = "outbox-test"; private const string IngressPassword = "ingress-test"; + private const string RebindPassword = "rebind-test"; private const string ContainerScriptPath = "/tmp/02-create-roles.sql"; // Pinned to the tag infra/compose/dev.yml runs. A fixture on a different major would @@ -97,7 +98,7 @@ public sealed class PostgresFixture : IAsyncLifetime private readonly PostgreSqlContainer _container = new PostgreSqlBuilder("postgres:18.4-alpine") .WithDatabase(Database) // Qualification can hold the supported job application (128) and - // privileged (158) source boundaries together, plus fixture observers. + // privileged (160) source boundaries together, plus fixture observers. .WithCommand("-c", "max_connections=300", "-c", "log_error_verbosity=terse", "-c", "log_min_error_statement=panic", "-c", "log_statement=none", "-c", "log_min_duration_statement=-1", "-c", "log_min_duration_sample=-1", @@ -110,6 +111,7 @@ public sealed class PostgresFixture : IAsyncLifetime .WithEnvironment("LEARNSTACK_PLATFORM_PW", PlatformPassword) .WithEnvironment("LEARNSTACK_OUTBOX_PW", OutboxPassword) .WithEnvironment("LEARNSTACK_IDENTITY_INGRESS_PW", IngressPassword) + .WithEnvironment("LEARNSTACK_IDENTITY_REBIND_PW", RebindPassword) // Keep concurrent publishers in one allocator address family, including identity fixtures. .WithCreateParameterModifier(parameters => ContainerLoopbackPorts.Configure(parameters, "5432/tcp")) .Build(); @@ -128,6 +130,9 @@ public sealed class PostgresFixture : IAsyncLifetime public string IdentityIngressConnectionString => For("learnstack_identity_ingress", IngressPassword); + /// NOBYPASSRLS; only the offline issuer-rebind tool's equivalent (ADR-0104). + public string IdentityRebindConnectionString => For("learnstack_identity_rebind", RebindPassword); + // An owned auxiliary fixture may attach this database to its disposable Docker network. internal string ContainerId => _container.Id; @@ -167,7 +172,7 @@ public async Task InitializeAsync() if (result.ExitCode != 0) { throw new InvalidOperationException( - $"Provisioning the four database roles failed (exit {result.ExitCode}).{Environment.NewLine}" + $"Provisioning the database roles failed (exit {result.ExitCode}).{Environment.NewLine}" + $"{result.Stderr}{Environment.NewLine}{result.Stdout}"); } } @@ -244,12 +249,15 @@ internal Task UnpauseOwnedServerAsync(CancellationToken cancellationToken = defa /// Every caller reverts what it did in a finally: the cluster is shared, /// and an isolation suite running against a bypass role is vacuous. /// - public async Task ExecuteAsSuperuserAsync(string sql) + /// The statement batch. + /// A database other than the container's own, for an object that belongs to one database. + public async Task ExecuteAsSuperuserAsync(string sql, string? database = null) { const int timeoutSeconds = 30; using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)); var connectionString = new NpgsqlConnectionStringBuilder(_container.GetConnectionString()) { + Database = database ?? new NpgsqlConnectionStringBuilder(_container.GetConnectionString()).Database, // This helper retains the container superuser privately. Every call // owns a physical connection, outside any caller's ambient transaction. Pooling = false, diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs index cc012e6bd..1848f726a 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs @@ -38,7 +38,8 @@ public class PublicReadFixture : ConstructionOnlyApiFactory, IAsyncLifetime public string AppConnectionString => _database?.AppConnectionString ?? Postgres.AppConnectionString; public string OutboxConnectionString => _database?.OutboxConnectionString ?? Postgres.OutboxConnectionString; internal string MigrationConnectionString => _database?.MigrationConnectionString ?? Postgres.MigrationConnectionString; - private string PlatformConnectionString => _database?.PlatformConnectionString ?? Postgres.PlatformConnectionString; + internal string PlatformConnectionString => _database?.PlatformConnectionString ?? Postgres.PlatformConnectionString; + internal string IdentityRebindConnectionString => _database?.IdentityRebindConnectionString ?? Postgres.IdentityRebindConnectionString; public PublicReadObservation Observation { get; } = new(); internal static async Task CreateIsolatedAsync(PublicReadFixture parent) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs b/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs new file mode 100644 index 000000000..a5ea46f94 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/RebindProofSupport.cs @@ -0,0 +1,224 @@ +using System.Data.Common; +using System.Net; +using System.Net.Sockets; +using System.Text; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; + +namespace LearnStack.Tests.Integration.Database; + +/// The pieces the controlled-rebind proofs share: the real audit store, admissions and fault injection. +internal static class RebindProofSupport +{ + internal static PlatformAdmission Admit(string? ticket = "CHG-104", DateTimeOffset? issuedAt = null) => + TestPlatformAdmissions.Admission( + PlatformOperations.IdentityAuthorityRebind, ticket, + correlationId: "00-rebind-" + Guid.NewGuid().ToString("N"), issuedAt: issuedAt); + + /// The real store over the real Identity catalogue; rows go through the connection the caller passes. + internal static AsyncServiceScope Store() => + new ServiceCollection() + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new IdentityAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The rebind rows are written on the caller's own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService() + .CreateAsyncScope(); + + internal static string DatabaseOf(string connectionString) => new NpgsqlConnectionStringBuilder(connectionString).Database!; + + internal static string In(string connectionString, string database) => + new NpgsqlConnectionStringBuilder(connectionString) { Database = database }.ConnectionString; +} + +/// A new realm that reports what the test says, or fails the way the test says. +internal sealed class FixedRealm(Func> read) : INewRealmContinuitySource +{ + internal int Reads { get; private set; } + + public Task ReadAsync(string issuer, CancellationToken cancellationToken = default) + { + Reads++; + return read(issuer, cancellationToken); + } + + internal static FixedRealm Reporting(IEnumerable subjects, string? discoveredIssuer = null, + int keys = 2, bool complete = true) => + new((issuer, _) => Task.FromResult(new NewRealmSnapshot(discoveredIssuer ?? issuer, keys, complete, subjects.ToArray()))); + + internal static FixedRealm Failing() => + new((_, _) => throw new NewRealmUnavailableException()); +} + +/// The real store, with seams at the two points a crash or an outage would strike. +internal sealed class FaultingAuditStore(IAuditStore inner) : IAuditStore +{ + internal Func? AfterResult { get; set; } + internal bool FailIntent { get; set; } + internal bool FailResult { get; set; } + + public async Task WriteIdentityRebindIntentAsync(AuditEntryDraft entry, PlatformAdmission admission, + DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) + { + if (FailIntent) throw new AuditWriteFailedException("forced intent failure"); + await inner.WriteIdentityRebindIntentAsync(entry, admission, connection, transaction, cancellationToken); + } + + public async Task WriteIdentityRebindResultAsync(AuditEntryDraft entry, PlatformAdmission admission, + DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) + { + if (FailResult) throw new AuditWriteFailedException("forced result failure"); + await inner.WriteIdentityRebindResultAsync(entry, admission, connection, transaction, cancellationToken); + if (AfterResult is not null) await AfterResult(connection); + } + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePlatformScopeAsync(AuditEntryDraft entry, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => throw new NotSupportedException(); +} + +/// +/// A loopback TCP relay in front of PostgreSQL that lets the first COMMIT that follows the issuer UPDATE reach the +/// server and then drops the answer and the connection, which is exactly the commit whose outcome the client cannot +/// know. +/// +internal sealed class CommitAckDroppingProxy : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly string _host; + private readonly int _port; + private readonly CancellationTokenSource _stop = new(); + private readonly List _pumps = []; + private int _dropped; + + internal CommitAckDroppingProxy(string upstreamConnectionString) + { + var upstream = new NpgsqlConnectionStringBuilder(upstreamConnectionString); + _host = upstream.Host!; + _port = upstream.Port; + _listener.Start(); + _pumps.Add(Task.Run(AcceptAsync)); + } + + internal int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + internal bool Dropped => Volatile.Read(ref _dropped) > 0; + + internal string Through(string connectionString) => new NpgsqlConnectionStringBuilder(connectionString) + { + Host = "127.0.0.1", + Port = Port, + SslMode = SslMode.Disable, + }.ConnectionString; + + private async Task AcceptAsync() + { + try + { + while (!_stop.IsCancellationRequested) + { + var client = await _listener.AcceptTcpClientAsync(_stop.Token); + lock (_pumps) _pumps.Add(Task.Run(() => RelayAsync(client))); + } + } + catch (OperationCanceledException) { } + catch (ObjectDisposedException) { } + } + + private async Task RelayAsync(TcpClient client) + { + using var clientSide = client; + using var upstream = new TcpClient(); + try + { + await upstream.ConnectAsync(_host, _port, _stop.Token); + var armed = false; + var dropAnswer = false; + var toServer = Task.Run(async () => + { + var buffer = new byte[16 * 1024]; + var fromClient = clientSide.GetStream(); + var toUpstream = upstream.GetStream(); + int read; + while ((read = await fromClient.ReadAsync(buffer, _stop.Token)) > 0) + { + var text = Encoding.ASCII.GetString(buffer, 0, read); + armed |= text.Contains("SET issuer", StringComparison.Ordinal); + if (armed && buffer[0] == (byte)'Q' && text.Contains("COMMIT", StringComparison.Ordinal)) + { + // The server will get this COMMIT; whatever it answers is discarded and the connection cut. + Volatile.Write(ref dropAnswer, true); + } + + await toUpstream.WriteAsync(buffer.AsMemory(0, read), _stop.Token); + } + }, _stop.Token); + var toClient = Task.Run(async () => + { + var buffer = new byte[16 * 1024]; + var fromUpstream = upstream.GetStream(); + var toClientStream = clientSide.GetStream(); + int read; + while ((read = await fromUpstream.ReadAsync(buffer, _stop.Token)) > 0) + { + if (Volatile.Read(ref dropAnswer)) + { + Interlocked.Increment(ref _dropped); + clientSide.Close(); + upstream.Close(); + return; + } + + await toClientStream.WriteAsync(buffer.AsMemory(0, read), _stop.Token); + } + }, _stop.Token); + await Task.WhenAny(toServer, toClient); + } + catch (Exception failure) when (failure is IOException or SocketException or OperationCanceledException or ObjectDisposedException or InvalidOperationException) { } + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + Task[] pumps; + lock (_pumps) pumps = [.. _pumps]; + try { await Task.WhenAll(pumps); } catch (Exception failure) when (failure is OperationCanceledException or IOException or ObjectDisposedException) { } + _stop.Dispose(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs index 113c5742f..e2e5f41ee 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs @@ -1338,7 +1338,7 @@ public async Task TheGrantMatrixIsExactlyWhatTheMigrationsWrote() SELECT grantee || ' ' || table_name || ' ' || string_agg(privilege_type, ',' ORDER BY privilege_type) FROM information_schema.table_privileges WHERE table_schema = 'public' - AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'PUBLIC') + AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'learnstack_identity_rebind', 'PUBLIC') GROUP BY grantee, table_name """); @@ -1357,7 +1357,9 @@ AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admi "learnstack_app identity_provider_event_targets SELECT", "learnstack_identity_ingress identity_provider_event_receipts SELECT", "learnstack_identity_ingress identity_provider_event_scan INSERT,SELECT", - "learnstack_identity_ingress identity_provider_event_problems INSERT,SELECT"]), + "learnstack_identity_ingress identity_provider_event_problems INSERT,SELECT", + "learnstack_identity_rebind identity_authority SELECT", + "learnstack_identity_rebind audit_log INSERT"]), "every line is one line of the migration chains' grant matrices, and " + "learnstack_outbox_admin holds only declared outbox/delivery scheduling columns " + "and terminal audit INSERT"); @@ -1396,7 +1398,8 @@ AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admi // that lets anything enter EnterPlatformAdminScope at all. "learnstack_platform platform_killswitches DELETE,INSERT,SELECT,UPDATE", "learnstack_platform platform_host_to_tenant DELETE,INSERT,SELECT,UPDATE", - "learnstack_platform outbox_messages DELETE,SELECT", + // ADR-0103: the purge keeps its DELETE; the table-wide SELECT is gone, and the inspection reads named columns. + "learnstack_platform outbox_messages DELETE", "learnstack_platform idempotency_keys DELETE,SELECT", "learnstack_app tenant_content_types DELETE,INSERT,SELECT,UPDATE", "learnstack_app tenant_level_taxonomies DELETE,INSERT,SELECT,UPDATE", diff --git a/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs index d4707ef6c..0bb4e88c0 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/UnitOfWorkTests.cs @@ -1261,13 +1261,7 @@ INSERT INTO outbox_messages } finally { - await using var platform = await PostgresFixture.OpenAsync( - _schema.Postgres.PlatformConnectionString); - await using var cleanup = new NpgsqlCommand( - "DELETE FROM outbox_messages WHERE correlation_id = @correlation", - (NpgsqlConnection)platform); - cleanup.Parameters.AddWithValue("correlation", correlation); - await cleanup.ExecuteNonQueryAsync(); + await DeleteOutboxAsync(correlation); } } @@ -1632,21 +1626,21 @@ INSERT INTO outbox_messages """, ("tenant", SchemaFixture.TenantA), ("correlation", correlation)); + // The platform role no longer reads correlation_id (ADR-0103 limits it to inspection metadata), and the dispatcher + // role cannot delete, so a test's own rows are removed by the container's superuser and counted by the dispatcher + // role, which reads the table across tenants. private async Task DeleteOutboxAsync(string correlation) { - await using var platform = await PostgresFixture.OpenAsync( - _schema.Postgres.PlatformConnectionString); - await using var cleanup = new NpgsqlCommand( - "DELETE FROM outbox_messages WHERE correlation_id = @correlation", - (NpgsqlConnection)platform); - cleanup.Parameters.AddWithValue("correlation", correlation); - await cleanup.ExecuteNonQueryAsync(); + System.Text.RegularExpressions.Regex.IsMatch(correlation, "^[0-9A-Za-z-]+$").Should().BeTrue( + "the cleanup statement embeds only a generated identifier"); + await _schema.Postgres.ExecuteAsSuperuserAsync( + $"DELETE FROM outbox_messages WHERE correlation_id = '{correlation}'"); } private async Task CountOutboxAsync(string correlation) { await using var platform = await PostgresFixture.OpenAsync( - _schema.Postgres.PlatformConnectionString); + _schema.Postgres.OutboxConnectionString); await using var command = new NpgsqlCommand( "SELECT count(*) FROM outbox_messages WHERE correlation_id = @correlation", (NpgsqlConnection)platform); diff --git a/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs new file mode 100644 index 000000000..2c2d10979 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/FakeKeycloakRealm.cs @@ -0,0 +1,225 @@ +using System.Net; +using System.Text.Json; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tools.IdentityAuthorityRebind; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Tests.Integration; + +/// A loopback realm that answers like Keycloak's discovery, key set, token and administration endpoints. +internal sealed class FakeKeycloakRealm : IAsyncDisposable +{ + internal const string ClientId = "rebind-reader"; + internal const string ClientSecret = "reader-secret-value"; + + private readonly WebApplication _app; + private readonly HttpClient _client; + private string? _failure; + private int _pages; + private int _firstPageRequests; + private readonly TaskCompletionSource _discoveryHung = new(TaskCreationOptions.RunContinuationsAsynchronously); + private string _prefix = string.Empty; + + private FakeKeycloakRealm(WebApplication app, List users) + { + _app = app; + Users = users; + _client = KeycloakRealmContinuitySource.CreateClient(); + } + + internal List Users { get; } + + internal string Issuer { get; private set; } = ""; + + internal string? DiscoveryIssuer { get; set; } + + /// + /// A reachable origin other than the issuer's: when set, the discovery document names its key set and token endpoint + /// there, so a reader that followed them would send the credential to a host that is up. + /// + internal string? ForeignOrigin { get; set; } + + internal int? ReportedCount { get; set; } + + internal int? CountAfterRead { get; set; } + + internal int Pages => Volatile.Read(ref _pages); + + /// Completes when a discovery request has arrived at a realm set to never answer it. + internal Task DiscoveryHung => _discoveryHung.Task; + + internal List> TokenRequests { get; } = []; + + internal List AdminAuthorization { get; } = []; + + internal static Task StartAsync(int users, string prefix = "") => + StartAsync(Enumerable.Range(0, users).Select(_ => Guid.NewGuid().ToString("D")), prefix); + + /// Starts the realm; puts it behind a path such as /auth, as older Keycloaks were. + internal static async Task StartAsync(IEnumerable users, string prefix = "") + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseKestrel(options => options.Listen(IPAddress.Loopback, 0)); + var app = builder.Build(); + var realm = new FakeKeycloakRealm(app, users.ToList()) { _prefix = prefix }; + realm.Map(app); + await app.StartAsync(); + var origin = app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); + realm.Issuer = origin + prefix + "/realms/learnstack"; + return realm; + } + + internal void Fail(string failure) => _failure = failure; + + internal Task ReadAsync() => + new KeycloakRealmContinuitySource(_client, ClientId, ClientSecret).ReadAsync(Issuer); + + private void Map(WebApplication app) + { + app.MapGet(_prefix + "/realms/learnstack/.well-known/openid-configuration", context => + { + if (_failure == "discovery-redirect") + { + context.Response.StatusCode = StatusCodes.Status302Found; + context.Response.Headers.Location = "https://elsewhere.example.test/"; + return Task.CompletedTask; + } + + if (_failure == "discovery-hang") + { + // The realm never answers: the request ends only when its caller gives up or goes away. + _discoveryHung.TrySetResult(); + return Task.Delay(System.Threading.Timeout.InfiniteTimeSpan, context.RequestAborted); + } + + var foreign = ForeignOrigin ?? "http://127.0.0.1:1"; + var jwks = _failure == "jwks-other-origin" ? foreign + "/realms/learnstack/keys" : Issuer + "/keys"; + var token = _failure == "token-other-origin" + ? foreign + "/realms/learnstack/protocol/openid-connect/token" + : Issuer + "/protocol/openid-connect/token"; + context.Response.ContentType = "application/json"; + return context.Response.WriteAsync(JsonSerializer.Serialize(new + { + issuer = DiscoveryIssuer ?? Issuer, + jwks_uri = jwks, + token_endpoint = token, + })); + }); + app.MapGet(_prefix + "/realms/learnstack/keys", context => + { + context.Response.ContentType = "application/json"; + return context.Response.WriteAsync( + """{"keys":[{"kty":"RSA","kid":"a","use":"sig"},{"kty":"RSA","kid":"b"},{"kty":"RSA","kid":"c","use":"enc"}]}"""); + }); + app.MapPost(_prefix + "/realms/learnstack/protocol/openid-connect/token", async context => + { + var form = await context.Request.ReadFormAsync(); + TokenRequests.Add(form.ToDictionary(pair => pair.Key, pair => pair.Value.ToString())); + if (_failure == "token-denied") + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return; + } + + context.Response.ContentType = "application/json"; + // The first token is the one an enumeration outlives when "token-expires" is set; the second is accepted. + var issued = TokenRequests.Count; + await context.Response.WriteAsync(_failure == "oversized-token-answer" + ? "{\"access_token\":\"" + new string('x', 300 * 1024) + "\"}" + : "{\"access_token\":\"" + (issued >= 2 && _failure == "token-expires" ? "realm-token-2" : "realm-token") + "\"}"); + }); + app.MapGet(_prefix + "/admin/realms/learnstack/users/count", context => + { + AdminAuthorization.Add(context.Request.Headers.Authorization); + if (Unauthorized(context)) + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } + + if (_failure == "admin-denied") + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + return Task.CompletedTask; + } + + if (_failure == "count-not-a-number") + { + return context.Response.WriteAsync("\"many\""); + } + + var count = Pages > 0 && CountAfterRead is { } later ? later : ReportedCount ?? Users.Count; + return context.Response.WriteAsync(count.ToString(System.Globalization.CultureInfo.InvariantCulture)); + }); + app.MapGet(_prefix + "/admin/realms/learnstack/users", context => + { + AdminAuthorization.Add(context.Request.Headers.Authorization); + if (Unauthorized(context)) + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } + + Interlocked.Increment(ref _pages); + if (_failure == "users-redirect") + { + context.Response.StatusCode = StatusCodes.Status302Found; + context.Response.Headers.Location = "https://elsewhere.example.test/"; + return Task.CompletedTask; + } + + context.Response.ContentType = "application/json"; + if (_failure == "users-not-an-array") + { + return context.Response.WriteAsync("{}"); + } + + var first = int.Parse(context.Request.Query["first"]!, System.Globalization.CultureInfo.InvariantCulture); + var max = int.Parse(context.Request.Query["max"]!, System.Globalization.CultureInfo.InvariantCulture); + if (first == 0) + { + Interlocked.Increment(ref _firstPageRequests); + } + + var users = Users.ToList(); + if (_failure == "duplicate-user" && users.Count > 1) + { + // A user is served twice and another never is, with the count unchanged. + users[^1] = users[0]; + } + + if (_failure == "second-pass-differs" && Volatile.Read(ref _firstPageRequests) >= 2 && users.Count > 0) + { + // A different user at the start of the second pass: the realm changed between the two reads. + users[0] = Guid.NewGuid().ToString("D"); + } + + var page = users.Skip(first).Take(max).Select(id => _failure == "user-without-id" + ? (object)new { username = id } + : new { id, username = "user-" + id }); + return context.Response.WriteAsync(JsonSerializer.Serialize(page)); + }); + } + + // "token-expires": the first token stops being accepted once any admin call has been made with it, as a short-lived + // one does mid-enumeration; "always-unauthorized": no token is ever accepted. + private bool Unauthorized(HttpContext context) + { + var header = context.Request.Headers.Authorization.ToString(); + return _failure == "always-unauthorized" + || (_failure == "token-expires" && header == "Bearer realm-token" && AdminAuthorization.Count > 2); + } + + public async ValueTask DisposeAsync() + { + _client.Dispose(); + await _app.DisposeAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs new file mode 100644 index 000000000..1e4f8a0ac --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/KeycloakRealmContinuitySourceTests.cs @@ -0,0 +1,199 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tools.IdentityAuthorityRebind; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The tool's reader of the new realm (ADR-0104 § 4, § 6) against a loopback realm that behaves like Keycloak's +/// administration API: bounded, same-origin, paged, and complete or refused. +/// +/// +/// A real Keycloak answers the same questions in ; here the +/// failure modes a real one cannot be made to produce are driven on purpose. +/// +public sealed class KeycloakRealmContinuitySourceTests +{ + private const string ClientId = FakeKeycloakRealm.ClientId; + private const string ClientSecret = FakeKeycloakRealm.ClientSecret; + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(99)] + [InlineData(100)] + [InlineData(101)] + [InlineData(250)] + public async Task Every_User_Of_Every_Page_Is_Reported_And_The_Snapshot_Is_Complete(int users) + { + await using var realm = await FakeKeycloakRealm.StartAsync(users); + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeTrue(); + snapshot.DiscoveredIssuer.Should().Be(realm.Issuer); + snapshot.SigningKeyCount.Should().Be(2, "only signature keys count, an encryption key does not"); + snapshot.Subjects.Should().BeEquivalentTo(realm.Users); + realm.Pages.Should().Be(2 * (users / KeycloakRealmContinuitySource.PageSize + 1), + "two full passes, each ended by a page shorter than the page size, an exact multiple needing one empty page"); + } + + [Fact] + public async Task The_Realm_Credential_Is_Sent_Only_As_A_Client_Credentials_Grant_And_The_Token_Only_As_A_Bearer() + { + await using var realm = await FakeKeycloakRealm.StartAsync(3); + + await realm.ReadAsync(); + + realm.TokenRequests.Should().ContainSingle().Which.Should().BeEquivalentTo(new Dictionary + { + ["grant_type"] = "client_credentials", + ["client_id"] = ClientId, + ["client_secret"] = ClientSecret, + }); + realm.AdminAuthorization.Should().OnlyContain(header => header == "Bearer realm-token"); + } + + [Fact] + public async Task A_Realm_That_Changes_While_It_Is_Read_Is_Not_Complete() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.CountAfterRead = 6; + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeFalse("the count before and after the pages differ"); + } + + [Fact] + public async Task A_User_Served_Twice_And_Another_Never_Is_Not_Complete_Although_The_Count_Matches() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.Fail("duplicate-user"); + + (await realm.ReadAsync()).Complete.Should().BeFalse(); + } + + [Fact] + public async Task A_Realm_That_Reports_Another_Set_On_The_Second_Pass_Is_Not_Complete() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.Fail("second-pass-differs"); + + (await realm.ReadAsync()).Complete.Should().BeFalse("a user deleted and another created between the passes keeps the count"); + } + + [Fact] + public async Task A_Token_That_Expires_During_The_Enumeration_Is_Obtained_Again_Once_And_The_Read_Completes() + { + await using var realm = await FakeKeycloakRealm.StartAsync(250); + realm.Fail("token-expires"); + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeTrue(); + realm.TokenRequests.Should().HaveCount(2, "one more token, not one per request"); + realm.AdminAuthorization.Should().Contain("Bearer realm-token-2"); + } + + [Fact] + public async Task A_Credential_That_Is_Refused_Even_With_A_New_Token_Is_A_Refusal_After_One_Retry() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.Fail("always-unauthorized"); + + var act = async () => await realm.ReadAsync(); + + await act.Should().ThrowAsync(); + realm.TokenRequests.Should().HaveCount(2); + } + + [Fact] + public async Task A_Path_Prefixed_Issuer_Reads_Its_Own_Administration_Path() + { + await using var realm = await FakeKeycloakRealm.StartAsync(3, prefix: "/auth"); + + var snapshot = await realm.ReadAsync(); + + snapshot.Complete.Should().BeTrue(); + snapshot.Subjects.Should().BeEquivalentTo(realm.Users); + } + + [Fact] + public async Task A_Reported_Count_That_The_Pages_Do_Not_Add_Up_To_Is_Not_Complete() + { + await using var realm = await FakeKeycloakRealm.StartAsync(5); + realm.ReportedCount = 7; + + (await realm.ReadAsync()).Complete.Should().BeFalse(); + } + + [Fact] + public async Task A_Discovery_Issuer_That_Differs_Is_Reported_As_It_Is_And_No_Credential_Is_Sent_To_That_Realm() + { + await using var realm = await FakeKeycloakRealm.StartAsync(1); + realm.DiscoveryIssuer = "https://elsewhere.example.test/realms/learnstack"; + + var snapshot = await realm.ReadAsync(); + + snapshot.DiscoveredIssuer.Should().Be("https://elsewhere.example.test/realms/learnstack"); + realm.TokenRequests.Should().BeEmpty("a realm that is not the target never receives the client secret"); + realm.Pages.Should().Be(0); + } + + [Theory] + [InlineData("jwks-other-origin", NewRealmStep.Discovery)] + [InlineData("token-other-origin", NewRealmStep.Discovery)] + [InlineData("discovery-redirect", NewRealmStep.Discovery)] + [InlineData("token-denied", NewRealmStep.Token)] + [InlineData("oversized-token-answer", NewRealmStep.Token)] + [InlineData("admin-denied", NewRealmStep.UserCount)] + [InlineData("count-not-a-number", NewRealmStep.UserCount)] + [InlineData("users-redirect", NewRealmStep.UserList)] + [InlineData("users-not-an-array", NewRealmStep.UserList)] + [InlineData("user-without-id", NewRealmStep.UserList)] + public async Task Any_Transport_Or_Shape_Failure_Is_One_Fixed_Refusal_That_Names_Only_The_Step(string failure, NewRealmStep step) + { + await using var realm = await FakeKeycloakRealm.StartAsync(3); + realm.Fail(failure); + + var act = async () => await realm.ReadAsync(); + + var thrown = (await act.Should().ThrowAsync()).Which; + thrown.Step.Should().Be(step, "the refusal says where the read stopped, which is all an operator needs to look"); + thrown.Message.Should().Be("The new realm could not be read completely."); + thrown.Message.Should().NotContain(ClientSecret).And.NotContain("127.0.0.1").And.NotContain("realm-token"); + thrown.InnerException.Should().BeNull("no transport exception is carried out"); + } + + [Theory] + [InlineData("token-other-origin")] + [InlineData("jwks-other-origin")] + public async Task A_Reachable_Foreign_Origin_Named_By_Discovery_Is_Never_Called_And_Never_Gets_The_Credential(string failure) + { + await using var foreign = await FakeKeycloakRealm.StartAsync(3); + await using var realm = await FakeKeycloakRealm.StartAsync(3); + realm.ForeignOrigin = foreign.Issuer[..foreign.Issuer.IndexOf("/realms/", StringComparison.Ordinal)]; + realm.Fail(failure); + + var act = async () => await realm.ReadAsync(); + + await act.Should().ThrowAsync(); + foreign.TokenRequests.Should().BeEmpty("the client secret never leaves the issuer's own origin"); + foreign.AdminAuthorization.Should().BeEmpty(); + } + + [Fact] + public void A_Credential_Replacing_The_Certificate_Check_Is_Refused() + { + var handler = new SocketsHttpHandler(); +#pragma warning disable CA5359 // The case proves that a replaced certificate check is refused; it is never used. + handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; +#pragma warning restore CA5359 + + var act = () => KeycloakRealmContinuitySource.CreateClient(handler); + + act.Should().Throw(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs new file mode 100644 index 000000000..fc743154a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs @@ -0,0 +1,223 @@ +using System.Data.Common; +using FluentAssertions; +using LearnStack.Modules.Tenancy.Infrastructure; +using LearnStack.SharedKernel.Caching; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The order of the killswitch writer's steps and the failure branches around its commit, decided +/// against a scripted scope so a commit that faults can be produced exactly (ADR-0101 § 13). +/// +/// +/// No Docker. The real-database behaviour (row lock, both audit rows, rollback) is asserted in +/// ; what a stub can show and a database cannot is the writer's +/// reaction to a commit whose outcome is unknown. +/// +public sealed class KillswitchToggleOrderingTests +{ + private static readonly KillswitchKey Key = KillswitchKeys.AnalyticsIngestEnabled; + + [Fact] + public async Task A_Commit_Whose_Outcome_Is_Unknown_Still_Drops_The_Cache_And_Reaches_The_Caller() + { + // The flip may have landed. A stale overlay entry must not outlive a commit that might have + // happened, and the caller must see the failure rather than an Applied it cannot trust. + var handle = new ScriptedHandle { CommitFailure = new TimeoutException("the commit reply never came") }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync(); + cache.Removed.Should().Be(1); + handle.Disposed.Should().BeTrue("the scope is released whatever the commit did"); + } + + [Fact] + public async Task A_Failure_Before_The_Commit_Leaves_The_Cache_Alone() + { + var handle = new ScriptedHandle { ResultFailure = new LearnStack.SharedKernel.Audit.AuditWriteFailedException("no row") }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync(); + cache.Removed.Should().Be(0, "nothing was committed, so nothing is stale"); + handle.CommitCalls.Should().Be(0); + } + + [Fact] + public async Task A_Row_That_Is_Not_There_To_Lock_Abandons_The_Toggle_Without_A_Result_Row() + { + var handle = new ScriptedHandle { LockedRows = 0 }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync().WithMessage("*not there to lock*"); + handle.Steps.Should().NotContain("result").And.NotContain("commit"); + cache.Removed.Should().Be(0); + } + + [Fact] + public async Task An_Update_That_Changes_No_Row_Never_Gets_A_Result_Row_Describing_It() + { + var handle = new ScriptedHandle { UpdatedRows = 0 }; + var cache = new CountingCache(); + + var act = async () => await Toggle(handle, cache).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + await act.Should().ThrowAsync().WithMessage("*changed no row*"); + handle.Steps.Should().NotContain("result").And.NotContain("commit"); + cache.Removed.Should().Be(0); + } + + [Fact] + public async Task The_Commit_Is_Not_Cancellable_By_The_Caller() + { + // Past the point where the caller's abort could matter, a cancelled commit would leave its + // outcome unknown, which is the state this order exists to avoid. + var handle = new ScriptedHandle(); + using var abort = new CancellationTokenSource(); + await abort.CancelAsync(); + + await Toggle(handle, new CountingCache()).ToggleAsync(TestPlatformAdmissions.Admission(), Key, false, abort.Token); + + handle.CommitToken.CanBeCanceled.Should().BeFalse(); + } + + [Fact] + public async Task A_Cache_That_Cannot_Remove_Is_Logged_And_Does_Not_Fail_The_Applied_Toggle() + { + var handle = new ScriptedHandle(); + var logger = new CapturingLogger(); + var cache = new CountingCache { Failure = new TimeoutException("cache down") }; + var toggle = new KillswitchToggle(new ScriptedScope(handle), cache, new SystemClock(), logger); + + var result = await toggle.ToggleAsync(TestPlatformAdmissions.Admission(), Key, false); + + result.Outcome.Should().Be(KillswitchToggleOutcome.Applied, "the flip committed; the cache is an optimisation"); + logger.EventIds.Should().Contain(7104, "a store that cannot remove is a store that serves stale"); + } + + [Fact] + public async Task The_Writer_Creates_Locks_Reads_Updates_Records_And_Only_Then_Commits_In_That_Order() + { + var handle = new ScriptedHandle(); + + await Toggle(handle, new CountingCache()).ToggleAsync(TestPlatformAdmissions.Admission(ticket: "INC-3"), Key, false); + + handle.Steps.Should().Equal("exec:INSERT", "query:SELECT", "exec:UPDATE", "result", "commit"); + handle.Statements[1].Should().EndWith("FOR UPDATE", "the read takes the row lock the update then holds"); + } + + private static KillswitchToggle Toggle(ScriptedHandle handle, CountingCache cache) => + new(new ScriptedScope(handle), cache, new SystemClock(), NullLogger.Instance); + + private sealed class ScriptedScope(ScriptedHandle handle) : IPlatformAdminScope + { + public Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + string? callerMember = null, string? callerFile = null, int callerLine = 0) => + Task.FromResult(handle); + } + + private sealed class ScriptedHandle : IPlatformAdminScopeHandle + { + public Exception? CommitFailure { get; init; } + public Exception? ResultFailure { get; init; } + public int LockedRows { get; init; } = 1; + public int UpdatedRows { get; init; } = 1; + public List Steps { get; } = []; + public List Statements { get; } = []; + public int CommitCalls { get; private set; } + public CancellationToken CommitToken { get; private set; } + public bool Disposed { get; private set; } + + public Task ExecuteAsync( + string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) + { + Steps.Add("exec:" + sql.Split(' ')[0]); + Statements.Add(sql); + return Task.FromResult(sql.StartsWith("UPDATE", StringComparison.Ordinal) ? UpdatedRows : 1); + } + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) + { + Steps.Add("query:" + sql.Split(' ')[0]); + Statements.Add(sql); + return Task.FromResult>( + (IReadOnlyList)(object)Enumerable.Repeat(true, LockedRows).ToList()); + } + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) + { + Steps.Add("intent"); + return Task.CompletedTask; + } + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) + { + Steps.Add("result"); + return ResultFailure is null ? Task.CompletedTask : Task.FromException(ResultFailure); + } + + public Task CommitAsync(CancellationToken cancellationToken = default) + { + Steps.Add("commit"); + CommitCalls++; + CommitToken = cancellationToken; + return CommitFailure is null ? Task.CompletedTask : Task.FromException(CommitFailure); + } + + public ValueTask DisposeAsync() + { + Disposed = true; + return ValueTask.CompletedTask; + } + } + + private sealed class CountingCache : ICacheService + { + public int Removed { get; private set; } + public Exception? Failure { get; init; } + + public Task RemoveAsync(string key, CancellationToken cancellationToken = default) + { + Removed++; + return Failure is null ? Task.CompletedTask : Task.FromException(Failure); + } + + public Task GetAsync(string key, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task GetOrSetAsync( + string key, Func> factory, CacheOptions? options = null, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task SetAsync(string key, T value, CacheOptions? options = null, CancellationToken cancellationToken = default) => + throw new NotSupportedException(); + } + + private sealed class CapturingLogger : ILogger + { + public List EventIds { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + EventIds.Add(eventId.Id); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj index 3d19ac15b..dd58d635f 100644 --- a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj +++ b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj @@ -19,6 +19,7 @@ to be asserted against the real schema rather than taken on trust. --> + + diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs new file mode 100644 index 000000000..a3a753d6c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -0,0 +1,1616 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The operator surface through the production Program and the stock bearer handler, with a +/// controlled issuer signing real RS256 tokens (ADR-0101). +/// +/// +/// +/// Protocol refusals are isolated with controlled signed tokens, as the tenant suite does; the +/// real-realm proof is a separate case against pinned Keycloak. The killswitch writer is a +/// recording double here, so these cases decide admission and mapping only and never reach a +/// database; the writer's own transaction semantics are asserted against real PostgreSQL. +/// +/// +/// What a refusal must show is the same in every case: the double was never called, so no +/// privileged connection was acquired, and the answer carries no detail a probing caller could use. +/// +/// +[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", + Justification = "xUnit disposes the fields through IAsyncLifetime.DisposeAsync.")] +public sealed class PlatformOperatorHttpTests : IAsyncLifetime +{ + private const string Path = "/api/platform/v1/killswitches/killswitch.classroom.recording"; + private const string Subject = "operator-sub-1"; + + private TenantAuthenticationIssuer _tenant = null!; + private TenantAuthenticationIssuer _operator = null!; + private PlatformOperatorApiFactory _factory = null!; + private RecordingToggle _toggle = null!; + private RecordingRecovery _recovery = null!; + private RecordingInspection _inspection = null!; + private RecordingBrokers _brokers = null!; + private CapturingLogs _logs = null!; + private HttpClient _client = null!; + + public async Task InitializeAsync() + { + _tenant = await TenantAuthenticationIssuer.StartAsync(); + _operator = await TenantAuthenticationIssuer.StartAsync(); + _toggle = new RecordingToggle(); + _recovery = new RecordingRecovery(); + _inspection = new RecordingInspection(); + _brokers = new RecordingBrokers(); + _logs = new CapturingLogs(); + _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => + { + // The host's logging is Serilog, which does not feed registered providers: the routes ask for the factory. + registrations.AddSingleton(_ => LoggerFactory.Create(builder => builder.AddProvider(_logs))); + registrations.AddSingleton(_recovery); + registrations.AddScoped(_ => _inspection); + registrations.AddScoped(_ => _brokers); + }); + _client = _factory.CreateClient(); + } + + public async Task DisposeAsync() + { + _client.Dispose(); + await _factory.DisposeAsync(); + await _operator.DisposeAsync(); + await _tenant.DisposeAsync(); + } + + [Fact] + public async Task A_Valid_Operator_With_The_Grant_Toggles_And_The_Admission_Carries_Them() + { + var response = await Put(Valid(), """{"enabled":false,"ticket":"INC-42"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + var body = await response.Content.ReadFromJsonAsync(); + body.GetProperty("key").GetString().Should().Be("killswitch.classroom.recording"); + body.GetProperty("after").GetBoolean().Should().BeFalse(); + _toggle.Calls.Should().ContainSingle(); + var admission = _toggle.Calls[0]; + admission.Operator.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_operator.Issuer, Subject)); + admission.Operator.Issuer.Should().Be(_operator.Issuer); + admission.Operator.Acr.Should().Be("mfa"); + admission.Ticket.Should().Be("INC-42"); + admission.Operation.Should().BeSameAs(PlatformOperations.KillswitchToggle); + admission.Operator.CorrelationId.Should().NotBeNullOrWhiteSpace( + "a result row is never recorded without a handle the operator can quote"); + body.GetProperty("correlationId").GetString().Should().Be(admission.Operator.CorrelationId); + admission.IssuedAt.Should().BeCloseTo(DateTimeOffset.UtcNow, TimeSpan.FromSeconds(30)); + } + + [Fact] + public async Task The_Bearer_Prefix_And_The_Route_Prefix_Are_Matched_Without_Regard_To_Case() + { + // Routing is case-insensitive, so the scheme's own prefix checks must be too: a request the + // router sends to the operator endpoint is a request the operator scheme authenticates. + using var request = new HttpRequestMessage(HttpMethod.Put, Path.ToUpperInvariant().Replace("KILLSWITCH.CLASSROOM.RECORDING", "killswitch.classroom.recording")) + { + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + request.Headers.TryAddWithoutValidation("Authorization", "bearer " + Valid()); + + var response = await _client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + _toggle.Calls.Should().ContainSingle(); + } + + [Fact] + public async Task No_Credential_Is_Refused_Without_Detail() + { + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Content = JsonContent.Create(new { enabled = false }), + }; + + var response = await _client.SendAsync(request); + + await AssertUnauthorized(response); + } + + [Theory] + [InlineData("audience", "token_audience")] + [InlineData("issuer", "token_issuer")] + [InlineData("typ", "token_type")] + [InlineData("alg", "token_signature")] // the stock handler reports a disallowed algorithm as a signature failure + [InlineData("signature", "token_signature")] + [InlineData("azp", "profile_azp")] + [InlineData("acr", "profile_acr")] + [InlineData("acr-missing", "profile_acr")] + [InlineData("auth-time-old", "profile_auth_age")] + [InlineData("auth-time-missing", "profile_auth_time")] + [InlineData("auth-time-future", "profile_auth_age")] + [InlineData("lifetime", "profile_lifetime")] + [InlineData("expired", "token_expired")] + [InlineData("subject-missing", "profile_subject")] + public async Task A_Wrongly_Profiled_Token_Is_Refused_Counted_Under_Its_Cause_And_Nothing_Is_Called( + string defect, string expectedCause) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var token = defect switch + { + "audience" => Sign(("aud", "learnstack-api")), + "issuer" => Sign(("iss", _tenant.Issuer)), + "typ" => _operator.Token(Payload([]), header: Header("RS256", "at+jwt")), + "alg" => SignWithSha384(), + "signature" => Sign()[..^4] + "AAAA", + "azp" => Sign(("azp", "learnstack-web")), + "acr" => Sign(("acr", "0")), + "acr-missing" => SignWithout("acr"), + "auth-time-old" => Sign(("auth_time", now - 3600)), + "auth-time-missing" => SignWithout("auth_time"), + "auth-time-future" => Sign(("auth_time", now + 600)), + "lifetime" => Sign(("iat", now - 5), ("exp", now + 3600)), + "expired" => Sign(("iat", now - 7200), ("exp", now - 3600)), + _ => SignWithout("sub"), + }; + using var counted = Counted(); + + var response = await Put(token, """{"enabled":false}"""); + + await AssertUnauthorized(response); + _toggle.Calls.Should().BeEmpty("a refused credential reaches no operator service"); + counted.Causes.Should().Contain(expectedCause, "the cause is a closed label an operator can alert on"); + } + + [Fact] + public async Task A_Missing_Credential_Is_Counted_As_Missing() + { + using var counted = Counted(); + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + + await AssertUnauthorized(await _client.SendAsync(request)); + + counted.Causes.Should().Contain("token_missing"); + } + + [Fact] + public async Task Keys_That_A_Failed_Refresh_Could_Not_Renew_Stop_Being_Trusted_After_Fifteen_Minutes() + { + // The stock manager keeps serving the keys it last fetched when a refresh fails. Right for a blip, + // wrong for a key the issuer has since withdrawn while an attacker holds the network down. So + // once a later fetch has failed and the last success is older than the window, operator tokens + // are refused, whatever key signed them. + var clock = new MovableClock(DateTimeOffset.UtcNow); + var toggle = new RecordingToggle(); + await using var factory = new PlatformOperatorApiFactory( + _tenant, _operator, toggle, grantSubject: Subject, + services: registrations => registrations.AddSingleton(new PlatformOperatorMetadataHealth(clock))); + using var client = factory.CreateClient(); + using var counted = Counted(); + + // 1. A good token loads the keys. + (await Send(client, Valid())).StatusCode.Should().Be(HttpStatusCode.OK); + + // 2. A token signed with a key the cache has never seen makes the scheme ask the issuer for a + // refresh, and the issuer is down. + _operator.DiscoveryStatusCode = StatusCodes.Status503ServiceUnavailable; + try + { + var unknownKey = await Send(client, _operator.Token(Payload([]), key: _operator.NewKey())); + unknownKey.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await unknownKey.Content.ReadAsStringAsync()); + // The refresh the unknown key asked for runs in the background, after the response. + for (var attempt = 0; attempt < 100 && counted.MetadataFailures == 0; attempt++) + { + await Task.Delay(50); + } + + counted.MetadataFailures.Should().BeGreaterThan(0); + + // 3. Within the window the keys already held still serve. + clock.Advance(TimeSpan.FromMinutes(5)); + (await Send(client, Valid())).StatusCode.Should().Be(HttpStatusCode.OK, "a blip is bridged"); + + // 4. Past the window they do not, and the cause says why. + clock.Advance(PlatformOperatorMetadataHealth.MaximumStaleness); + await AssertUnauthorized(await Send(client, Valid())); + counted.Causes.Should().Contain("metadata_stale"); + } + finally + { + _operator.DiscoveryStatusCode = StatusCodes.Status200OK; + } + } + + [Fact] + public async Task An_Issuer_That_Is_Down_At_Start_Is_Asked_Once_Not_Once_Per_Waiting_Request() + { + // Each caller waiting for the first configuration would otherwise fetch it in turn, holding an + // unauthenticated request for the whole transport timeout apiece. A failed fetch makes the next + // ones fail at once for a short while. + var down = await TenantAuthenticationIssuer.StartAsync(); + down.DiscoveryStatusCode = StatusCodes.Status503ServiceUnavailable; + try + { + await using var factory = new PlatformOperatorApiFactory(_tenant, down, new RecordingToggle(), grantSubject: Subject); + using var client = factory.CreateClient(); + var token = down.Token(down.Payload( + ("aud", "learnstack-platform"), ("azp", "learnstack-operator"), ("acr", "mfa"), + ("auth_time", DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 30), ("sub", Subject))); + + var responses = await Task.WhenAll(Enumerable.Range(0, 12).Select(_ => Send(client, token))); + + responses.Should().OnlyContain(response => response.StatusCode == HttpStatusCode.Unauthorized); + down.MetadataRequests.Should().BeLessThanOrEqualTo(2, + "twelve waiting requests are answered from one failed fetch, not twelve"); + } + finally + { + await down.DisposeAsync(); + } + } + + [Theory] + [InlineData("redirect")] + [InlineData("oversized-keys")] + [InlineData("foreign-jwks-uri")] + public async Task Unsafe_Issuer_Metadata_Refuses_Every_Operator_And_Is_Counted(string fault) + { + // The scheme's own transport follows no redirect, reads at most 256 KB and fetches nothing + // outside the issuer's origin, so a hostile or broken metadata endpoint cannot choose the + // keys the operator scheme trusts. An unreachable issuer refuses everyone (no last known + // good), which is the safe side of an outage. + var misbehaving = await TenantAuthenticationIssuer.StartAsync(); + var foreign = await TenantAuthenticationIssuer.StartAsync(); + try + { + TenantAuthenticationSigningKey? signer = null; + switch (fault) + { + case "redirect": + misbehaving.DiscoveryStatusCode = StatusCodes.Status302Found; + misbehaving.DiscoveryRedirect = misbehaving.CanaryAddress; + break; + case "oversized-keys": + misbehaving.JwksResponse = new string(' ', 300 * 1024); + break; + default: + // A second, live origin that would happily serve a key set and so make a token + // signed by its key valid, if the discovery document's address were followed. + misbehaving.DiscoveryResponse = misbehaving.DiscoveryDocument.Replace( + misbehaving.Issuer + "/keys", foreign.Issuer + "/keys", StringComparison.Ordinal); + signer = foreign.CurrentKey; + break; + } + + var toggle = new RecordingToggle(); + await using var factory = new PlatformOperatorApiFactory(_tenant, misbehaving, toggle, grantSubject: Subject); + using var client = factory.CreateClient(); + using var counted = Counted(); + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + misbehaving.Token(misbehaving.Payload( + ("aud", "learnstack-platform"), ("azp", "learnstack-operator"), ("acr", "mfa"), + ("auth_time", DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 30), ("sub", Subject)), key: signer) } }, + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + + var response = await client.SendAsync(request); + + await AssertUnauthorized(response); + toggle.Calls.Should().BeEmpty(); + counted.MetadataFailures.Should().BeGreaterThan(0, + "the transport refusal is counted where it happens; the request itself finds no key"); + misbehaving.CanaryRequests.Should().Be(0, "no redirect target is ever dereferenced"); + foreign.JwksRequests.Should().Be(0, "a key set at another origin is never fetched"); + } + finally + { + await foreign.DisposeAsync(); + await misbehaving.DisposeAsync(); + } + } + + [Fact] + public async Task A_Tenant_Realm_Token_Is_Refused_On_The_Operator_Surface() + { + // Signed by the tenant issuer with the tenant audience and client: the operator scheme + // validates its own pinned issuer and audience, so it cannot be admitted here. + var tenantToken = _tenant.Token(_tenant.Payload()); + + var response = await Put(tenantToken, """{"enabled":false}"""); + + await AssertUnauthorized(response); + _toggle.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task An_Authenticated_Operator_Without_The_Grant_Is_Forbidden_And_Nothing_Is_Called() + { + var response = await Put(Sign(("sub", "someone-else")), """{"enabled":false}"""); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + await AssertProblem(response, "forbidden"); + _toggle.Calls.Should().BeEmpty("admission is refused before any operator service, so before any bypass connection"); + } + + [Theory] + [InlineData("has space")] + [InlineData("semi;colon")] + [InlineData("this-ticket-is-far-too-long-to-be-a-ticket-reference-it-exceeds-sixty-four")] + public async Task A_Malformed_Ticket_Is_A_Validation_Failure_Not_A_Permission_One(string ticket) + { + var response = await Put(Valid(), JsonSerializer.Serialize(new { enabled = false, ticket })); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + await AssertProblem(response, "validation_failed"); + _toggle.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"ticket":"INC-1"}""")] + [InlineData("""{"enabled":null}""")] + public async Task A_Body_Without_The_State_Is_A_Validation_Failure(string body) + { + var response = await Put(Valid(), body); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _toggle.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task An_Unknown_Killswitch_Key_Is_Not_Found() + { + _toggle.Outcome = KillswitchToggleOutcome.UnknownKey; + + var response = await Put(Valid(), """{"enabled":false}"""); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Fact] + public async Task A_Failed_Audit_Write_Is_A_Retryable_503_Not_A_Success() + { + _toggle.Failure = new AuditWriteFailedException("forced"); + using var counted = Counted(); + + var response = await Put(Valid(), """{"enabled":false}"""); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + await AssertProblem(response, "audit_unavailable"); + response.Headers.RetryAfter.Should().NotBeNull("every 503 the API answers carries Retry-After"); + counted.AuditFailures.Should().Be(1, "a refused audit write is a signal an alert can watch"); + } + + [Theory] + [InlineData("{}")] + [InlineData("""{"enabled":false,"ticket":"has space"}""")] + [InlineData("""{"enabled":"not-a-bool"}""")] + public async Task An_Operator_Without_The_Grant_Is_Refused_As_Such_Whatever_The_Body_Says(string body) + { + // Admission comes first: a malformed body or ticket never earns an ungranted operator a 400, + // so the refusal teaches them nothing about the request and is counted as a missing permission. + using var counted = Counted(); + + var response = await Put(Sign(("sub", "someone-else")), body); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + await AssertProblem(response, "forbidden"); + _toggle.Calls.Should().BeEmpty(); + counted.Causes.Should().Contain("missing_permission"); + } + + [Fact] + public async Task A_Body_That_Is_Not_Json_Or_Not_Valid_Json_Is_Answered_As_A_Problem_Not_A_Bare_Status() + { + using var wrongType = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "text/plain"), + }; + using var malformed = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{", System.Text.Encoding.UTF8, "application/json"), + }; + + var first = await _client.SendAsync(wrongType); + var second = await _client.SendAsync(malformed); + + first.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + second.StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await first.Content.ReadAsStringAsync()).Should().Contain("\"code\""); + (await second.Content.ReadAsStringAsync()).Should().Contain("\"code\""); + _toggle.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task The_Served_Contract_Documents_The_Federation_Report_Its_Unread_Count_And_The_Removal_Rule() + { + using var document = JsonDocument.Parse(await _client.GetStringAsync("/openapi/platform-v1.json")); + var paths = document.RootElement.GetProperty("paths"); + + var report = paths.GetProperty("/api/platform/v1/federation/brokers").GetProperty("get"); + report.GetProperty("description").GetString().Should().Contain("mappersUnread").And.Contain("not the end"); + var schema = document.RootElement.GetProperty("components").GetProperty("schemas").GetProperty("FederationReportResponse"); + schema.GetProperty("properties").TryGetProperty("mappersUnread", out var unread).Should().BeTrue(); + unread.GetProperty("type").ToString().Should().Contain("integer"); + schema.GetProperty("required").EnumerateArray().Select(item => item.GetString()).Should().Contain("mappersUnread"); + + var remove = paths.GetProperty("/api/platform/v1/federation/brokers/{alias}/remove").GetProperty("post"); + remove.GetProperty("description").GetString().Should().Contain("reads or is still enabled").And.Contain("disabled"); + document.RootElement.GetProperty("info").GetProperty("description").GetString().Should().Contain("federation-operator.md"); + var conflict = remove.GetProperty("responses").GetProperty("409").GetProperty("description").GetString(); + conflict.Should().Contain("errors.owner").And.Contain("errors.connection").And.Contain("errors.class").And.Contain("errors.provider"); + } + + [Fact] + public async Task The_Operator_Contract_Is_Its_Own_Document_And_The_Tenant_Document_Does_Not_Carry_It() + { + var operatorDocument = await _client.GetStringAsync("/openapi/platform-v1.json"); + var tenantDocument = await _client.GetStringAsync("/openapi/v1.json"); + + foreach (var route in OperatorRoutes) + { + operatorDocument.Should().Contain(route, "the contract is the only client the operator surface has"); + } + + tenantDocument.Should().NotContain("/api/platform", "the tenant contract is pinned and untouched (ADR-0101 § 4)"); + + // What a client author needs: a title, no Host-derived servers, the bearer scheme and its token + // profile, a security requirement on the operation, and every status an operator can meet. + using var document = JsonDocument.Parse(operatorDocument); + var root = document.RootElement; + root.GetProperty("info").GetProperty("title").GetString().Should().Be("LearnStack Platform Operator API"); + root.TryGetProperty("servers", out var servers).Should().BeFalse("servers would be derived from the caller's Host header"); + _ = servers; + var scheme = root.GetProperty("components").GetProperty("securitySchemes").GetProperty("PlatformOperator"); + scheme.GetProperty("scheme").GetString().Should().Be("bearer"); + scheme.GetProperty("bearerFormat").GetString().Should().Be("JWT"); + var put = root.GetProperty("paths").GetProperty("/api/platform/v1/killswitches/{key}").GetProperty("put"); + put.GetProperty("security").GetArrayLength().Should().Be(1); + put.GetProperty("requestBody").GetProperty("content").TryGetProperty("application/json", out _).Should().BeTrue(); + put.GetProperty("responses").EnumerateObject().Select(response => response.Name) + .Should().Contain(["200", "400", "401", "403", "404", "415", "500", "503"]); + put.GetProperty("responses").GetProperty("401").GetProperty("headers").TryGetProperty("WWW-Authenticate", out _) + .Should().BeTrue(); + put.GetProperty("responses").GetProperty("503").GetProperty("headers").TryGetProperty("Retry-After", out _) + .Should().BeTrue(); + put.GetProperty("responses").TryGetProperty("409", out _).Should().BeFalse("a switch toggle never answers a refused state"); + + // Every act has its own body, the same status set, and a 409 for the state it refuses. An inspection is a + // read: it has no body and nothing to refuse, so it answers no 409. + foreach (var route in OperatorRoutes.Where(route => !route.Contains("killswitches", StringComparison.Ordinal))) + { + var act = root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)); + act.GetProperty("security").GetArrayLength().Should().Be(1, route); + if (VerbOf(route) == "get") + { + act.TryGetProperty("requestBody", out _).Should().BeFalse("a read carries no body: " + route); + act.GetProperty("responses").EnumerateObject().Select(response => response.Name) + .Should().Contain(["200", "400", "401", "403", "500", "503"], route); + continue; + } + + act.GetProperty("requestBody").GetProperty("content").GetProperty("application/json") + .GetProperty("schema").ValueKind.Should().NotBe(JsonValueKind.Undefined, route); + act.GetProperty("responses").EnumerateObject().Select(response => response.Name) + .Should().Contain(["200", "400", "401", "403", "404", "409", "415", "500", "503"], route); + } + + root.GetProperty("paths").EnumerateObject().Select(path => path.Name).Should().BeEquivalentTo(OperatorRoutes, + "a route that is not in the closed list is an operator act nobody reviewed"); + + // What a generated client needs to know it must send, and the statuses it can meet beyond the common ones. + var schemas = root.GetProperty("components").GetProperty("schemas"); + string[] RequiredOf(string route) + { + var schema = root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)).GetProperty("requestBody") + .GetProperty("content").GetProperty("application/json").GetProperty("schema"); + if (schema.TryGetProperty("$ref", out var reference)) + { + schema = schemas.GetProperty(reference.GetString()!.Split('/')[^1]); + } + + return schema.TryGetProperty("required", out var required) + ? [.. required.EnumerateArray().Select(name => name.GetString()!)] : []; + } + + RequiredOf("/api/platform/v1/tenants/{tenantId}").Should().Contain(["slug", "displayName", "defaultOrganization"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/host-mappings/{host}").Should().Contain(["isActive", "isPubliclyLive"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/roles/{roleId}").Should().Contain(["builtInKey", "capabilityScope"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}").Should().Contain(["roleId", "providerSubject"]); + RequiredOf("/api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}").Should().Contain(["roleId", "providerSubject"]); + RequiredOf("/api/platform/v1/asynchronous-work/event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay") + .Should().Contain(["replayCount", "deadLetteredAt", "terminalReason"]); + RequiredOf("/api/platform/v1/asynchronous-work/outbox-messages/{tenantId}/{eventId}/reset") + .Should().Contain(["attempts", "deadLetteredAt"]); + foreach (var route in OperatorRoutes) + { + var statuses = root.GetProperty("paths").GetProperty(route).GetProperty(VerbOf(route)).GetProperty("responses") + .EnumerateObject().Select(response => response.Name).ToArray(); + if (VerbOf(route) == "get") + { + statuses.Should().Contain("429", route).And.NotContain(["404", "409", "413", "415"], "a read has no body, no row to find and no state to refuse: " + route); + } + else + { + statuses.Should().Contain(["413", "429"], route); + } + } + + // The page parameters are declared by their rule, not only described: the closed state set, the size range, + // the ticket's shape and the cursor's bound. + JsonElement ParameterOf(string route, string name) => root.GetProperty("paths").GetProperty(route).GetProperty("get") + .GetProperty("parameters").EnumerateArray().Single(parameter => parameter.GetProperty("name").GetString() == name) + .GetProperty("schema"); + var outbox = "/api/platform/v1/asynchronous-work/outbox-messages"; + root.GetProperty("paths").GetProperty("/api/platform/v1/asynchronous-work/quarantined-jobs").GetProperty("get") + .GetProperty("parameters").EnumerateArray().Select(parameter => parameter.GetProperty("name").GetString()) + .Should().NotContain("state", "the jobs list takes no state and refuses one"); + ParameterOf(outbox, "state").GetProperty("enum").EnumerateArray().Select(value => value.GetString()) + .Should().BeEquivalentTo(["dead_lettered", "terminal_requested"]); + ParameterOf(outbox, "limit").GetProperty("minimum").GetRawText().Trim('"').Should().Be("1"); + ParameterOf(outbox, "cursor").GetProperty("maxLength").GetInt32().Should().Be(512); + ParameterOf(outbox, "ticket").GetProperty("pattern").GetString().Should().Be(@"^[A-Za-z0-9._:/#-]{1,64}$"); + } + + private const string Work = "/api/platform/v1/asynchronous-work"; + private const string RowTenant = "019a1929-5450-7bbb-8df1-516e8e002501"; + private const string RowEvent = "019a1929-5450-7bbb-8df1-516e8e002502"; + private const string RowSubscription = "orders.notify.v1"; + private const string ReplayPath = Work + "/event-deliveries/" + RowTenant + "/" + RowSubscription + "/" + RowEvent + "/replay"; + private const string ResetPath = Work + "/outbox-messages/" + RowTenant + "/" + RowEvent + "/reset"; + private const string ReplayBody = """{"replayCount":2,"deadLetteredAt":"2026-10-01T12:00:00.1234560Z","terminalReason":"retry_exhausted","ticket":"CHG-103"}"""; + private const string ResetBody = """{"attempts":6,"deadLetteredAt":"2026-10-01T12:00:00.1234560Z","ticket":"CHG-103"}"""; + + [Fact] + public async Task An_Inspection_Passes_Its_Parameters_On_Clamps_The_Limit_And_Answers_The_Page_Envelope() + { + var response = await Call(HttpMethod.Get, Work + "/outbox-messages?state=terminal_requested&limit=500&cursor=abc&ticket=CHG-1", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var call = _inspection.Calls.Should().ContainSingle().Which; + call.Resource.Should().Be("outbox"); + call.State.Should().Be(DeliveryInspectionState.TerminalRequested); + call.Cursor.Should().Be("abc"); + call.Limit.Should().Be(100, "a limit above the maximum is clamped, as Standard 04 says"); + call.Admission.Operation.Should().BeSameAs(PlatformOperations.DeliveryInspect); + call.Admission.Ticket.Should().Be("CHG-1"); + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain("\"items\":[]").And.Contain("\"nextCursor\":\"next-cursor\"").And.Contain("\"hasNext\":true"); + } + + [Theory] + [InlineData("state=bogus")] + [InlineData("limit=abc")] + [InlineData("limit=-1")] + [InlineData("limit=1.5")] + [InlineData("limit=0")] + [InlineData("ticket=has%20space")] + public async Task An_Inspection_With_A_Malformed_Parameter_Is_A_Validation_Failure_Before_Any_Scope(string query) + { + var response = await Call(HttpMethod.Get, Work + "/event-deliveries?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _inspection.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("500")] + [InlineData("99999999999")] + [InlineData("99999999999999999999999999")] + public async Task A_Limit_Of_Any_Size_Is_Clamped_To_The_Maximum_And_Never_Refused(string limit) + { + var response = await Call(HttpMethod.Get, Work + "/event-deliveries?limit=" + limit, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + _inspection.Calls.Should().ContainSingle().Which.Limit.Should().Be(100); + } + + [Theory] + [InlineData("statee=terminal_requested")] + [InlineData("limt=5")] + [InlineData("state=dead_lettered&cursr=abc")] + public async Task A_Misspelt_Parameter_Is_Refused_And_Never_Ignored_And_Is_Not_Echoed(string query) + { + var response = await Call(HttpMethod.Get, Work + "/outbox-messages?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("errors").TryGetProperty("query", out _).Should().BeTrue(); + text.Should().NotContain("statee").And.NotContain("limt").And.NotContain("cursr"); + _inspection.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("tenant_not_serving")] + [InlineData("invalid_envelope")] + [InlineData("type_not_dispatchable")] + public async Task A_Refused_State_Names_The_Rule_That_Refused_It_As_A_Parameter_Of_Its_Reason(string cause) + { + _recovery.Result = new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable, Refusal: cause); + + var response = await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var reason = body.RootElement.GetProperty("errors").GetProperty("state")[0]; + reason.GetProperty("key").GetString().Should().Be("lockey_not_recoverable"); + reason.GetProperty("params").GetProperty("cause").GetString().Should().Be(cause); + } + + [Fact] + public async Task An_Unavailable_Owner_Logs_Its_Cause_Under_Its_Own_Event_Id_Which_No_Other_Line_Uses() + { + _recovery.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), ReplayBody); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + var entry = _logs.Entries.Should().ContainSingle(line => line.Id == 7110).Which; + entry.Level.Should().Be(LogLevel.Warning); + entry.Exception.Should().BeOfType("the cause is in the log and in no response"); + (await response.Content.ReadAsStringAsync()).Should().NotContain("forced"); + // 7109 is the onboarding pipeline's defect alert, which the operator runbooks pin to that meaning. + _logs.Entries.Should().NotContain(line => line.Id == 7109); + } + + private const string Fed = "/api/platform/v1/federation/brokers"; + private const string BrokerAlias = "lsf-019a192954507bbb8df1516e8e002502"; + + [Fact] + public async Task A_Federation_Report_Passes_Its_Page_On_Clamps_The_Limit_And_Answers_The_Envelope() + { + var response = await Call(HttpMethod.Get, Fed + "?limit=500&cursor=abc&ticket=CHG-5", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var call = _brokers.Calls.Should().ContainSingle().Which; + (call.Operation, call.Argument, call.Limit).Should().Be(("report", "abc", 100)); + call.Admission.Operation.Should().BeSameAs(PlatformOperations.FederationReport); + call.Admission.Ticket.Should().Be("CHG-5"); + var text = await response.Content.ReadAsStringAsync(); + text.Should().Contain("\"items\":[]").And.Contain("\"nextCursor\":\"next\"").And.Contain("\"scanned\":3").And.Contain("\"ignored\":1") + .And.Contain("\"mappersUnread\":4"); + } + + [Theory] + [InlineData("limit=0", "limit")] + [InlineData("state=terminal_requested", "query")] + [InlineData("limt=5", "query")] + public async Task A_Federation_Report_Refuses_A_Bad_Or_Unknown_Parameter_And_Names_It_Without_Echo(string query, string field) + { + var response = await Call(HttpMethod.Get, Fed + "?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("errors").TryGetProperty(field, out _).Should().BeTrue(field); + text.Should().NotContain("limt"); + _brokers.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Cursor_The_Federation_Owner_Refuses_And_An_Unavailable_Provider_Are_Answered_As_Their_Problems() + { + _brokers.Report = FederationReportResult.Of(FederationReportOutcome.InvalidCursor); + var refused = await Call(HttpMethod.Get, Fed + "?cursor=forged", Valid()); + refused.StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await refused.Content.ReadAsStringAsync()).Should().Contain("cursor"); + + _brokers.Report = FederationReportResult.Of(FederationReportOutcome.Unavailable); + var unavailable = await Call(HttpMethod.Get, Fed, Valid()); + unavailable.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + unavailable.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await unavailable.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + } + + [Theory] + [InlineData("remove", "FederationRemove")] + [InlineData("disable", "FederationDisable")] + public async Task A_Federation_Act_Runs_Under_An_Admission_For_Exactly_Its_Operation_And_Answers_The_Review_Owed( + string verb, string operationName) + { + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/{verb}", Valid(), """{"ticket":"CHG-9"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var call = _brokers.Calls.Should().ContainSingle().Which; + (call.Operation, call.Argument).Should().Be((verb, BrokerAlias)); + call.Admission.Operation.Should().BeSameAs(operationName == "FederationRemove" + ? PlatformOperations.FederationRemove : PlatformOperations.FederationDisable); + call.Admission.Ticket.Should().Be("CHG-9"); + var text = await response.Content.ReadAsStringAsync(); + text.Should().Contain("\"outcome\":\"applied\"").And.Contain("\"accountReviewOwed\":true").And.Contain(BrokerAlias); + } + + [Theory] + [InlineData("not-an-alias")] + [InlineData("lsf-ABCDEF0123456789ABCDEF0123456789")] + [InlineData("lsf-0123456789abcdef0123456789abcde")] + [InlineData("kc-019a192954507bbb8df1516e8e002502")] + public async Task A_Federation_Act_Names_Only_A_Derived_Alias_And_Calls_Nothing_Otherwise(string alias) + { + var response = await Call(HttpMethod.Post, $"{Fed}/{alias}/remove", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _brokers.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData(FederationActOutcome.NotOwned, "owner", "lockey_not_owned")] + [InlineData(FederationActOutcome.LiveConnection, "connection", "lockey_live_connection")] + [InlineData(FederationActOutcome.NotApplicable, "class", "lockey_not_applicable")] + [InlineData(FederationActOutcome.Refused, "provider", "lockey_provider_refused")] + public async Task A_Federation_Act_Refusal_Is_A_409_With_Its_Reason_On_The_Field_It_Concerns( + FederationActOutcome outcome, string field, string reason) + { + _brokers.Act = new FederationActResult(outcome); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("business_rule_violation"); + var reasons = body.RootElement.GetProperty("errors").EnumerateObject().ToDictionary( + property => property.Name, property => property.Value[0].GetProperty("key").GetString()); + reasons.Should().Equal(new Dictionary { [field] = reason }, "the reason is on the field it concerns, and only there"); + } + + [Theory] + [InlineData(FederationActOutcome.AlreadyApplied, HttpStatusCode.OK, "already_applied", false)] + [InlineData(FederationActOutcome.NotFound, HttpStatusCode.NotFound, null, false)] + public async Task A_Federation_Act_Answers_A_Repeat_Or_A_Missing_Alias_Without_Owing_An_Account_Review( + FederationActOutcome outcome, HttpStatusCode status, string? token, bool owed) + { + _brokers.Act = new FederationActResult(outcome); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}"); + + response.StatusCode.Should().Be(status); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + if (token is null) + { + body.RootElement.GetProperty("code").GetString().Should().Be("not_found"); + return; + } + + (body.RootElement.GetProperty("outcome").GetString(), body.RootElement.GetProperty("accountReviewOwed").GetBoolean()).Should().Be((token, owed)); + } + + [Fact] + public async Task An_Unknown_Or_Unavailable_Federation_Outcome_Is_A_Retryable_503_Whose_Body_Agrees_With_Its_Status() + { + foreach (var (outcome, unknown) in new[] { (FederationActOutcome.Unavailable, false), (FederationActOutcome.Uncertain, true) }) + { + _brokers.Act = new FederationActResult(outcome); + + var response = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, outcome.ToString()); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503); + body.RootElement.TryGetProperty("errors", out var errors).Should().Be(unknown); + if (unknown) errors.GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } + } + + [Fact] + public async Task A_Failed_Federation_Audit_Write_Is_The_Retryable_Audit_503_And_Is_Counted() + { + using var counted = Counted(); + _brokers.Failure = new AuditWriteFailedException("forced"); + + var act = await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + var report = await Call(HttpMethod.Get, Fed, Valid()); + + foreach (var response in new[] { act, report }) + { + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + await AssertProblem(response, "audit_unavailable"); + } + + counted.AuditFailures.Should().Be(2); + } + + [Theory] + [InlineData("report")] + [InlineData("remove")] + public async Task A_Database_Fault_The_Federation_Owner_Translates_Is_A_Retryable_503_Without_An_Unknown_Outcome(string act) + { + using var federation = new FederationListener(); + _brokers.Failure = new OperatorRecoveryUnavailableException(cause: new InvalidOperationException("the database is not reachable")); + + var response = act == "report" + ? await Call(HttpMethod.Get, Fed, Valid()) + : await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + body.RootElement.TryGetProperty("errors", out _).Should().BeFalse("nothing was changed, so no unknown outcome is named"); + federation.Calls.Should().Equal([(act == "report" ? "platform.federation.report" : "platform.federation.remove", "unavailable")]); + } + + [Fact] + public async Task The_Federation_Counter_Is_Labelled_By_The_Operation_Slug_And_A_Closed_Outcome_And_Counts_Only_Calls_That_Reached_The_Owner() + { + using var federation = new FederationListener(); + + (await Call(HttpMethod.Get, Fed, Valid())).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + _brokers.Act = new FederationActResult(FederationActOutcome.AlreadyApplied); + (await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Get, Fed + "?limit=0", Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + + federation.Calls.Should().Equal( + ("platform.federation.report", "ok"), ("platform.federation.remove", "applied"), ("platform.federation.disable", "already_applied")); + } + + [Theory] + [InlineData(FedKey.None)] + [InlineData(FedKey.Read)] + [InlineData(FedKey.Admin)] + public async Task The_Federation_Read_And_Admin_Keys_Admit_Only_Their_Own_Routes_And_The_Delivery_Keys_Neither(FedKey held) + { + var key = held switch + { + FedKey.Read => PlatformPermissions.FederationRead.Key, + FedKey.Admin => PlatformPermissions.FederationAdmin.Key, + _ => PlatformPermissions.DeliveryWrite.Key, + }; + var brokers = new RecordingBrokers(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => registrations.AddScoped(_ => brokers), + permissions: [key]); + using var client = single.CreateClient(); + + async Task Send(HttpMethod method, string path, string? json) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + Valid() } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return (await client.SendAsync(request)).StatusCode; + } + + (await Send(HttpMethod.Get, Fed, null)).Should().Be(held == FedKey.Read ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + (await Send(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", "{}")).Should().Be( + held == FedKey.Admin ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + (await Send(HttpMethod.Post, $"{Fed}/{BrokerAlias}/disable", "{}")).Should().Be( + held == FedKey.Admin ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + brokers.Calls.Count.Should().Be(held == FedKey.None ? 0 : held == FedKey.Read ? 1 : 2); + } + + public enum FedKey + { + None, + Read, + Admin, + } + + [Theory] + [InlineData("limit=0", "limit")] + [InlineData("limit=-3", "limit")] + [InlineData("state=bogus", "state")] + public async Task A_Refused_Page_Parameter_Names_Itself_As_Standard_04_Asks(string query, string field) + { + var response = await Call(HttpMethod.Get, Work + "/outbox-messages?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("errors").TryGetProperty(field, out _).Should().BeTrue(field); + _inspection.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task The_Quarantined_Jobs_List_Takes_No_State_And_Refuses_One_After_The_Gate() + { + var refused = await Call(HttpMethod.Get, Work + "/quarantined-jobs?state=terminal_requested", Valid()); + + refused.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using (var body = JsonDocument.Parse(await refused.Content.ReadAsStringAsync())) + { + body.RootElement.GetProperty("errors").TryGetProperty("state", out _).Should().BeTrue(); + } + + _inspection.Calls.Should().BeEmpty(); + (await Call(HttpMethod.Get, Work + "/quarantined-jobs?state=terminal_requested", Sign(("sub", "someone-else")))) + .StatusCode.Should().Be(HttpStatusCode.Forbidden, "the gate answers before a parameter is read"); + } + + [Fact] + public async Task An_Inspection_Whose_Database_Fault_Surfaces_Is_A_Retryable_503_Whose_Body_Agrees_With_Its_Status() + { + _inspection.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + + var response = await Call(HttpMethod.Get, Work + "/outbox-messages", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + body.RootElement.ToString().Should().NotContain("forced", "the cause is for the log and never for the response"); + } + + [Theory] + [InlineData(HeldKey.None)] + [InlineData(HeldKey.Read)] + [InlineData(HeldKey.Write)] + public async Task The_Read_And_Write_Delivery_Permissions_Admit_Only_Their_Own_Routes_And_The_Killswitch_Grant_Neither( + HeldKey held) + { + // ADR-0103 Decision table. Every other test here runs as an operator who holds all three keys, so none of them can tell + // which key a route asks for. This one holds exactly one key, and the other routes must refuse it. + var key = held switch + { + HeldKey.Read => PlatformPermissions.DeliveryRead.Key, + HeldKey.Write => PlatformPermissions.DeliveryWrite.Key, + _ => PlatformPermissions.KillswitchWrite.Key, + }; + var recovery = new RecordingRecovery(); + var inspection = new RecordingInspection(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => + { + registrations.AddSingleton(recovery); + registrations.AddScoped(_ => inspection); + }, + permissions: [key]); + using var client = single.CreateClient(); + + async Task Send(HttpMethod method, string path, string? json) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + Valid() } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return (await client.SendAsync(request)).StatusCode; + } + + var reads = new[] { Work + "/outbox-messages", Work + "/event-deliveries", Work + "/quarantined-jobs" }; + foreach (var path in reads) + { + (await Send(HttpMethod.Get, path, null)).Should().Be( + held == HeldKey.Read ? HttpStatusCode.OK : HttpStatusCode.Forbidden, path); + } + + (await Send(HttpMethod.Post, ReplayPath, ReplayBody)).Should().Be( + held == HeldKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden, ReplayPath); + (await Send(HttpMethod.Post, ResetPath, ResetBody)).Should().Be( + held == HeldKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden, ResetPath); + inspection.Calls.Count.Should().Be(held == HeldKey.Read ? reads.Length : 0); + recovery.Calls.Count.Should().Be(held == HeldKey.Write ? 2 : 0); + } + + public enum HeldKey + { + None, + Read, + Write, + } + + [Fact] + public async Task A_Cursor_The_Service_Refuses_Is_A_Validation_Failure_And_A_Failed_Audit_Write_Is_A_Retryable_503() + { + _inspection.RefuseCursor = true; + (await Call(HttpMethod.Get, Work + "/quarantined-jobs?cursor=forged", Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + + _inspection.RefuseCursor = false; + _inspection.Failure = new AuditWriteFailedException("forced"); + var response = await Call(HttpMethod.Get, Work + "/quarantined-jobs", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter.Should().NotBeNull(); + } + + [Theory] + [InlineData("GET", Work + "/outbox-messages")] + [InlineData("GET", Work + "/event-deliveries")] + [InlineData("GET", Work + "/quarantined-jobs")] + [InlineData("POST", ReplayPath)] + [InlineData("POST", ResetPath)] + public async Task An_Operator_Without_The_Delivery_Grants_Is_Forbidden_Whatever_The_Request_Carries_And_Nothing_Is_Called(string verb, string path) + { + var response = await Call(new HttpMethod(verb), path, Sign(("sub", "someone-else")), verb == "POST" ? "not json" : null); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + await AssertProblem(response, "forbidden"); + _inspection.Calls.Should().BeEmpty("admission is refused before any scope is entered"); + _recovery.Calls.Should().BeEmpty("admission is refused before any outbox-role connection is opened"); + } + + [Fact] + public async Task A_Replay_Carries_The_Fence_To_The_Microsecond_Under_An_Admission_For_Exactly_That_Operation() + { + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), ReplayBody); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, request) = _recovery.Calls.Should().ContainSingle().Which; + admission.Operation.Should().BeSameAs(PlatformOperations.DeliveryReplay); + admission.Ticket.Should().Be("CHG-103"); + var replay = request.Should().BeOfType().Which; + replay.TenantId.Should().Be(Guid.Parse(RowTenant)); + replay.EventId.Should().Be(Guid.Parse(RowEvent)); + replay.SubscriptionId.Should().Be(RowSubscription); + replay.ReplayCount.Should().Be(2); + replay.TerminalReason.Should().Be("retry_exhausted"); + replay.DeadLetteredAt.UtcTicks.Should().Be(new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero).AddTicks(1234560).UtcTicks); + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain("\"outcome\":\"applied\"").And.Contain("\"countAfter\":1").And.Contain("\"correlationId\""); + } + + [Fact] + public async Task A_Reset_Carries_Its_Fence_Under_An_Admission_For_The_Reset_Operation() + { + var response = await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, request) = _recovery.Calls.Should().ContainSingle().Which; + admission.Operation.Should().BeSameAs(PlatformOperations.DeliveryReset); + var reset = request.Should().BeOfType().Which; + (reset.TenantId, reset.EventId, reset.Attempts).Should().Be((Guid.Parse(RowTenant), Guid.Parse(RowEvent), 6)); + } + + [Theory] + [InlineData("""{}""")] + [InlineData("""{"replayCount":2,"deadLetteredAt":"2026-10-01T12:00:00Z"}""")] + [InlineData("""{"replayCount":2,"deadLetteredAt":"not a date","terminalReason":"retry_exhausted"}""")] + [InlineData("""{"replayCount":2,"deadLetteredAt":"2026-10-01T12:00:00Z","terminalReason":"retry_exhausted","ticket":"has space"}""")] + public async Task A_Replay_Body_That_Cannot_Be_A_Fence_Is_A_Validation_Failure_And_Nothing_Is_Called(string body) + { + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), body); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + _recovery.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData("/event-deliveries/not-a-guid/orders.notify.v1/" + RowEvent + "/replay", HttpStatusCode.NotFound)] + [InlineData("/event-deliveries/" + RowTenant + "/Not.A.Subscription/" + RowEvent + "/replay", HttpStatusCode.BadRequest)] + [InlineData("/event-deliveries/00000000-0000-0000-0000-000000000000/orders.notify.v1/" + RowEvent + "/replay", HttpStatusCode.BadRequest)] + [InlineData("/event-deliveries/" + RowTenant + "/orders.notify.v1/00000000-0000-0000-0000-000000000000/replay", HttpStatusCode.BadRequest)] + public async Task A_Replay_Route_Naming_No_Real_Row_Is_Refused_Without_Calling_The_Owner(string suffix, HttpStatusCode expected) + { + // A tenant that is not a UUID matches no route; the nil identifiers and a malformed subscription match it and + // are refused by the route's own checks, after the gate. + var response = await Call(HttpMethod.Post, Work + suffix, Valid(), ReplayBody); + + response.StatusCode.Should().Be(expected); + _recovery.Calls.Should().BeEmpty(); + } + + [Theory] + [InlineData(OperatorRecoveryOutcome.StaleFence, HttpStatusCode.Conflict, "lockey_stale_fence")] + [InlineData(OperatorRecoveryOutcome.NotRecoverable, HttpStatusCode.Conflict, "lockey_not_recoverable")] + [InlineData(OperatorRecoveryOutcome.NotFound, HttpStatusCode.NotFound, "not_found")] + public async Task A_Refused_Recovery_Answers_Its_Status_With_The_Reason_On_The_Field_It_Concerns( + OperatorRecoveryOutcome outcome, HttpStatusCode status, string expected) + { + _recovery.Result = new OperatorRecoveryResult(outcome); + + var response = await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody); + + response.StatusCode.Should().Be(status); + (await response.Content.ReadAsStringAsync()).Should().Contain(expected); + } + + [Fact] + public async Task A_Stale_Fence_And_A_Refused_State_Name_Different_Fields_Under_One_Status_Code() + { + _recovery.Result = new OperatorRecoveryResult(OperatorRecoveryOutcome.StaleFence); + var stale = await (await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody)).Content.ReadAsStringAsync(); + _recovery.Result = new OperatorRecoveryResult(OperatorRecoveryOutcome.NotRecoverable); + var state = await (await Call(HttpMethod.Post, ResetPath, Valid(), ResetBody)).Content.ReadAsStringAsync(); + + stale.Should().Contain("\"code\":\"business_rule_violation\"").And.Contain("\"fence\""); + state.Should().Contain("\"code\":\"business_rule_violation\"").And.Contain("\"state\""); + } + + [Fact] + public async Task An_Owner_That_Cannot_Finish_Or_Whose_Commit_Is_Unknown_Or_Whose_Audit_Failed_Is_A_Retryable_503_With_Its_Own_Reason() + { + foreach (var (failure, reason) in new (Exception, string)[] + { + (new OperatorRecoveryUnavailableException(), "dependency_unavailable"), + (new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true), "outcome_unknown"), + (new AuditWriteFailedException("forced"), "audit_unavailable"), + }) + { + _recovery.Failure = failure; + + var response = await Call(HttpMethod.Post, ReplayPath, Valid(), ReplayBody); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, reason); + response.Headers.RetryAfter.Should().NotBeNull(reason); + var text = await response.Content.ReadAsStringAsync(); + text.Should().Contain(reason); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503, "the body's status never disagrees with the response's: " + reason); + body.RootElement.GetProperty("code").GetString().Should().Be( + reason == "outcome_unknown" ? "dependency_unavailable" : reason); + if (reason == "outcome_unknown") + { + body.RootElement.GetProperty("errors").GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } + } + } + + [Fact] + public async Task An_Act_Without_A_Body_Or_With_The_Wrong_Media_Type_Is_Answered_As_A_Problem_Only_To_A_Granted_Operator() + { + (await Call(HttpMethod.Post, ResetPath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var wrongType = new HttpRequestMessage(HttpMethod.Post, ResetPath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent(ResetBody, System.Text.Encoding.UTF8, "text/plain"), + }; + + (await _client.SendAsync(wrongType)).StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + _recovery.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task The_Production_Composition_Resolves_The_Recovery_Owner_And_The_Inspection_Over_The_Real_Stores() + { + // The doubles above replace both ports, so this builds the host the way production does and asks for them: a + // registration that is missing or cannot be constructed would otherwise surface only on the first operator call. + await using var production = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject); + using var client = production.CreateClient(); + + using var scope = production.Services.CreateScope(); + scope.ServiceProvider.GetRequiredService() + .Should().BeOfType(); + scope.ServiceProvider.GetRequiredService() + .Should().BeOfType(); + scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); + scope.ServiceProvider.GetRequiredService().Should().NotBeNull(); + } + + private static readonly string[] OperatorRoutes = + [ + "/api/platform/v1/killswitches/{key}", + "/api/platform/v1/tenants/{tenantId}", + "/api/platform/v1/tenants/{tenantId}/host-mappings/{host}", + "/api/platform/v1/tenants/{tenantId}/roles/{roleId}", + "/api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}", + "/api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}", + "/api/platform/v1/asynchronous-work/outbox-messages", + "/api/platform/v1/asynchronous-work/event-deliveries", + "/api/platform/v1/asynchronous-work/quarantined-jobs", + "/api/platform/v1/asynchronous-work/event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay", + "/api/platform/v1/asynchronous-work/outbox-messages/{tenantId}/{eventId}/reset", + "/api/platform/v1/federation/brokers", + "/api/platform/v1/federation/brokers/{alias}/remove", + "/api/platform/v1/federation/brokers/{alias}/disable", + ]; + + /// The verb each operator route answers: reads are GET, recovery acts are POST, the rest are idempotent PUTs. + private static string VerbOf(string route) => + route.Contains("/asynchronous-work/", StringComparison.Ordinal) + ? route.EndsWith("/replay", StringComparison.Ordinal) || route.EndsWith("/reset", StringComparison.Ordinal) ? "post" : "get" + : route.Contains("/federation/", StringComparison.Ordinal) + ? route.EndsWith("/remove", StringComparison.Ordinal) || route.EndsWith("/disable", StringComparison.Ordinal) ? "post" : "get" + : "put"; + + [Fact] + public async Task Without_An_Issuer_The_Surface_And_Its_Document_Do_Not_Exist() + { + await using var absent = new PlatformOperatorApiFactory(_tenant, _operator, new RecordingToggle(), configured: false); + using var client = absent.CreateClient(); + + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = JsonContent.Create(new { enabled = false }), + }; + var response = await client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound, "no issuer means no operator route"); + (await client.GetAsync("/openapi/platform-v1.json")).StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Fact] + public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_Stays_The_Only_One_Without_An_Issuer() + { + var withIssuer = await _factory.Services.GetRequiredService() + .GetAllSchemesAsync(); + withIssuer.Select(scheme => scheme.Name).Should().BeEquivalentTo([TenantAuthenticationRegistration.Scheme, "PlatformOperator"]); + (await _factory.Services.GetRequiredService() + .GetDefaultAuthenticateSchemeAsync())!.Name.Should().Be(TenantAuthenticationRegistration.Scheme, + "the tenant scheme stays the default and the only scheme on /api/v1 (ADR-0064 Amendment 9)"); + + await using var absent = new PlatformOperatorApiFactory(_tenant, _operator, new RecordingToggle(), configured: false); + (await absent.Services.GetRequiredService() + .GetAllSchemesAsync()).Select(scheme => scheme.Name).Should().Equal(TenantAuthenticationRegistration.Scheme); + } + + [Fact] + public void The_Operator_Surface_Is_Exactly_The_Fourteen_Authorized_Endpoints_Under_Its_Prefix() + { + // The tenant surface census excludes this surface by exact type (it has its own scheme), so + // its population is closed here instead: every routed endpoint under /api/platform (whatever + // the case of its pattern) or carrying the operator metadata anywhere, its verb, and the + // policy that guards it. A second endpoint, another verb or a missing policy fails. + var endpoints = _factory.Services.GetServices() + .SelectMany(source => source.Endpoints).OfType() + .Where(endpoint => endpoint.RoutePattern.RawText!.TrimStart('/') + .StartsWith("api/platform", StringComparison.OrdinalIgnoreCase) + || endpoint.Metadata.GetMetadata() + ?.Kind == InfrastructureOperationKind.PlatformOperator) + .ToList(); + + endpoints.Select(endpoint => endpoint.RoutePattern.RawText).Should().BeEquivalentTo( + OperatorRoutes.Select(route => route.Replace("{tenantId}", "{tenantId:guid}").Replace("{roleId}", "{roleId:guid}") + .Replace("{membershipId}", "{membershipId:guid}").Replace("{eventId}", "{eventId:guid}")), + "the operator population is closed: a new route is a reviewed act with its own policy, grant and audit slug"); + foreach (var endpoint in endpoints) + { + var route = endpoint.RoutePattern.RawText; + endpoint.Metadata.GetMetadata()!.HttpMethods.Should().Equal( + [VerbOf(route!.Replace(":guid", string.Empty)).ToUpperInvariant()], route); + endpoint.Metadata.GetOrderedMetadata() + .Select(data => data.Policy).Should().Contain(PlatformOperatorAuthentication.PolicyName, + "an operator endpoint without the authenticated-operator policy would admit an anonymous caller: " + route); + endpoint.Metadata.GetMetadata().Should().BeNull(route); + } + } + + private string Header(string alg, string typ) => JsonSerializer.Serialize(new { alg, typ, kid = _operator.CurrentKey.Kid }); + + // Correctly signed, with an algorithm the scheme does not allow: only the algorithm is wrong. + private string SignWithSha384() + { + var input = TenantAuthenticationIssuer.Base64Url(System.Text.Encoding.UTF8.GetBytes(Header("RS384", "JWT"))) + + "." + TenantAuthenticationIssuer.Base64Url(System.Text.Encoding.UTF8.GetBytes(Payload([]))); + var signature = _operator.CurrentKey.Rsa.SignData( + System.Text.Encoding.ASCII.GetBytes(input), + System.Security.Cryptography.HashAlgorithmName.SHA384, + System.Security.Cryptography.RSASignaturePadding.Pkcs1); + return input + "." + TenantAuthenticationIssuer.Base64Url(signature); + } + + private string Valid() => Sign(); + + private static CauseListener Counted() => new(); + + /// Captures the cause label of every refusal counted while it is alive. + private sealed class CauseListener : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly ConcurrentBag _causes = []; + private long _metadataFailures; + private long _auditFailures; + + public CauseListener() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName + && instrument.Name is PlatformOperatorMetrics.RefusalCounterName + or PlatformOperatorMetrics.MetadataFailureCounterName + or PlatformOperatorMetrics.AuditFailureCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => + { + if (instrument.Name == PlatformOperatorMetrics.MetadataFailureCounterName) + { + Interlocked.Add(ref _metadataFailures, value); + } + + if (instrument.Name == PlatformOperatorMetrics.AuditFailureCounterName) + { + Interlocked.Add(ref _auditFailures, value); + } + + foreach (var tag in tags) + { + if (tag is { Key: "cause", Value: string cause }) + { + _causes.Add(cause); + } + } + }); + _listener.Start(); + } + + public IReadOnlyCollection Causes => _causes; + + public long MetadataFailures => Interlocked.Read(ref _metadataFailures); + + public long AuditFailures => Interlocked.Read(ref _auditFailures); + + public void Dispose() => _listener.Dispose(); + } + + private string Sign(params (string Name, object? Value)[] replacements) => _operator.Token(Payload(replacements)); + + private string SignWithout(string name) + { + using var baseline = JsonDocument.Parse(Payload([])); + return _operator.Token("{" + string.Join(",", baseline.RootElement.EnumerateObject() + .Where(property => property.Name != name) + .Select(property => JsonSerializer.Serialize(property.Name) + ":" + property.Value.GetRawText())) + "}"); + } + + private string Payload((string Name, object? Value)[] replacements) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var claims = new Dictionary(StringComparer.Ordinal) + { + ["iss"] = _operator.Issuer, + ["sub"] = Subject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + }; + foreach (var (name, value) in replacements) + { + claims[name] = value; + } + + return JsonSerializer.Serialize(claims); + } + + private static async Task Send(HttpClient client, string token) + { + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + token } }, + Content = new StringContent("""{"enabled":false}""", System.Text.Encoding.UTF8, "application/json"), + }; + return await client.SendAsync(request); + } + + private sealed class MovableClock(DateTimeOffset start) : LearnStack.SharedKernel.Time.IClock + { + public DateTimeOffset UtcNow { get; private set; } = start; + + public void Advance(TimeSpan by) => UtcNow += by; + } + + private async Task Call(HttpMethod method, string path, string token, string? json = null) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + token } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return await _client.SendAsync(request); + } + + private async Task Put(string token, string json) + { + using var request = new HttpRequestMessage(HttpMethod.Put, Path) + { + Headers = { { "Authorization", "Bearer " + token } }, + Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"), + }; + return await _client.SendAsync(request); + } + + private static async Task AssertUnauthorized(HttpResponseMessage response) + { + var diagnostics = response.Headers + await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.Unauthorized, diagnostics); + response.Headers.WwwAuthenticate.Should().ContainSingle(diagnostics).Which.Scheme.Should().Be("Bearer"); + await AssertProblem(response, "unauthorized"); + } + + private static async Task AssertProblem(HttpResponseMessage response, string code) + { + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain($"\"code\":\"{code}\""); + } + + private sealed class RecordingToggle : IKillswitchToggle + { + public List Calls { get; } = []; + public KillswitchToggleOutcome Outcome { get; set; } = KillswitchToggleOutcome.Applied; + public Exception? Failure { get; set; } + + public Task ToggleAsync( + PlatformAdmission admission, KillswitchKey key, bool enabled, CancellationToken cancellationToken = default) + { + Calls.Add(admission); + return Failure is not null + ? Task.FromException(Failure) + : Task.FromResult(new KillswitchToggleResult(Outcome, key, true, enabled)); + } + } + + /// Captures the operation and outcome labels of every federation call counted while it is alive. + private sealed class FederationListener : IDisposable + { + private readonly MeterListener _listener = new(); + private readonly ConcurrentQueue<(string Operation, string Outcome)> _calls = new(); + + public FederationListener() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName && instrument.Name == PlatformOperatorMetrics.FederationCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((_, _, tags, _) => + { + string? operation = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "operation") operation = tag.Value as string; + if (tag.Key == "outcome") outcome = tag.Value as string; + } + + _calls.Enqueue((operation ?? string.Empty, outcome ?? string.Empty)); + }); + _listener.Start(); + } + + public IReadOnlyList<(string Operation, string Outcome)> Calls => [.. _calls]; + + public void Dispose() => _listener.Dispose(); + } + + private sealed class RecordingBrokers : IFederationBrokerOperations + { + public List<(string Operation, PlatformAdmission Admission, string? Argument, int Limit)> Calls { get; } = []; + public FederationReportResult Report { get; set; } = new(FederationReportOutcome.Ok, [], "next", 3, 1, 4); + public FederationActResult Act { get; set; } = new(FederationActOutcome.Applied, Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501"), + Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502")); + public Exception? Failure { get; set; } + + public Task ReportAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) + { + Calls.Add(("report", admission, cursor, limit)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Report); + } + + public Task RemoveAsync(PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + Record("remove", admission, brokerAlias); + + public Task DisableAsync(PlatformAdmission admission, string brokerAlias, CancellationToken cancellationToken = default) => + Record("disable", admission, brokerAlias); + + private Task Record(string operation, PlatformAdmission admission, string alias) + { + Calls.Add((operation, admission, alias, 0)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Act); + } + } + + private sealed class RecordingRecovery : IOperatorRecovery + { + public List<(PlatformAdmission Admission, object Request)> Calls { get; } = []; + public OperatorRecoveryResult Result { get; set; } = new(OperatorRecoveryOutcome.Applied, 1); + public Exception? Failure { get; set; } + + public Task ReplayDeliveryAsync( + PlatformAdmission admission, DeliveryReplayRequest request, CancellationToken cancellationToken = default) => + Record(admission, request); + + public Task ResetOutboxAsync( + PlatformAdmission admission, OutboxResetRequest request, CancellationToken cancellationToken = default) => + Record(admission, request); + + private Task Record(PlatformAdmission admission, object request) + { + Calls.Add((admission, request)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Result); + } + } + + private sealed class CapturingLogs : ILoggerProvider + { + private readonly ConcurrentQueue<(int Id, LogLevel Level, Exception? Exception)> _entries = new(); + + public IReadOnlyCollection<(int Id, LogLevel Level, Exception? Exception)> Entries => [.. _entries]; + + public ILogger CreateLogger(string categoryName) => new Capture(_entries); + + public void Dispose() + { + } + + private sealed class Capture(ConcurrentQueue<(int Id, LogLevel Level, Exception? Exception)> entries) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + entries.Enqueue((eventId.Id, logLevel, exception)); + } + } + + private sealed class RecordingInspection : IDeliveryInspection + { + public List<(PlatformAdmission Admission, string Resource, DeliveryInspectionState? State, string? Cursor, int Limit)> Calls { get; } = []; + public bool RefuseCursor { get; set; } + public Exception? Failure { get; set; } + + public Task?> InspectOutboxAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) => + Page(admission, "outbox", state, cursor, limit); + + public Task?> InspectDeliveriesAsync( + PlatformAdmission admission, DeliveryInspectionState state, string? cursor, int limit, CancellationToken cancellationToken = default) => + Page(admission, "delivery", state, cursor, limit); + + public Task?> InspectJobsAsync( + PlatformAdmission admission, string? cursor, int limit, CancellationToken cancellationToken = default) => + Page(admission, "job", null, cursor, limit); + + private Task?> Page(PlatformAdmission admission, string resource, DeliveryInspectionState? state, string? cursor, int limit) + { + Calls.Add((admission, resource, state, cursor, limit)); + if (Failure is not null) return Task.FromException?>(Failure); + return Task.FromResult?>(RefuseCursor ? null : new InspectionPage([], "next-cursor")); + } + } + + private sealed class PlatformOperatorApiFactory( + TenantAuthenticationIssuer tenant, + TenantAuthenticationIssuer @operator, + IKillswitchToggle toggle, + string grantSubject = Subject, + bool configured = true, + Action? services = null, + string[]? permissions = null) : ConstructionOnlyApiFactory + { + protected override void ConfigureTestHost(IWebHostBuilder builder) + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting(TenantAuthenticationOptions.IssuerConfigurationKey, tenant.Issuer); + if (configured) + { + builder.UseSetting("PlatformOperator:Issuer", @operator.Issuer); + builder.UseSetting("PlatformOperator:AcceptedAcr:0", "mfa"); + builder.UseSetting("PlatformOperator:AuthorizedParties:0", "learnstack-operator"); + builder.UseSetting("PlatformOperator:Grants:0:Subject", grantSubject); + var held = permissions ?? + [ + PlatformPermissions.KillswitchWrite.Key, PlatformPermissions.DeliveryRead.Key, + PlatformPermissions.DeliveryWrite.Key, PlatformPermissions.FederationRead.Key, + PlatformPermissions.FederationAdmin.Key, + ]; + for (var index = 0; index < held.Length; index++) + { + builder.UseSetting("PlatformOperator:Grants:0:Permissions:" + index, held[index]); + } + } + + builder.ConfigureTestServices(registrations => + { + registrations.AddScoped(_ => toggle); + services?.Invoke(registrations); + }); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs new file mode 100644 index 000000000..ddc01d0a2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorTokenValidatorTests.cs @@ -0,0 +1,231 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The offline caller of the operator validator (ADR-0104 § 3) against a real loopback issuer: the same +/// cryptographic parameters, bounded metadata manager and closed profile the API scheme applies. +/// +/// +/// proves the same refusals through the HTTP scheme; here they are proved for +/// the second caller, so the two cannot drift. A refusal is one closed label and never a value the token carried. +/// +[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", + Justification = "xUnit disposes the fields through IAsyncLifetime.DisposeAsync.")] +public sealed class PlatformOperatorTokenValidatorTests : IAsyncLifetime +{ + private const string Subject = "operator-sub-7"; + private const string Correlation = "00-rebind-tool-01"; + + private TenantAuthenticationIssuer _issuer = null!; + private PlatformOperatorBackchannel _backchannel = null!; + private PlatformOperatorTokenValidator _validator = null!; + + public async Task InitializeAsync() + { + _issuer = await TenantAuthenticationIssuer.StartAsync(); + _backchannel = new PlatformOperatorBackchannel(); + _validator = ValidatorFor(_issuer); + } + + public async Task DisposeAsync() + { + _backchannel.Dispose(); + await _issuer.DisposeAsync(); + } + + [Fact] + public async Task A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Tool_Executor() + { + var result = await Validate(Sign()); + + result.IsValid.Should().BeTrue(); + result.Cause.Should().BeNull(); + var witness = result.Witness!; + witness.Issuer.Should().Be(_issuer.Issuer); + witness.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_issuer.Issuer, Subject)); + witness.Acr.Should().Be("mfa"); + witness.Executor.Should().Be(PlatformOperatorSettings.RebindToolExecutor); + witness.CorrelationId.Should().Be(Correlation); + } + + [Theory] + [InlineData(null, "token_missing")] + [InlineData("", "token_missing")] + [InlineData(" ", "token_missing")] + [InlineData("not-a-token", "token_invalid")] + [InlineData("a.b.c", "token_invalid")] + public async Task A_Missing_Or_Malformed_Token_Is_Refused_With_One_Closed_Label(string? token, string cause) + { + var result = await _validator.ValidateAsync(token, PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse(); + result.Cause.Should().Be(cause); + } + + [Fact] + public async Task A_Token_Over_The_Length_Bound_Is_Refused_Without_Being_Parsed() + { + var result = await _validator.ValidateAsync( + new string('a', PlatformOperatorTokenValidator.MaximumTokenCharacters + 1), + PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.Cause.Should().Be("token_invalid"); + } + + [Fact] + public async Task Each_Cryptographic_Failure_Has_Its_Own_Closed_Label() + { + (await Validate(Sign(("aud", "learnstack-api")))).Cause.Should().Be("token_audience", "the wrong audience"); + (await Validate(Sign(("iss", "https://elsewhere.example.test/realms/x")))).Cause.Should().Be("token_issuer", "another issuer"); + (await Validate(Sign(("exp", DateTimeOffset.UtcNow.AddHours(-1).ToUnixTimeSeconds())))).Cause.Should().Be("token_expired", "an expired token"); + (await Validate(_issuer.Token(Payload([]), key: _issuer.NewKey()))).Cause.Should().Be("token_signature", "a key the issuer never published"); + (await Validate(_issuer.Token(Payload([]), header: Header("at+jwt")))).Cause.Should().Be("token_type", "another token type"); + } + + [Fact] + public async Task Each_Profile_Failure_Has_Its_Own_Closed_Label() + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + (await Validate(Sign(("azp", "learnstack-web")))).Cause.Should().Be("profile_azp", "a client the profile does not allow"); + (await Validate(Sign(("acr", "pwd")))).Cause.Should().Be("profile_acr", "an assurance the profile does not accept"); + (await Validate(SignWithout("acr"))).Cause.Should().Be("profile_acr", "no assurance claim"); + (await Validate(SignWithout("auth_time"))).Cause.Should().Be("profile_auth_time", "no authentication time"); + (await Validate(Sign(("auth_time", now - 7200)))).Cause.Should().Be("profile_auth_age", "an authentication older than the configured age"); + (await Validate(Sign(("exp", now + 7200)))).Cause.Should().Be("profile_lifetime", "a lifetime above fifteen minutes"); + (await Validate(Sign(("sub", "")))).Cause.Should().Be("profile_subject", "a blank subject"); + } + + [Fact] + public async Task An_Unreachable_Issuer_Refuses_The_Operator_Rather_Than_Trusting_A_Key_It_Never_Read() + { + await using var down = await TenantAuthenticationIssuer.StartAsync(); + down.DiscoveryStatusCode = 500; + using var backchannel = new PlatformOperatorBackchannel(); + var validator = ValidatorFor(down, backchannel); + + var result = await validator.ValidateAsync( + down.Token(Payload([], down)), PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse(); + result.Cause.Should().Be("metadata_unavailable"); + } + + [Fact] + public async Task A_Discovery_Document_That_Names_Another_Issuer_Is_Refused() + { + await using var misbehaving = await TenantAuthenticationIssuer.StartAsync(); + // Only the document's own issuer property differs: the key set and the endpoints stay at the issuer's origin. + var document = JsonNode.Parse(misbehaving.DiscoveryDocument)!.AsObject(); + document["issuer"] = "https://elsewhere.example.test/realms/x"; + misbehaving.DiscoveryResponse = document.ToJsonString(); + using var backchannel = new PlatformOperatorBackchannel(); + var validator = ValidatorFor(misbehaving, backchannel); + + var result = await validator.ValidateAsync( + misbehaving.Token(Payload([], misbehaving)), PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse("a discovery issuer other than the pinned one is never trusted"); + result.Cause.Should().Be("metadata_unavailable", "the configuration validator refuses it, not a missing key"); + } + + [Fact] + public async Task A_Key_Set_At_Another_Origin_Is_Refused() + { + await using var foreign = await TenantAuthenticationIssuer.StartAsync(); + await using var misbehaving = await TenantAuthenticationIssuer.StartAsync(); + // A live key set at another origin: a reader that followed it would succeed, so refusing is the control. + var document = JsonNode.Parse(misbehaving.DiscoveryDocument)!.AsObject(); + document["jwks_uri"] = foreign.Issuer + "/keys"; + misbehaving.DiscoveryResponse = document.ToJsonString(); + using var backchannel = new PlatformOperatorBackchannel(); + var validator = ValidatorFor(misbehaving, backchannel); + + var result = await validator.ValidateAsync( + misbehaving.Token(Payload([], misbehaving)), PlatformOperatorSettings.RebindToolExecutor, Correlation); + + result.IsValid.Should().BeFalse(); + foreign.JwksRequests.Should().Be(0, "the other origin is never called"); + } + + [Theory] + [InlineData("operator.other")] + [InlineData("")] + [InlineData("operator.api ")] + public async Task An_Executor_That_Is_Not_One_Of_The_Two_Registered_Constants_Is_Refused_Before_Any_Token_Is_Read(string executor) + { + var act = async () => await _validator.ValidateAsync(Sign(), executor, Correlation); + + await act.Should().ThrowAsync(); + } + + [Fact] + public void The_Tenant_Issuer_Key_The_Settings_Refuse_Is_The_Key_The_Tenant_Scheme_Reads() + { + PlatformOperatorSettings.TenantIssuerConfigurationKey.Should().Be( + LearnStack.Api.Authentication.TenantAuthenticationOptions.IssuerConfigurationKey); + } + + private Task Validate(string token) => + _validator.ValidateAsync(token, PlatformOperatorSettings.RebindToolExecutor, Correlation); + + private PlatformOperatorTokenValidator ValidatorFor(TenantAuthenticationIssuer issuer, PlatformOperatorBackchannel? backchannel = null) + { + var settings = PlatformOperatorSettings.FromConfiguration( + new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["PlatformOperator:Issuer"] = issuer.Issuer, + ["PlatformOperator:AuthorizedParties:0"] = "learnstack-operator", + ["PlatformOperator:AcceptedAcr:0"] = "mfa", + }).Build(), + DeploymentMode.Development)!; + var health = new PlatformOperatorMetadataHealth(new SystemClock()); + var manager = PlatformOperatorValidation.CreateConfigurationManager( + settings, backchannel ?? _backchannel, health, NullLoggerFactory.Instance); + return new PlatformOperatorTokenValidator(settings, manager, health, new SystemClock()); + } + + private string Sign(params (string Name, object? Value)[] replacements) => _issuer.Token(Payload(replacements)); + + private string SignWithout(string name) + { + using var baseline = JsonDocument.Parse(Payload([])); + return _issuer.Token("{" + string.Join(",", baseline.RootElement.EnumerateObject() + .Where(property => property.Name != name) + .Select(property => JsonSerializer.Serialize(property.Name) + ":" + property.Value.GetRawText())) + "}"); + } + + private string Payload((string Name, object? Value)[] replacements, TenantAuthenticationIssuer? issuer = null) + { + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var claims = new Dictionary(StringComparer.Ordinal) + { + ["iss"] = (issuer ?? _issuer).Issuer, + ["sub"] = Subject, + ["aud"] = "learnstack-platform", + ["iat"] = now - 5, + ["exp"] = now + 600, + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["auth_time"] = now - 30, + }; + foreach (var (name, value) in replacements) + { + claims[name] = value; + } + + return JsonSerializer.Serialize(claims); + } + + private string Header(string type) => + JsonSerializer.Serialize(new { alg = "RS256", typ = type, kid = _issuer.CurrentKey.Kid }); +} diff --git a/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs b/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs new file mode 100644 index 000000000..743668692 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/RebindToolInputTests.cs @@ -0,0 +1,214 @@ +using System.Diagnostics.Metrics; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tools.IdentityAuthorityRebind; +using Microsoft.Extensions.Configuration; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// What the tool accepts from its environment and one line of standard input (ADR-0104 § 3), and what it refuses +/// without saying why: a refusal names no value, so a mistake cannot echo a secret. +/// +public sealed class RebindToolInputTests +{ + private const string Authority = "019a1929-5450-7bbb-8df1-516e8e002501"; + + private static Dictionary Valid() => new() + { + ["ConnectionStrings__IdentityRebind"] = "Host=db.example;Database=learnstack;Username=learnstack_identity_rebind;Password=x", // leakwatch:ignore:database-connection-string + ["Identity__AuthorityId"] = Authority, + ["Authentication__Tenant__Issuer"] = "https://new.example.test/realms/learnstack", + ["Deployment__Mode"] = "SaaS", + ["LEARNSTACK_OPERATOR_TOKEN"] = " header.payload.signature ", + ["LEARNSTACK_REBIND_REALM_CLIENT_ID"] = "reader", + ["LEARNSTACK_REBIND_REALM_CLIENT_SECRET"] = "secret-value", + }; + + private static bool Read(Dictionary environment, out RebindToolInput? input, string? line = null) => + Read(environment, out input, out _, line); + + private static bool Read(Dictionary environment, out RebindToolInput? input, out string field, string? line = null) => + RebindToolInput.TryRead(name => environment.GetValueOrDefault(name), () => line, + new ConfigurationBuilder().Build(), out input, out field); + + [Fact] + public void A_Complete_Environment_Is_Read_And_The_Token_Is_Trimmed() + { + Read(Valid(), out var input).Should().BeTrue(); + + input!.OperatorToken.Should().Be("header.payload.signature"); + input.Target.AuthorityId.Value.Should().Be(Guid.Parse(Authority)); + input.Target.Issuer.Should().Be("https://new.example.test/realms/learnstack"); + input.Ticket.Should().BeNull(); + input.Mode.Should().Be(LearnStack.SharedKernel.Hosting.DeploymentMode.SaaS); + } + + [Theory] + [InlineData("ConnectionStrings__IdentityRebind", "connection_string")] + [InlineData("Identity__AuthorityId", "authority_id")] + [InlineData("Authentication__Tenant__Issuer", "issuer")] + [InlineData("Deployment__Mode", "deployment_mode")] + [InlineData("LEARNSTACK_OPERATOR_TOKEN", "operator_token")] + [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_ID", "realm_client")] + [InlineData("LEARNSTACK_REBIND_REALM_CLIENT_SECRET", "realm_client")] + public void Each_Required_Value_Missing_Refuses_Naming_Only_The_Setting(string missing, string field) + { + var environment = Valid(); + environment.Remove(missing); + + Read(environment, out _, out var named).Should().BeFalse(); + named.Should().Be(field); + RebindToolInput.Fields.All.Should().Contain(named, "the name is one of the closed set the runbook lists"); + } + + [Fact] + public void The_Closed_Field_Names_Are_Distinct_Lowercase_Tokens() + { + RebindToolInput.Fields.All.Should().OnlyHaveUniqueItems() + .And.OnlyContain(name => name.All(character => char.IsAsciiLetterLower(character) || character == '_')); + } + + [Theory] + [InlineData("0")] + [InlineData("1")] + [InlineData("Development,SaaS")] + [InlineData("Production")] + [InlineData("")] + public void The_Deployment_Mode_Is_A_Declared_Name_And_Never_An_Ordinal_Or_A_List(string mode) + { + var environment = Valid(); + environment["Deployment__Mode"] = mode; + + Read(environment, out _, out var field).Should().BeFalse("the API refuses ordinals and lists, so the tool must not guess a mode"); + field.Should().Be("deployment_mode"); + } + + [Theory] + [InlineData("development", LearnStack.SharedKernel.Hosting.DeploymentMode.Development)] + [InlineData("saas", LearnStack.SharedKernel.Hosting.DeploymentMode.SaaS)] + [InlineData(" SaaS ", LearnStack.SharedKernel.Hosting.DeploymentMode.SaaS)] + [InlineData("SELFHOSTEDAIRGAPPED", LearnStack.SharedKernel.Hosting.DeploymentMode.SelfHostedAirGapped)] + public void The_Deployment_Mode_Is_Read_The_Way_The_Api_Reads_It_Without_Regard_To_Case_Or_Padding( + string mode, LearnStack.SharedKernel.Hosting.DeploymentMode expected) + { + var environment = Valid(); + environment["Deployment__Mode"] = mode; + environment["Authentication__Tenant__Issuer"] = "https://new.example.test/realms/learnstack"; + + Read(environment, out var input).Should().BeTrue("an API started with this spelling accepts it, so the tool must too"); + input!.Mode.Should().Be(expected); + } + + [Theory] + [InlineData("not-a-guid")] + [InlineData("00000000-0000-0000-0000-000000000000")] + [InlineData("019a192954507bbb8df1516e8e002501")] + public void The_Authority_Must_Be_A_Nonempty_Hyphenated_Guid(string authority) + { + var environment = Valid(); + environment["Identity__AuthorityId"] = authority; + + Read(environment, out _).Should().BeFalse(); + } + + [Theory] + [InlineData("learnstack_app")] + [InlineData("learnstack_migration")] + [InlineData("learnstack_platform")] + public void Only_The_Rebind_Role_Is_Accepted_In_The_Connection_String(string role) + { + var environment = Valid(); + environment["ConnectionStrings__IdentityRebind"] = $"Host=db.example;Database=learnstack;Username={role};Password=x"; // leakwatch:ignore:database-connection-string + + Read(environment, out _).Should().BeFalse(); + } + + [Theory] + [InlineData("http://localhost:8080/realms/learnstack", "SaaS", false)] + [InlineData("http://localhost:8080/realms/learnstack", "SelfHostedOnline", false)] + [InlineData("http://localhost:8080/realms/learnstack", "Development", true)] + [InlineData("http://new.example.test/realms/learnstack", "Development", false)] + [InlineData("https://new.example.test/realms/learnstack", "Dedicated", true)] + [InlineData("https://new.example.test/realms/other", "Dedicated", false)] + [InlineData("https://new.example.test/realms/learnstack?x=1", "Dedicated", false)] + public void The_Target_Issuer_Follows_The_Grammar_And_Loopback_Http_Is_Development_Only(string issuer, string mode, bool accepted) + { + var environment = Valid(); + environment["Authentication__Tenant__Issuer"] = issuer; + environment["Deployment__Mode"] = mode; + + Read(environment, out _).Should().Be(accepted); + } + + [Fact] + public void The_Printed_Line_Names_The_Detail_After_The_Correlation_And_Before_The_Counts() + { + var line = RebindTool.Line( + new IdentityRebindOutcome(IdentityRebindResult.Refused, IdentityRebindRefusal.RoleInvalid, null, 2, IdentityRebindDetail.RoleGrants), + "rebind-abc"); + + line.Should().Be("rebind: outcome=refused_role_invalid correlation=rebind-abc detail=role_grants sessions=2"); + RebindTool.Line(new IdentityRebindOutcome(IdentityRebindResult.AlreadyApplied), "rebind-abc") + .Should().Be("rebind: outcome=already_applied correlation=rebind-abc", "a class with one cause carries no detail"); + } + + [Fact] + public void A_Refusal_Before_The_Database_Is_Printed_And_Counted_Under_The_Same_Label() + { + var seen = new System.Collections.Concurrent.ConcurrentBag(); + using var listener = new MeterListener(); + listener.InstrumentPublished = (instrument, subscriber) => + { + if (instrument.Meter.Name == IdentityRebindMetrics.MeterName) subscriber.EnableMeasurementEvents(instrument); + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag.Key == "outcome") seen.Add((string)tag.Value!); + } + }); + listener.Start(); + var output = new StringWriter(); + + RebindTool.RefuseInput(output, RebindToolInput.Fields.ConnectionString).Should().Be(RebindTool.Refused); + RebindTool.Refuse(output, "operator_missing_permission", "rebind-abc").Should().Be(RebindTool.Refused); + + output.ToString().Replace("\r", string.Empty).Split('\n', StringSplitOptions.RemoveEmptyEntries).Should().Equal( + "rebind: outcome=refused_input detail=connection_string", + "rebind: outcome=refused_operator_missing_permission correlation=rebind-abc"); + // The meter is process-wide and other cases record on it too, so the labels are looked for, not counted. + seen.Should().Contain(["refused_input", "refused_operator_missing_permission"]); + } + + [Fact] + public void The_Token_Falls_Back_To_One_Line_Of_Standard_Input_And_Never_To_An_Argument() + { + var environment = Valid(); + environment.Remove("LEARNSTACK_OPERATOR_TOKEN"); + + Read(environment, out var input, line: " piped.token.value ").Should().BeTrue(); + input!.OperatorToken.Should().Be("piped.token.value"); + Read(environment, out _, line: " ").Should().BeFalse(); + Read(environment, out _, line: null).Should().BeFalse(); + } + + [Fact] + public void A_Token_Over_The_Length_Bound_Refuses_And_A_Blank_Ticket_Is_No_Ticket() + { + var environment = Valid(); + environment["LEARNSTACK_OPERATOR_TOKEN"] = new string('a', 16 * 1024 + 1); + Read(environment, out _).Should().BeFalse(); + + environment["LEARNSTACK_OPERATOR_TOKEN"] = "a.b.c"; + environment["LEARNSTACK_REBIND_TICKET"] = " "; + Read(environment, out var input).Should().BeTrue(); + input!.Ticket.Should().BeNull(); + + environment["LEARNSTACK_REBIND_TICKET"] = "CHG-104"; + Read(environment, out input).Should().BeTrue(); + input!.Ticket.Should().Be("CHG-104"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs b/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs index bd2a6f87b..69da411e9 100644 --- a/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/SeedOperationSourceTests.cs @@ -3,6 +3,7 @@ using LearnStack.Application.Authorization; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Localization; using LearnStack.Application.Pipeline; @@ -46,6 +47,34 @@ public async Task Canonical_slot_five_refuses_an_unclassified_request_before_its scope.ServiceProvider.GetRequiredService().HasActiveTransaction.Should().BeFalse(); } + [Fact] + public async Task The_seed_source_does_not_admit_an_operator_act_before_its_handler() + { + // ADR-0102 § 1: neither source is sufficient for the other's request. The seed composition mints no + // operator descriptor, so an operator command sent through it is refused by the policy it names + // before any handler, transaction or database connection. + await using var data = Source(); + await using var provider = SeedComposition.Build(data, + new SeedTenantContext(TenantId.From(Guid.CreateVersion7()), null), NullLoggerFactory.Instance); + await using var scope = provider.CreateAsyncScope(); + var behavior = scope.ServiceProvider + .GetServices>>() + .OfType>>().Single(); + var entered = false; + var command = new OperatorProvisionTenantCommand( + TenantId.From(Guid.CreateVersion7()), "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + var result = await behavior.Handle(command, () => + { + entered = true; + return Task.FromResult(Result.Fail(new Error(new LocalizedMessage("lockey_forbidden")))); + }, CancellationToken.None); + + result.Error!.Code.Should().Be("forbidden"); + entered.Should().BeFalse("a seed descriptor, or none, is not an operator act"); + scope.ServiceProvider.GetRequiredService().HasActiveTransaction.Should().BeFalse(); + } + [Fact] public async Task An_attributable_finite_seed_refusal_cannot_claim_durability_without_a_shared_evidence_factory() { diff --git a/backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs b/backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs new file mode 100644 index 000000000..cf4ce33fa --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/SeederDevelopmentOnlyTests.cs @@ -0,0 +1,86 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Tools.Seeder; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The seeder is a development capability (ADR-0102 § 10): started anywhere but a Development +/// deployment it refuses before it reads a credential or opens a connection. +/// +/// +/// No Docker and no database: the process is given no connection string at all, so a run that did anything +/// but refuse would exit with the missing-credential code instead. +/// +public sealed class SeederDevelopmentOnlyTests +{ + [Theory] + [InlineData("Production")] + [InlineData("Dedicated")] + [InlineData("SelfHosted")] + [InlineData("development")] + [InlineData("")] + [InlineData(null)] + public async Task The_Seeder_Refuses_Outside_A_Development_Deployment_Before_Reading_A_Credential(string? mode) + { + var (exit, errors) = await RunAsync(mode); + + exit.Should().Be(2); + errors.Should().Contain("only when Deployment__Mode is Development").And.Contain("operator surface"); + } + + [Fact] + public async Task In_A_Development_Deployment_The_Refusal_Is_Not_The_Answer() + { + // With the mode right and no credential the seeder reaches its own missing-credential exit, which is + // how this case shows the refusal is the mode's and not a blanket one. + var (exit, errors) = await RunAsync("Development"); + + exit.Should().Be(2); + errors.Should().NotContain("only when Deployment__Mode is Development"); + errors.Should().Contain("ConnectionStrings__Default"); + } + + private static async Task<(int Exit, string Errors)> RunAsync(string? mode) + { + var start = new ProcessStartInfo("dotnet") + { + WorkingDirectory = AppContext.BaseDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.deps.json")); + start.ArgumentList.Add(typeof(SeedRunner).Assembly.Location); + start.Environment.Remove("ConnectionStrings__Default"); + start.Environment.Remove("Deployment__Mode"); + if (mode is not null) + { + start.Environment["Deployment__Mode"] = mode; + } + + using var process = new Process { StartInfo = start }; + process.Start().Should().BeTrue(); + var output = process.StandardOutput.ReadToEndAsync(); + var errors = process.StandardError.ReadToEndAsync(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + try + { + await process.WaitForExitAsync(deadline.Token); + } + finally + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + } + + await Task.WhenAll(output, errors); + return (process.ExitCode, await errors); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs new file mode 100644 index 000000000..942aa9ab4 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/FederationProviderTests.Operator.cs @@ -0,0 +1,216 @@ +using System.Net; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.Identity.Federation; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using Polly; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// ADR-0099 Amendment 10 against the pinned provider: the operator's listing, inspection, remove and disable through the +/// same confined admin client, which holds manage-identity-providers and nothing wider. Each case builds its own +/// brokers and removes them, so the realm the other cases share ends as it began. +/// +public sealed partial class FederationProviderTests +{ + private KeycloakFederationProvider OperatorAdapter() => + new(new KeycloakFederationOptions(Keycloak.Issuer), new Secrets(KeycloakFixture.FederationAdminSecret), new OperatorResilience(), + KeycloakHttp.CreateHandler(Keycloak.RootCertificate)); + + private sealed class OperatorResilience : IProviderResilience + { + public ResiliencePipeline Pipeline => ResiliencePipeline.Empty; + public string PortName => "federation"; + } + + private async Task OwnedBrokerAsync(KeycloakFederationProvider tenant, bool unreadable) + { + var owner = FederationKeycloakFixture.Owner(); + (await tenant.ApplyAsync(new(Oidc(owner, "federation-idp-a", enabled: true), Secret(FederationKeycloakFixture.IdpSecretA)))) + .Should().Be(FederationProviderResult.Applied); + if (unreadable) + { + // Out of band, as an operator in the provider's own console might: the broker keeps its marker and loses its issuer. + using var admin = await Keycloak.CreateAdminClientAsync(); + var damaged = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + owner.Alias)).GetRawText())!.AsObject(); + damaged["config"]!.AsObject().Remove("issuer"); + (await admin.PutAsync("identity-provider/instances/" + owner.Alias, damaged)).Should().Be(HttpStatusCode.NoContent); + } + + return owner; + } + + [Fact] + public async Task The_operator_lists_the_realm_in_bounded_pages_and_classifies_owned_unreadable_and_foreign_instances() + { + using var tenant = Adapter(); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + var healthy = await OwnedBrokerAsync(tenant, unreadable: false); + var broken = await OwnedBrokerAsync(tenant, unreadable: true); + var unmarked = FederationKeycloakFixture.Owner(); + var manual = KeycloakFederationProfile.Representation(Oidc(unmarked, "federation-idp-a", enabled: true), Secret(FederationKeycloakFixture.IdpSecretA)); + manual["config"]!.AsObject().Remove(KeycloakFederationProfile.OwnerKey); + (await admin.PostAsync("identity-provider/instances", manual)).Should().Be(HttpStatusCode.Created); + try + { + var owned = new Dictionary(StringComparer.Ordinal); + var seen = new List(); + var ignored = 0; + var scanned = 0; + for (var offset = 0; ; offset += 2) + { + var page = await op.ListAsync(offset, 2); + page.Status.Should().Be(FederationOperatorStatus.Ok, "the federation client's one role is enough to list"); + page.Scanned.Should().BeLessThanOrEqualTo(2); + foreach (var facts in page.Owned) + { + owned[facts.Owner.Alias] = facts; + seen.Add(facts.Owner.Alias); + } + + ignored += page.Ignored; + scanned += page.Scanned; + if (page.Scanned < 2) break; + } + + // The pages are disjoint and complete: nothing is listed twice, and every instance the realm holds is scanned once. + seen.Should().OnlyHaveUniqueItems("offset paging must not repeat an instance across pages"); + scanned.Should().Be((await admin.GetAsync("identity-provider/instances")).GetArrayLength()); + + owned[healthy.Alias].Should().Match(facts => facts.Readable && facts.Conforms && facts.Enabled, + "the pinned provider masks the secret in the listing, so a healthy broker reads as conforming"); + owned[broken.Alias].Should().Match(facts => !facts.Readable && !facts.Conforms); + owned.Should().NotContainKey(unmarked.Alias, "an unmarked instance is never reported"); + ignored.Should().BeGreaterThanOrEqualTo(1); + owned.Values.Should().OnlyContain(facts => facts.Owner.Alias.StartsWith("lsf-", StringComparison.Ordinal)); + + var inspection = await op.InspectAsync(healthy.Alias); + (inspection.Status, inspection.Facts!.Owner.TenantId, inspection.MapperCount).Should().Be((FederationInspectionStatus.Owned, healthy.TenantId, 0)); + (await op.InspectAsync(unmarked.Alias)).Should().Be(FederationBrokerInspection.NotOwned); + (await op.InspectAsync(FederationKeycloakFixture.Owner().Alias)).Should().Be(FederationBrokerInspection.Absent); + } + finally + { + foreach (var alias in new[] { healthy.Alias, broken.Alias, unmarked.Alias }) + await admin.DeleteAsync("identity-provider/instances/" + alias); + } + } + + [Fact] + public async Task The_operator_removes_an_unreadable_orphan_and_the_provider_deletes_its_federated_links_and_nothing_else() + { + using var tenant = Adapter(); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + var broken = await OwnedBrokerAsync(tenant, unreadable: true); + var unmarked = FederationKeycloakFixture.Owner(); + var manual = KeycloakFederationProfile.Representation(Oidc(unmarked, "federation-idp-a", enabled: true), Secret(FederationKeycloakFixture.IdpSecretA)); + manual["config"]!.AsObject().Remove(KeycloakFederationProfile.OwnerKey); + (await admin.PostAsync("identity-provider/instances", manual)).Should().Be(HttpStatusCode.Created); + var user = await admin.UserAsync("demo-learner@tenant-a.test"); + var userId = user.GetProperty("id").GetString()!; + (await admin.PostAsync($"users/{userId}/federated-identity/{broken.Alias}", new JsonObject { ["userId"] = "external-1", ["userName"] = "external-1" })) + .Should().Be(HttpStatusCode.NoContent, "a link exists to be lost"); + (await admin.GetAsync($"users/{userId}/federated-identity")).GetArrayLength().Should().BeGreaterThan(0); + try + { + // The tenant adapter will not touch an unreadable broker; the operator removes it on its marker alone. + (await tenant.DeleteAsync(broken)).Should().Be(FederationProviderResult.Foreign); + var stored = (await admin.GetAsync("identity-provider/instances/" + unmarked.Alias)).GetRawText(); + + // The owner removes a broker a live row names only while it is unreadable and disabled, proved at the delete: this one + // is unreadable but still enabled, so the provider refuses and nothing is deleted. Disabled, it is removed. + (await op.RemoveAsync(broken, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Refused); + (await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetProperty("alias").GetString().Should().Be(broken.Alias); + (await op.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + (await op.RemoveAsync(broken, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Applied); + + (await admin.GetAsync("identity-provider/instances")).EnumerateArray() + .Select(instance => instance.GetProperty("alias").GetString()).Should().NotContain(broken.Alias); + (await admin.GetAsync($"users/{userId}/federated-identity")).EnumerateArray() + .Select(link => link.GetProperty("identityProvider").GetString()).Should().NotContain(broken.Alias, + "the provider deletes the federated links with the broker, which is why an account review is owed"); + (await admin.GetAsync($"users/{userId}")).GetProperty("id").GetString().Should().Be(userId, "the account itself stays"); + (await op.RemoveAsync(broken)).Should().Be(FederationOperatorOutcome.AlreadyApplied); + // Dirty control: a derived alias with no marker is never deleted, and stays as it was found. + var other = new FederationBrokerOwner(unmarked.TenantId, unmarked.ConnectionId, unmarked.Alias); + (await op.RemoveAsync(other)).Should().Be(FederationOperatorOutcome.NotOwned); + JsonNode.DeepEquals(JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + unmarked.Alias)).GetRawText()), + JsonNode.Parse(stored)).Should().BeTrue(); + } + finally + { + foreach (var alias in new[] { broken.Alias, unmarked.Alias }) + await admin.DeleteAsync("identity-provider/instances/" + alias); + } + } + + [Fact] + public async Task The_operator_disables_an_unreadable_broker_by_sending_back_what_the_provider_returned_with_only_enabled_changed() + { + using var tenant = Adapter(); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + var broken = await OwnedBrokerAsync(tenant, unreadable: true); + try + { + var before = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetRawText())!.AsObject(); + + (await op.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + var after = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + broken.Alias)).GetRawText())!.AsObject(); + after["enabled"]!.GetValue().Should().BeFalse(); + // The administrative read masks the secret whether or not it was kept, so this asserts the shape only; the next + // test proves the secret was kept, by signing a person in through the broker afterwards. + after["config"]!["clientSecret"]!.GetValue().Should().Be(FederationClientSecret.MaskLiteral); + // Nothing else moved: compare everything the provider computes on each read away. + foreach (var key in new[] { "internalId", "types" }) + { + before.Remove(key); + after.Remove(key); + } + + before["enabled"] = false; + JsonNode.DeepEquals(after, before).Should().BeTrue("only enabled differs from what the provider held"); + (await op.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.AlreadyApplied); + } + finally + { + await admin.DeleteAsync("identity-provider/instances/" + broken.Alias); + } + } + + [Fact] + public async Task The_operator_disable_keeps_the_stored_secret_so_a_person_can_sign_in_through_the_broker_once_it_is_enabled_again() + { + var owner = federation.OwnerA; + await EnableAsync(owner, "federation-idp-a", FederationKeycloakFixture.IdpSecretA); + using var op = OperatorAdapter(); + using var admin = await Keycloak.CreateAdminClientAsync(); + const string person = "demo-admin@tenant-a.test"; + + // Control: the broker reaches the link confirmation, which needs its client secret at the identity provider. + using (var before = Keycloak.Browser()) + (await before.BrokeredAuthorizeAsync(owner.Alias, person, KeycloakFixture.IdentityProviderPassword, null, null, Callback, + confirmLink: false)).Stop.Should().Be(BrokeredStop.ConfirmationAbandoned); + + (await op.DisableAsync(owner)).Should().Be(FederationOperatorOutcome.Applied); + using (var disabled = Keycloak.Browser()) + (await disabled.BrokeredAuthorizeAsync(owner.Alias, person, KeycloakFixture.IdentityProviderPassword, null, null, Callback, + confirmLink: false)).Stop.Should().NotBe(BrokeredStop.ConfirmationAbandoned, "a disabled broker signs nobody in"); + + // Enabled again out of band, with the representation the provider returns and its mask. If the operator's write had + // stored the mask literal as the secret, this write would keep it so, and the sign-in below could not succeed. + var returned = JsonNode.Parse((await admin.GetAsync("identity-provider/instances/" + owner.Alias)).GetRawText())!.AsObject(); + returned["enabled"] = true; + (await admin.PutAsync("identity-provider/instances/" + owner.Alias, returned)).Should().Be(HttpStatusCode.NoContent); + using var after = Keycloak.Browser(); + (await after.BrokeredAuthorizeAsync(owner.Alias, person, KeycloakFixture.IdentityProviderPassword, null, null, Callback, + confirmLink: false)).Stop.Should().Be(BrokeredStop.ConfirmationAbandoned, "the stored secret survived the disable"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs index 187c1cb9a..470796efd 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakBrowserFlow.cs @@ -115,7 +115,7 @@ internal async Task CompleteBffLogoutAsync(Uri logout) internal async Task AuthorizeAsync(string username, string password, string redirectUri, KeycloakPkce pkce = KeycloakPkce.S256, string clientId = "learnstack-web", string scope = "openid profile email", - Func>? otpCode = null) + Func>? otpCode = null, IReadOnlyDictionary? extraQuery = null) { var state = RandomValue(); var verifier = RandomValue(); @@ -129,6 +129,8 @@ internal async Task AuthorizeAsync(string username, strin ["state"] = state, ["nonce"] = nonce, }; + if (extraQuery is not null) + foreach (var (name, value) in extraQuery) query[name] = value; if (pkce != KeycloakPkce.Missing) { query["code_challenge"] = pkce == KeycloakPkce.Plain ? verifier diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs new file mode 100644 index 000000000..58036d39a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakEnumerationTests.cs @@ -0,0 +1,136 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Tests.Integration.Database; +using LearnStack.Tools.IdentityAuthorityRebind; +using Microsoft.IdentityModel.JsonWebTokens; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// The tool's reader of the new realm against the pinned Keycloak (ADR-0104 § 6): its discovery issuer, its key set, +/// the user count, the paging past one page, and that a user's id is the sub its tokens carry. +/// +/// +/// drives the failure modes on purpose; this is the other half, the +/// shape and the arithmetic of the real administration API, which a fake only imitates. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class KeycloakEnumerationTests : IAsyncLifetime +{ + private const string ReaderClient = "rebind-view-users-reader"; + private const string ReaderSecret = "view-users-reader-secret-of-the-test"; + private const int ExtraUsers = 130; + + private KeycloakFixture _keycloak = null!; + + public async Task InitializeAsync() => _keycloak = await KeycloakFixture.StartAsync(); + + public async Task DisposeAsync() => await _keycloak.DisposeAsync(); + + [Fact] + public async Task The_Pinned_Realm_Is_Enumerated_Completely_Across_Pages_And_Its_Ids_Are_The_Token_Subjects() + { + using var admin = await _keycloak.CreateAdminClientAsync(); + var readerAccount = await CreateViewUsersReaderAsync(admin); + var created = await CreateUsersAsync(admin, ExtraUsers); + + using var client = KeycloakRealmContinuitySource.CreateClient(KeycloakHttp.CreateHandler(_keycloak.RootCertificate)); + var snapshot = await new KeycloakRealmContinuitySource(client, ReaderClient, ReaderSecret).ReadAsync(_keycloak.Issuer); + + snapshot.DiscoveredIssuer.Should().Be(_keycloak.Issuer, "the realm names its own issuer, which the proof requires to equal the target"); + snapshot.SigningKeyCount.Should().BeGreaterThan(0); + snapshot.Complete.Should().BeTrue("the pages add up to the count, and the count did not move while they were read"); + + // The independent read: every account the administration API lists in one request, by the test's own admin client. + var listed = await admin.GetAsync("users?first=0&max=1000&briefRepresentation=true"); + var expected = listed.EnumerateArray().Select(user => user.GetProperty("id").GetString()!).ToList(); + expected.Count.Should().BeGreaterThan(ExtraUsers, "the shipped realm's own users and the created ones"); + snapshot.Subjects.Should().BeEquivalentTo(expected); + snapshot.Subjects.Count.Should().BeGreaterThan(KeycloakRealmContinuitySource.PageSize, + "the enumeration crossed at least one page boundary"); + snapshot.Subjects.Should().Contain(created); + snapshot.Subjects.Should().NotContain(readerAccount, "a service account is not a person of the realm"); + + // The id is the sub: the service account's own token carries its user id as the subject. + var token = await AccessTokenAsync(client); + new JsonWebToken(token).Subject.Should().Be(readerAccount); + + // A credential without the role cannot read the realm: the administration API refuses it. + await CreateReaderClientAsync(admin, "rebind-no-role-reader", assignRole: false); + var refused = async () => await new KeycloakRealmContinuitySource(client, "rebind-no-role-reader", ReaderSecret) + .ReadAsync(_keycloak.Issuer); + await refused.Should().ThrowAsync(); + } + + /// The credential the runbook has the operator create: a confidential client with the one view-users role. + private static async Task CreateViewUsersReaderAsync(KeycloakAdminClient admin) => + await CreateReaderClientAsync(admin, ReaderClient, assignRole: true); + + private static async Task CreateReaderClientAsync(KeycloakAdminClient admin, string clientId, bool assignRole) + { + (await admin.PostAsync("clients", new + { + clientId, + protocol = "openid-connect", + publicClient = false, + serviceAccountsEnabled = true, + standardFlowEnabled = false, + directAccessGrantsEnabled = false, + secret = ReaderSecret, + })).Should().Be(HttpStatusCode.Created); + + var client = await admin.ClientAsync(clientId); + var account = (await admin.GetAsync("clients/" + client.GetProperty("id").GetString() + "/service-account-user")) + .GetProperty("id").GetString()!; + if (assignRole) + { + var management = await admin.ClientAsync("realm-management"); + var role = await admin.GetAsync("clients/" + management.GetProperty("id").GetString() + "/roles/view-users"); + (await admin.PostAsync( + "users/" + account + "/role-mappings/clients/" + management.GetProperty("id").GetString(), + new[] { role })).Should().Be(HttpStatusCode.NoContent); + } + + return account; + } + + private static async Task> CreateUsersAsync(KeycloakAdminClient admin, int count) + { + for (var index = 0; index < count; index++) + { + (await admin.PostAsync("users", new + { + username = $"enumeration-user-{index:D3}", + enabled = true, + email = $"enumeration-user-{index:D3}@example.test", + firstName = "Enumeration", + lastName = $"User{index:D3}", + })) + .Should().Be(HttpStatusCode.Created); + } + + // The realm may use the e-mail address as the username, so the created accounts are found by search. + var found = await admin.GetAsync("users?search=Enumeration&first=0&max=1000&briefRepresentation=true"); + var ids = found.EnumerateArray().Select(user => user.GetProperty("id").GetString()!).ToList(); + ids.Count.Should().Be(count, "every created account is found"); + return ids; + } + + private async Task AccessTokenAsync(HttpClient client) + { + using var response = await client.PostAsync( + new Uri(_keycloak.BaseAddress, "realms/learnstack/protocol/openid-connect/token"), + new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "client_credentials", + ["client_id"] = ReaderClient, + ["client_secret"] = ReaderSecret, + })); + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("access_token").GetString()!; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs index 034b78021..a3747579a 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs @@ -27,6 +27,7 @@ public sealed partial class KeycloakFixture : IAsyncLifetime, IAsyncDisposable private readonly string _adminPassword = Guid.NewGuid().ToString("N"); private readonly string _databasePassword = Guid.NewGuid().ToString("N"); private readonly string? _tenantRealmJson; + private readonly string? _hubRealmJson; private INetwork? _network; private PostgreSqlContainer? _database; private IContainer? _keycloak; @@ -36,7 +37,11 @@ public sealed partial class KeycloakFixture : IAsyncLifetime, IAsyncDisposable private bool _callbackTrust = true; public KeycloakFixture() { } - private KeycloakFixture(string? tenantRealmJson) => _tenantRealmJson = tenantRealmJson; + private KeycloakFixture(string? tenantRealmJson, string? hubRealmJson = null) + { + _tenantRealmJson = tenantRealmJson; + _hubRealmJson = hubRealmJson; + } internal Uri BaseAddress { get; private set; } = null!; // Set only after successful container startup. internal string Issuer => IssuerFor("learnstack"); @@ -50,9 +55,10 @@ internal static string CheckedRealm(string realm) => realm is "learnstack" or "l internal string CallbackCertificate => Encoding.ASCII.GetString(_tls!.CallbackCertificatePem); internal string CallbackPrivateKey => Encoding.ASCII.GetString(_tls!.CallbackPrivateKeyPem); - internal static async Task StartAsync(string? tenantRealmJson = null, bool callbackTrust = true) + internal static async Task StartAsync( + string? tenantRealmJson = null, bool callbackTrust = true, string? hubRealmJson = null) { - var fixture = new KeycloakFixture(tenantRealmJson) { _callbackTrust = callbackTrust }; + var fixture = new KeycloakFixture(tenantRealmJson, hubRealmJson) { _callbackTrust = callbackTrust }; await fixture.InitializeAsync(); return fixture; } @@ -98,7 +104,9 @@ public async Task InitializeAsync() diagnostics.Mark(stage); var tenantImport = _tenantRealmJson ?? await File.ReadAllTextAsync(RealmPath("learnstack"), startup.Token); tenantImport = ConfigureInvitationMailRealm(tenantImport); - var hubImport = await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token); + var hubImport = _hubRealmJson is null + ? await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token) + : Encoding.UTF8.GetBytes(_hubRealmJson); _keycloak = BuildProvider(tenantImport, hubImport, _callbackTrust); _keycloak.Created += (_, _) => { stage = "provider_created"; diagnostics.Mark(stage); }; _keycloak.Starting += (_, _) => { stage = "provider_starting"; diagnostics.Mark(stage); }; @@ -197,7 +205,9 @@ internal async Task RecreateWithCallbackTrustAsync() using var startup = new CancellationTokenSource(TimeSpan.FromMinutes(2)); var tenantImport = _tenantRealmJson ?? await File.ReadAllTextAsync(RealmPath("learnstack"), startup.Token); tenantImport = ConfigureInvitationMailRealm(tenantImport); - var hubImport = await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token); + var hubImport = _hubRealmJson is null + ? await File.ReadAllBytesAsync(RealmPath("learnstack-hub"), startup.Token) + : Encoding.UTF8.GetBytes(_hubRealmJson); await _keycloak.DisposeAsync(); _keycloak = null; _keycloak = BuildProvider(tenantImport, hubImport, callbackTrust: true, publicPort); @@ -312,16 +322,9 @@ internal async Task WriteReconciliationInputAsync(Stream destination, string sce await JsonSerializer.SerializeAsync(destination, input, JsonSerializerOptions.Web, cancellationToken); } - internal static string RealmPath(string realm) => Path.Combine(RepositoryRoot(), "infra", "keycloak", "realms", realm + ".json"); + internal static string RealmPath(string realm) => RealmFiles.RealmPath(realm); - private static string RepositoryRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !(File.Exists(Path.Combine(directory.FullName, "CLAUDE.md")) - && Directory.Exists(Path.Combine(directory.FullName, "infra", "keycloak", "realms")))) - directory = directory.Parent; - return directory?.FullName ?? throw new InvalidOperationException("Keycloak fixture repository root is missing."); - } + internal static string RepositoryRoot() => RealmFiles.RepositoryRoot(); public async Task DisposeAsync() { diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs new file mode 100644 index 000000000..8cab58ed4 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmFileTests.cs @@ -0,0 +1,49 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// Properties of the shipped operator realm export that need no running Keycloak (ADR-0101 § 3). +/// +/// +/// The behavioural proof against pinned Keycloak is . These +/// cases pin the settings whose effect is a refusal that cannot be provoked from a headless login. +/// +public sealed class PlatformOperatorRealmFileTests +{ + private static JsonObject Realm() => + JsonNode.Parse(File.ReadAllText(RealmFiles.RealmPath("learnstack-hub")))!.AsObject(); + + [Fact] + public void Password_Reset_Is_Off_So_No_Second_Path_To_A_Password_Skips_The_Second_Factor() => + Realm()["resetPasswordAllowed"]!.GetValue().Should().BeFalse(); + + [Fact] + public void The_Operator_Client_Is_Public_Pkce_With_No_Direct_Grant_And_No_Realm_Roles_In_Its_Token() + { + var client = Realm()["clients"]!.AsArray().Select(node => node!.AsObject()) + .Single(candidate => candidate["clientId"]!.GetValue() == "learnstack-operator"); + + client["publicClient"]!.GetValue().Should().BeTrue(); + client["standardFlowEnabled"]!.GetValue().Should().BeTrue(); + client["implicitFlowEnabled"]!.GetValue().Should().BeFalse(); + client["directAccessGrantsEnabled"]!.GetValue().Should().BeFalse(); + client["serviceAccountsEnabled"]!.GetValue().Should().BeFalse(); + client["fullScopeAllowed"]!.GetValue().Should().BeFalse(); + client["attributes"]!["pkce.code.challenge.method"]!.GetValue().Should().Be("S256"); + client["attributes"]!["access.token.lifespan"]!.GetValue().Should().Be("900"); + } + + [Fact] + public void The_Realm_Browser_Flow_Is_The_Step_Up_Flow_And_Its_Second_Level_Asks_For_The_Factor_Every_Time() + { + var realm = Realm(); + + realm["browserFlow"]!.GetValue().Should().Be("browser-loa"); + var level2 = realm["authenticatorConfig"]!.AsArray().Select(node => node!.AsObject()) + .Single(config => config["alias"]!.GetValue() == "loa-2"); + level2["config"]!["loa-max-age"]!.GetValue().Should().Be("0", "level 2 never rides an earlier session"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs new file mode 100644 index 000000000..f6e43007e --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/PlatformOperatorRealmTests.cs @@ -0,0 +1,250 @@ +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Hosting; +using LearnStack.Tests.Integration.Database; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.JsonWebTokens; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// What the pinned learnstack-hub realm actually issues to an operator, judged by the +/// same token profile the scheme and the rebind tool use (ADR-0101 § 2, § 3). +/// +/// +/// +/// A controlled issuer isolates protocol refusals in ; this +/// is the other half: the realm export, as shipped, emits an audience, a client, an acr +/// that shows the second factor, an auth_time and a lifetime inside the cap. A realm that +/// stopped doing any of these would pass every controlled-token case and fail here. +/// +/// +/// The shipped demo user must set up OTP at its first login, which a headless fixture cannot do, +/// so this case imports the same realm with that one user holding a known OTP credential. +/// Everything else is the file under infra/keycloak/realms. +/// +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class PlatformOperatorRealmTests : IAsyncLifetime +{ + private const string OtpSecret = "JBSWY3DPEHPK3PXP"; + private const string Redirect = "http://127.0.0.1:8765/callback"; + private const string OperatorClient = "learnstack-operator"; + + private KeycloakFixture _keycloak = null!; + + public async Task InitializeAsync() + { + var realm = JsonNode.Parse(await File.ReadAllTextAsync(KeycloakFixture.RealmPath("learnstack-hub")))!.AsObject(); + var user = realm["users"]!.AsArray()[0]!.AsObject(); + user["requiredActions"] = new JsonArray(); + // An operator created in the realm's console receives the realm's default roles, which carry the + // account console's `manage-account`. The shipped demo user omits them, so the fixture adds them + // to make the account-console cases below represent a normal operator account. + user["realmRoles"]!.AsArray().Add("default-roles-learnstack-hub"); + user["credentials"]!.AsArray().Add(new JsonObject + { + ["type"] = "otp", + ["userLabel"] = "fixture", + ["secretData"] = JsonSerializer.Serialize(new { value = OtpSecret }), + ["credentialData"] = JsonSerializer.Serialize(new + { + subType = "totp", + digits = 6, + period = 30, + algorithm = "HmacSHA1", + secretEncoding = "BASE32", + }), + }); + _keycloak = await KeycloakFixture.StartAsync(hubRealmJson: realm.ToJsonString()); + } + + public async Task DisposeAsync() => await _keycloak.DisposeAsync(); + + [Fact] + public async Task The_Operator_Client_Issues_A_Token_That_Meets_The_Operator_Profile() + { + var token = await OperatorTokenAsync(); + + token.Issuer.Should().Be(_keycloak.IssuerFor("learnstack-hub")); + token.Audiences.Should().Contain("learnstack-platform"); + token.GetPayloadValue("azp").Should().Be(OperatorClient); + token.Subject.Should().Be(LearnStack.Infrastructure.PlatformOperator.PlatformOperatorGrantOptions.DemoOperatorSubject, + "the export pins the demo operator's subject so a Development grant can name it"); + (new DateTimeOffset(token.ValidTo, TimeSpan.Zero) - DateTimeOffset.FromUnixTimeSeconds(token.GetPayloadValue("iat"))) + .Should().BeLessThanOrEqualTo(TimeSpan.FromMinutes(15), "the realm caps the operator client's access token"); + + var settings = Settings(token.GetPayloadValue("acr")); + PlatformOperatorTokenProfile.TryRead(token, settings, DateTimeOffset.UtcNow, PlatformOperatorSettings.Executor, null, out var witness, out _) + .Should().BeTrue("the token the realm issues is the token the scheme accepts"); + witness!.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(_keycloak.IssuerFor("learnstack-hub"), token.Subject)); + } + + [Fact] + public async Task The_Acr_Shows_The_Second_Factor_And_The_Shipped_Development_Config_Accepts_It() + { + var token = await OperatorTokenAsync(); + var acr = token.GetPayloadValue("acr"); + + var development = JsonDocument.Parse(await File.ReadAllTextAsync( + Path.Combine(KeycloakFixture.RepositoryRoot(), "backend", "src", "LearnStack.Api", "appsettings.Development.json"))); + var accepted = development.RootElement.GetProperty("PlatformOperator").GetProperty("AcceptedAcr") + .EnumerateArray().Select(value => value.GetString()).ToList(); + + accepted.Should().Contain(acr, "Development configuration accepts exactly what the realm emits for MFA"); + token.TryGetPayloadValue("auth_time", out _).Should().BeTrue(); + } + + [Fact] + public async Task A_Token_From_The_Portal_Client_Does_Not_Meet_The_Operator_Profile() + { + // The Hub portal client shares the realm and the user, but not the audience, the + // client allow-list or the step-up: it is not an operator credential for LearnStack. + using var browser = _keycloak.Browser("learnstack-hub"); + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, "http://localhost:3100/callback", + clientId: "learnstack-hub-web", otpCode: () => Task.FromResult(Totp())); + authorization.Authorized.Should().BeTrue(); + var exchange = await browser.RedeemAsync(authorization, secret: null); + exchange.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); + + var token = new JsonWebToken(exchange.AccessToken); + + token.Audiences.Should().NotContain("learnstack-platform"); + PlatformOperatorTokenProfile.TryRead(token, Settings("mfa"), DateTimeOffset.UtcNow, PlatformOperatorSettings.Executor, null, out _, out _) + .Should().BeFalse("a portal token carries neither the operator client nor the platform audience"); + } + + [Fact] + public async Task A_Password_Only_Session_Cannot_Remove_The_Second_Factor_Through_The_Account_Console() + { + // The realm's browser flow asks for the second factor only when a level of two is requested, and + // the account console asks for none, so a password alone opens a console session. If that session + // could delete the authenticator, anyone holding the password could remove it and then enrol their + // own at the next operator login. Pinned Keycloak refuses the removal; this keeps it that way. + using var browser = _keycloak.Browser("learnstack-hub"); + var redirect = new Uri(_keycloak.BaseAddress, "realms/learnstack-hub/account/").AbsoluteUri; + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, redirect, + clientId: "account-console", scope: "openid", otpCode: null); + authorization.Authorized.Should().BeTrue( + "premise: the console accepts a password alone, so the removal below is what is being judged"); + + var exchange = await browser.RedeemAsync(authorization, secret: null); + exchange.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); + using var client = KeycloakHttp.Create(_keycloak.BaseAddress, _keycloak.RootCertificate); + client.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", exchange.AccessToken); + client.DefaultRequestHeaders.Accept.ParseAdd("application/json"); + using var listing = await client.GetAsync("realms/learnstack-hub/account/credentials"); + listing.StatusCode.Should().Be(System.Net.HttpStatusCode.OK, "premise: the session can manage credentials at all"); + var otpIds = JsonNode.Parse(await listing.Content.ReadAsStringAsync())!.AsArray() + .SelectMany(group => group!["userCredentialMetadatas"]!.AsArray()) + .Select(metadata => metadata!["credential"]!) + .Where(credential => credential["type"]!.GetValue() == "otp") + .Select(credential => credential["id"]!.GetValue()) + .ToList(); + otpIds.Should().NotBeEmpty("premise: the fixture user has an authenticator to try to remove"); + + foreach (var id in otpIds) + { + using var removal = await client.DeleteAsync("realms/learnstack-hub/account/credentials/" + id); + removal.StatusCode.Should().NotBe(System.Net.HttpStatusCode.NoContent, + "a password-only console session must not remove the authenticator"); + } + } + + [Fact] + public async Task A_Password_Only_Login_Is_Asked_For_The_Existing_Factor_Before_A_New_Authenticator_Is_Offered() + { + // The other way round the second factor: an account-console login that asks, in the same request, + // to set up an authenticator. For an operator who already has one, pinned Keycloak asks for the + // existing code first. If the password alone reached the set-up form, whoever holds the password + // could enrol a device of their own and obtain `mfa`. + using var browser = _keycloak.Browser("learnstack-hub"); + var redirect = new Uri(_keycloak.BaseAddress, "realms/learnstack-hub/account/").AbsoluteUri; + + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, redirect, + clientId: "account-console", scope: "openid", otpCode: null, + extraQuery: new Dictionary { ["kc_action"] = "CONFIGURE_TOTP" }); + + authorization.Error.Should().NotBe("mfa_action_required", "the set-up form is not reachable with the password alone"); + authorization.Authorized.Should().BeFalse(); + authorization.MfaChallenged.Should().BeTrue("the existing authenticator is asked for first"); + } + + private async Task OperatorTokenAsync() + { + using var browser = _keycloak.Browser("learnstack-hub"); + var authorization = await browser.AuthorizeAsync( + "demo-operator@learnstack.test", KeycloakFixture.DemoPassword, Redirect, + clientId: OperatorClient, scope: "openid", otpCode: () => Task.FromResult(Totp())); + authorization.Authorized.Should().BeTrue("password, then the one-time password, completes the step-up"); + authorization.MfaChallenged.Should().BeTrue("the operator flow asks for the second factor on every login"); + var exchange = await browser.RedeemAsync(authorization, secret: null); + exchange.StatusCode.Should().Be(System.Net.HttpStatusCode.OK); + return new JsonWebToken(exchange.AccessToken); + } + + private PlatformOperatorSettings Settings(params string[] acr) + { + var values = new Dictionary + { + ["PlatformOperator:Issuer"] = _keycloak.IssuerFor("learnstack-hub"), + ["PlatformOperator:AuthorizedParties:0"] = OperatorClient, + }; + for (var index = 0; index < acr.Length; index++) + { + values[$"PlatformOperator:AcceptedAcr:{index}"] = acr[index]; + } + + return PlatformOperatorSettings.FromConfiguration( + new ConfigurationBuilder().AddInMemoryCollection(values).Build(), DeploymentMode.Development)!; + } + + /// RFC 6238, HMAC-SHA1, six digits, thirty seconds; the realm accepts one step either side. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", + Justification = "RFC 6238 TOTP is defined over HMAC-SHA1; this generates the fixture user's one-time code.")] + private static string Totp() + { + var key = Base32(OtpSecret); + var counter = DateTimeOffset.UtcNow.ToUnixTimeSeconds() / 30; + var message = BitConverter.GetBytes(counter); + if (BitConverter.IsLittleEndian) + { + Array.Reverse(message); + } + + var hash = HMACSHA1.HashData(key, message); + var offset = hash[^1] & 0x0F; + var binary = ((hash[offset] & 0x7F) << 24) | (hash[offset + 1] << 16) | (hash[offset + 2] << 8) | hash[offset + 3]; + return (binary % 1_000_000).ToString("D6", System.Globalization.CultureInfo.InvariantCulture); + } + + private static byte[] Base32(string value) + { + const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + var bytes = new List(); + var buffer = 0; + var bits = 0; + foreach (var character in value.TrimEnd('=')) + { + buffer = (buffer << 5) | alphabet.IndexOf(character, StringComparison.Ordinal); + bits += 5; + if (bits >= 8) + { + bytes.Add((byte)(buffer >> (bits - 8))); + bits -= 8; + } + } + + return [.. bytes]; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs new file mode 100644 index 000000000..4826e490a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/RealmFiles.cs @@ -0,0 +1,22 @@ +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// +/// Where the shipped realm exports live, for the cases that read the files and start no Keycloak. +/// +/// +/// Kept apart from the Keycloak fixture on purpose: a case that only parses a file is not a Docker case, +/// and naming the fixture would route it to the job that has a Docker socket. +/// +internal static class RealmFiles +{ + internal static string RealmPath(string realm) => Path.Combine(RepositoryRoot(), "infra", "keycloak", "realms", realm + ".json"); + + internal static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !(File.Exists(Path.Combine(directory.FullName, "CLAUDE.md")) + && Directory.Exists(Path.Combine(directory.FullName, "infra", "keycloak", "realms")))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("The repository root is missing."); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs b/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs index 00739bd73..512ec609e 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenantAuthenticationPipelineProof.cs @@ -25,6 +25,7 @@ internal static class TenantAuthenticationPipelineProof private static readonly Dictionary HelperLeaves = new(StringComparer.Ordinal) { ["MapLearnStackOpenApi"] = [], + ["MapLearnStackPlatformOperator"] = [], ["UseLearnStackPublicResponsePolicy"] = ["Use"], ["MapLearnStackClientErrors"] = ["UseStatusCodePages"], ["UseLearnStackCorrelationHeader"] = ["UseMiddleware"], @@ -222,7 +223,7 @@ IEnumerable Expand(SyntaxNode body, string receiver, HashSet +/// The closed operator token profile, the failure labels, the settings guards and the classifier +/// guard (ADR-0101 § 2, § 3). The profile runs after the stock handler verified the signature, so +/// these unsigned fixtures exercise only the claim reading. +/// +public sealed class PlatformOperatorAuthenticationTests +{ + private const string Issuer = "https://operator.example.test/realms/learnstack-hub"; + private static readonly DateTimeOffset Now = new(2026, 11, 19, 9, 0, 0, TimeSpan.Zero); + + [Theory] + [InlineData("operator.other")] + [InlineData("")] + [InlineData("OPERATOR.API")] + public void Only_The_Two_Registered_Executors_Can_Be_Named_In_A_Witness(string executor) + { + var read = () => PlatformOperatorTokenProfile.TryRead(Token(), Settings(), Now, executor, "00-trace-01", out _, out _); + + read.Should().Throw(); + } + + [Fact] + public void The_Offline_Tool_Executor_Is_Accepted_And_Recorded() + { + PlatformOperatorTokenProfile.TryRead( + Token(), Settings(), Now, PlatformOperatorSettings.RebindToolExecutor, "00-trace-01", out var witness, out _) + .Should().BeTrue(); + + witness!.Executor.Should().Be("operator.rebind"); + } + + [Fact] + public void A_Token_Meeting_The_Whole_Profile_Yields_A_Witness_For_The_Pinned_Issuer() + { + var read = PlatformOperatorTokenProfile.TryRead( + Token(), Settings(), Now, PlatformOperatorSettings.Executor, "00-trace-01", out var witness, out var cause); + + read.Should().BeTrue(); + witness!.Issuer.Should().Be(Issuer); + witness.SubjectDigest.Should().Be(PlatformOperatorSubject.Digest(Issuer, "operator-sub-1")); + witness.Acr.Should().Be("mfa"); + witness.Executor.Should().Be(PlatformOperatorSettings.Executor); + witness.CorrelationId.Should().Be("00-trace-01"); + witness.AuthenticatedAt.Should().Be(Now.AddSeconds(-30)); + cause.Should().Be(default(PlatformOperatorTokenCause)); + } + + [Theory] + [InlineData("iss-other", "Issuer")] + [InlineData("iss-case", "Issuer")] + [InlineData("iss-missing", "Issuer")] + [InlineData("sub-missing", "Subject")] + [InlineData("sub-blank", "Subject")] + [InlineData("azp-missing", "AuthorizedParty")] + [InlineData("azp-other", "AuthorizedParty")] + [InlineData("acr-missing", "AuthenticationContext")] + [InlineData("acr-other", "AuthenticationContext")] + [InlineData("iat-missing", "IssuedAt")] + [InlineData("iat-out-of-range", "IssuedAt")] + [InlineData("auth-time-missing", "AuthenticationTime")] + [InlineData("auth-time-out-of-range", "AuthenticationTime")] + [InlineData("exp-missing", "Lifetime")] + [InlineData("lifetime-too-long", "Lifetime")] + [InlineData("lifetime-not-positive", "Lifetime")] + [InlineData("auth-time-future", "AuthenticationAge")] + [InlineData("auth-time-old", "AuthenticationAge")] + public void Each_Profile_Defect_Is_Refused_With_Its_Own_Closed_Cause(string defect, string expectedCause) + { + var expected = Enum.Parse(expectedCause); + var iat = Now.ToUnixTimeSeconds() - 5; + var claims = Claims(); + switch (defect) + { + case "iss-other": claims["iss"] = "https://elsewhere.example.test/realms/x"; break; + case "iss-case": claims["iss"] = Issuer.ToUpperInvariant(); break; + case "iss-missing": claims.Remove("iss"); break; + case "sub-missing": claims.Remove("sub"); break; + case "sub-blank": claims["sub"] = " "; break; + case "azp-missing": claims.Remove("azp"); break; + case "azp-other": claims["azp"] = "learnstack-web"; break; + case "acr-missing": claims.Remove("acr"); break; + case "acr-other": claims["acr"] = "0"; break; + case "iat-missing": claims.Remove("iat"); break; + case "iat-out-of-range": claims["iat"] = long.MaxValue; break; + case "auth-time-missing": claims.Remove("auth_time"); break; + case "auth-time-out-of-range": claims["auth_time"] = long.MinValue; break; + case "exp-missing": claims.Remove("exp"); break; + case "lifetime-too-long": claims["exp"] = iat + 16 * 60; break; + case "lifetime-not-positive": claims["exp"] = iat; break; + case "auth-time-future": claims["auth_time"] = Now.ToUnixTimeSeconds() + 600; break; + case "auth-time-old": claims["auth_time"] = Now.ToUnixTimeSeconds() - 3600; break; + default: throw new ArgumentOutOfRangeException(nameof(defect)); + } + + PlatformOperatorTokenProfile.TryRead(Token(claims), Settings(), Now, PlatformOperatorSettings.Executor, null, out var witness, out var cause) + .Should().BeFalse(); + witness.Should().BeNull(); + cause.Should().Be(expected); + cause.Label().Should().NotBe("profile_invalid", "every cause has a closed counter label"); + } + + [Fact] + public void Every_Profile_Cause_Has_A_Distinct_Closed_Label() + { + var labels = Enum.GetValues().Select(cause => cause.Label()).ToList(); + + labels.Should().OnlyHaveUniqueItems().And.OnlyContain(label => label.StartsWith("profile_", StringComparison.Ordinal)); + } + + // A theory parameter must be one xUnit can serialize: a case holding an Exception is discovered as one + // case and executed as many, and the hosted discovery protocol refuses the second completion of one id. + // The label is the serializable key; the exception is built inside the test. + private static readonly (string Label, Func Failure, string Expected)[] FailureCases = + [ + ("no failure", () => null, "token_missing"), + ("profile refusal", () => new PlatformOperatorProfileException("profile_azp"), "profile_azp"), + ("expired", () => new SecurityTokenExpiredException("x"), "token_expired"), + ("not yet valid", () => new SecurityTokenNotYetValidException("x"), "token_lifetime"), + ("no expiration", () => new SecurityTokenNoExpirationException("x"), "token_lifetime"), + ("invalid signature", () => new SecurityTokenInvalidSignatureException("x"), "token_signature"), + ("signature key not found", () => new SecurityTokenSignatureKeyNotFoundException("x"), "token_signature"), + ("invalid issuer", () => new SecurityTokenInvalidIssuerException("x"), "token_issuer"), + ("invalid audience", () => new SecurityTokenInvalidAudienceException("x"), "token_audience"), + ("invalid algorithm", () => new SecurityTokenInvalidAlgorithmException("x"), "token_algorithm"), + ("invalid type", () => new SecurityTokenInvalidTypeException("x"), "token_type"), + ("aggregate of expiry and io", () => new AggregateException(new SecurityTokenExpiredException("x"), new IOException()), "token_expired"), + ("configuration unobtainable", () => new InvalidOperationException("IDX20803: Unable to obtain configuration."), "metadata_unavailable"), + ("wrapped io refusal", () => new InvalidOperationException("wrapped", new IOException("refused")), "metadata_unavailable"), + ("http down", () => new HttpRequestException("down"), "metadata_unavailable"), + ("other format fault", () => new FormatException("other"), "token_invalid"), + ]; + + public static TheoryData FailureLabels() + { + var labels = new TheoryData(); + foreach (var row in FailureCases) + { + labels.Add(row.Label); + } + + return labels; + } + + [Theory] + [MemberData(nameof(FailureLabels))] + public void An_Authentication_Failure_Maps_To_One_Closed_Label(string label) + { + var row = FailureCases.Single(candidate => candidate.Label == label); + + PlatformOperatorFailure.Classify(row.Failure()).Should().Be(row.Expected); + } + + [Theory] + [InlineData("0")] + [InlineData("1")] + public void A_Single_Factor_Acr_Is_Not_An_Accepted_Assurance(string acr) + { + var act = () => FromConfiguration(("PlatformOperator:AcceptedAcr:0", "mfa"), ("PlatformOperator:AcceptedAcr:1", acr)); + + act.Should().Throw().WithMessage("*single-factor*"); + } + + [Fact] + public void The_Operator_Issuer_Cannot_Be_The_Tenant_Issuer() + { + var act = () => FromConfiguration((TenantAuthenticationOptions.IssuerConfigurationKey, Issuer + "/")); + + act.Should().Throw().WithMessage("*tenant issuer*"); + } + + [Fact] + public void A_Different_Tenant_Issuer_Leaves_The_Operator_Configuration_Valid() + { + var settings = FromConfiguration( + (TenantAuthenticationOptions.IssuerConfigurationKey, "https://identity.example.test/realms/learnstack")); + + settings.Should().NotBeNull(); + settings!.Issuer.Should().Be(Issuer); + } + + [Fact] + public void An_Unreadable_Maximum_Authentication_Age_Names_The_Expected_Format() + { + var act = () => FromConfiguration(("PlatformOperator:MaxAuthenticationAge", "fifteen minutes")); + + act.Should().Throw().WithMessage("*00:15:00*"); + } + + [Fact] + public void Operator_Metadata_Is_Honoured_Only_On_The_Operator_Surface_Behind_The_Operator_Policy() + { + var classifier = new OperationHttpClassifier(new EmptyCatalog()); + var operatorMetadata = InfrastructureOperationMetadata.PlatformOperator; + var policy = new AuthorizeAttribute(PlatformOperatorAuthentication.PolicyName); + + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Infrastructure); + Classify(classifier, "/API/Platform/V1/killswitches/{key}", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Infrastructure, "routing is case-insensitive, so is the prefix"); + + // The declaration alone proves nothing: a route off the prefix, a missing policy, another + // policy or an anonymous allowance is refused, so the metadata cannot be used to make a + // tenant route look like infrastructure and skip the tenant admission middlewares. + Classify(classifier, "/api/v1/public/site", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v2/killswitches", operatorMetadata, policy) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata, new AuthorizeAttribute("Other")) + .Should().Be(HttpOperationClassification.Refused); + Classify(classifier, "/api/platform/v1/killswitches/{key}", operatorMetadata, policy, new AllowAnonymousAttribute()) + .Should().Be(HttpOperationClassification.Refused); + } + + [Fact] + public async Task A_Challenge_For_A_Caller_Who_Hung_Up_Is_Not_Counted_As_An_Issuer_Fault() + { + // The abort raises a cancellation that the failure mapping would read as a metadata fault, and a + // burst of aborted calls would then look like an outage on a dashboard. + var causes = new System.Collections.Concurrent.ConcurrentBag(); + using var listener = new System.Diagnostics.Metrics.MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.MeterName + && instrument.Name == LearnStack.Infrastructure.PlatformOperator.PlatformOperatorMetrics.RefusalCounterName) + { + l.EnableMeasurementEvents(instrument); + } + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag is { Key: "cause", Value: string cause }) + { + causes.Add(cause); + } + } + }); + listener.Start(); + + using var aborted = new CancellationTokenSource(); + await aborted.CancelAsync(); + var http = new DefaultHttpContext + { + RequestAborted = aborted.Token, + RequestServices = new ServiceCollection().AddOptions().AddLogging().BuildServiceProvider(), + }; + http.Response.Body = new MemoryStream(); + var events = new PlatformOperatorEvents( + Settings(), new FixedClock(Now), new PlatformOperatorMetadataHealth(new FixedClock(Now)), + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + var challenge = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerChallengeContext( + http, + new Microsoft.AspNetCore.Authentication.AuthenticationScheme( + PlatformOperatorAuthentication.Scheme, null, typeof(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler)), + new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions(), + new Microsoft.AspNetCore.Authentication.AuthenticationProperties()) + { + AuthenticateFailure = new TaskCanceledException(), + }; + + // Writing the 401 to a caller who has gone is itself cancelled; the counting precedes it. + await FluentActions.Awaiting(() => events.Challenge(challenge)).Should().ThrowAsync(); + + causes.Should().Contain("request_aborted"); + causes.Should().NotContain("metadata_unavailable"); + } + + private sealed class FixedClock(DateTimeOffset instant) : LearnStack.SharedKernel.Time.IClock + { + public DateTimeOffset UtcNow => instant; + } + + private static HttpOperationClassification Classify( + OperationHttpClassifier classifier, string pattern, params object[] metadata) => + classifier.Classify( + new RouteEndpoint( + _ => Task.CompletedTask, + RoutePatternFactory.Parse(pattern), + 0, + new EndpointMetadataCollection(metadata), + "test"), + out _); + + private static PlatformOperatorSettings Settings() => FromConfiguration()!; + + private static PlatformOperatorSettings? FromConfiguration(params (string Key, string Value)[] extra) + { + var values = new Dictionary + { + ["PlatformOperator:Issuer"] = Issuer, + ["PlatformOperator:AcceptedAcr:0"] = "mfa", + ["PlatformOperator:AuthorizedParties:0"] = "learnstack-operator", + }; + foreach (var (key, value) in extra) + { + values[key] = value; + } + + return PlatformOperatorSettings.FromConfiguration( + new ConfigurationBuilder().AddInMemoryCollection(values).Build(), DeploymentMode.SaaS); + } + + private static Dictionary Claims() + { + var issued = Now.ToUnixTimeSeconds() - 5; + return new Dictionary + { + ["iss"] = Issuer, + ["sub"] = "operator-sub-1", + ["aud"] = "learnstack-platform", + ["azp"] = "learnstack-operator", + ["acr"] = "mfa", + ["iat"] = issued, + ["exp"] = issued + 600, + ["auth_time"] = Now.ToUnixTimeSeconds() - 30, + }; + } + + private static JsonWebToken Token(Dictionary? claims = null) => + new(Segment(new { alg = "RS256", typ = "JWT", kid = "owned-key" }) + "." + Segment(claims ?? Claims()) + ".c2ln"); + + private static string Segment(object value) => + Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value))); + + private sealed class EmptyCatalog : IOperationPolicyCatalog + { + public IReadOnlyCollection All => []; + public IReadOnlyCollection Definitions => []; + public bool TryGet(Type requestType, out OperationPolicy policy) + { + policy = null!; + return false; + } + + public bool TryGetDefinition(PermissionScope scope, string key, out PermissionRegistration definition) + { + definition = null!; + return false; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs new file mode 100644 index 000000000..75cd92130 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/PlatformOperatorMetadataHealthTests.cs @@ -0,0 +1,104 @@ +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Time; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Authentication; + +/// +/// The memory the operator scheme keeps of its issuer metadata: when to refuse a fetch without +/// trying, and when to stop trusting keys a failed refresh could not renew (ADR-0101 § 2). +/// +public sealed class PlatformOperatorMetadataHealthTests +{ + private static readonly DateTimeOffset Start = new(2026, 11, 19, 9, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_Healthy_History_Is_Neither_In_Backoff_Nor_Stale() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(TimeSpan.FromHours(3)); + + health.InBackoff().Should().BeFalse(); + health.IsStale().Should().BeFalse("no refresh has failed, so the keys held are the issuer's latest known"); + } + + [Fact] + public void A_Failure_Backs_Off_For_Thirty_Seconds_Then_Allows_A_Retry() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(TimeSpan.FromMinutes(1)); + health.RecordFailure(); + + health.InBackoff().Should().BeTrue(); + clock.Advance(PlatformOperatorMetadataHealth.RetryBackoff - TimeSpan.FromSeconds(1)); + health.InBackoff().Should().BeTrue(); + clock.Advance(TimeSpan.FromSeconds(2)); + health.InBackoff().Should().BeFalse("the next request may try the issuer again"); + } + + [Fact] + public void Keys_Become_Stale_Only_When_A_Later_Fetch_Failed_And_The_Last_Success_Is_Old() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(PlatformOperatorMetadataHealth.MaximumStaleness + TimeSpan.FromMinutes(1)); + health.IsStale().Should().BeFalse("old but never failed since"); + + health.RecordFailure(); + + health.IsStale().Should().BeTrue(); + } + + [Fact] + public void A_Failure_Within_The_Staleness_Window_Does_Not_Refuse_Tokens() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(TimeSpan.FromMinutes(5)); + health.RecordFailure(); + + health.IsStale().Should().BeFalse("a blip is bridged by the keys already held"); + } + + [Fact] + public void A_Later_Success_Clears_Both() + { + var (health, clock) = Build(); + health.RecordSuccess(); + clock.Advance(PlatformOperatorMetadataHealth.MaximumStaleness + TimeSpan.FromMinutes(1)); + health.RecordFailure(); + clock.Advance(TimeSpan.FromSeconds(31)); + + health.RecordSuccess(); + + health.IsStale().Should().BeFalse(); + health.InBackoff().Should().BeFalse(); + } + + [Fact] + public void A_Scheme_That_Never_Loaded_Keys_Is_Not_Called_Stale() + { + var (health, _) = Build(); + health.RecordFailure(); + + health.IsStale().Should().BeFalse("with no keys held every token already fails, and for the right reason"); + health.InBackoff().Should().BeTrue(); + } + + private static (PlatformOperatorMetadataHealth Health, MovableClock Clock) Build() + { + var clock = new MovableClock(Start); + return (new PlatformOperatorMetadataHealth(clock), clock); + } + + private sealed class MovableClock(DateTimeOffset start) : IClock + { + public DateTimeOffset UtcNow { get; private set; } = start; + + public void Advance(TimeSpan by) => UtcNow += by; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs index ce64eba88..68cacea70 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/BackgroundJobRuntimeProductionCompositionTests.cs @@ -21,7 +21,7 @@ public sealed class BackgroundJobRuntimeProductionCompositionTests [Fact] public async Task Mandatory_hosted_aliases_bind_the_actual_messaging_instances_and_keep_the_source_lazy() { - var builder = Builder(52); + var builder = Builder(54); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Services.AddLearnStackOutboxDispatcher(builder.Configuration); await using var services = builder.Services.BuildServiceProvider(); @@ -54,7 +54,7 @@ public async Task Mandatory_hosted_aliases_bind_the_actual_messaging_instances_a [Fact] public async Task Captured_capacity_refuses_one_below_the_supported_floor_before_source_construction() { - var builder = Builder(51); + var builder = Builder(53); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Configuration["ConnectionStrings:OutboxDispatcher"] = Connection(100); await using var services = builder.Services.BuildServiceProvider(); @@ -62,7 +62,7 @@ public async Task Captured_capacity_refuses_one_below_the_supported_floor_before var resolve = () => services.GetRequiredService(); resolve.Should().Throw().WithMessage("*supported physical capacity*"); source.IsValueCreated.Should().BeFalse(); - services.GetRequiredService().MaxPoolSize.Should().Be(51, + services.GetRequiredService().MaxPoolSize.Should().Be(53, "the source and its sanitized settings must use the same immutable registration input"); } @@ -72,7 +72,7 @@ public async Task Captured_capacity_refuses_one_below_the_supported_floor_before public async Task Captured_application_capacity_includes_external_work_before_either_source_is_constructed( int maximum, bool accepted) { - var builder = Builder(52); + var builder = Builder(54); builder.Configuration["ConnectionStrings:Default"] = ApplicationConnection(maximum); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Services.AddLearnStackOutboxDispatcher(builder.Configuration); diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs index 0fb9e468c..b564fe384 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/FederationCompositionTests.cs @@ -37,6 +37,42 @@ public async Task With_the_admin_secret_the_confined_adapter_and_guarded_fetcher provider.GetRequiredService().Count.Should().Be(1); } + [Fact] + public async Task Without_the_admin_secret_the_operator_port_is_closed_and_answers_nothing_it_could_act_on() + { + await using var provider = Build(new Dictionary()); + var operations = provider.GetRequiredService(); + var connection = Guid.CreateVersion7(); + var owner = new FederationBrokerOwner( + LearnStack.SharedKernel.Identifiers.TenantId.From(Guid.CreateVersion7()), connection, "lsf-" + connection.ToString("N")); + + operations.Should().BeOfType(); + (await operations.ListAsync(0, 5)).Status.Should().Be(FederationOperatorStatus.Unavailable); + (await operations.InspectAsync(owner.Alias)).Status.Should().Be(FederationInspectionStatus.Unavailable); + (await operations.CountMappersAsync(owner)).Should().BeNull(); + (await operations.RemoveAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + (await operations.DisableAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + } + + [Fact] + public async Task With_the_admin_secret_the_operator_is_its_own_adapter_instance_with_its_own_resilience_pipeline() + { + await using var provider = Build(new Dictionary + { + ["Federation:ClientSecret"] = "federation-admin-secret", + ["Authentication:Tenant:Issuer"] = "https://keycloak.example.com/realms/learnstack", + }); + + var operations = provider.GetRequiredService(); + var tenant = provider.GetRequiredService(); + + operations.GetType().Name.Should().Be("KeycloakFederationProvider"); + operations.Should().NotBeSameAs(tenant, "a sweep must not share the tenant calls' bulkhead and breaker"); + var operatorPipeline = provider.GetRequiredService>(); + var tenantPipeline = provider.GetRequiredService>(); + operatorPipeline.Pipeline.Should().NotBeSameAs(tenantPipeline.Pipeline); + } + [Fact] public void Plain_http_issuer_is_admitted_only_for_development_loopback() { @@ -140,6 +176,8 @@ private static ServiceProvider Build(Dictionary values, string // The module's defaults are registered first, exactly as the Identity foundation does. services.TryAddSingleton(); services.TryAddSingleton(); + // The operator's port has its own fail-closed default, registered by the Identity foundation the same way. + services.TryAddSingleton(); services.AddLearnStackFederationAdapter(configuration); return services.BuildServiceProvider(validateScopes: true); } diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs new file mode 100644 index 000000000..5cebaea1c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/PlatformCredentialConnectionStringTests.cs @@ -0,0 +1,32 @@ +using FluentAssertions; +using LearnStack.Api.Composition; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Composition; + +/// What the platform credential may and may not turn on (ADR-0101 § 8). +public sealed class PlatformCredentialConnectionStringTests +{ + private const string Valid = "Host=localhost;Database=learnstack;Username=learnstack_platform;Password=synthetic-secret-canary"; // leakwatch:ignore + + [Fact] + public void The_Ordinary_Credential_Is_Accepted() + { + var act = () => PersistenceCompositionExtensions.ValidatePlatformConnectionString(Valid); + + act.Should().NotThrow(); + } + + [Theory] + [InlineData("No Reset On Close=true")] + [InlineData("Multiplexing=true")] + public void A_Setting_That_Lets_Session_State_Outlive_A_Scope_Is_Refused(string setting) + { + // Session state set in one platform scope would reach the next on a connection that bypasses row + // level security. The sibling privileged sources pin these off; this one refuses a string that + // turns them on. + var act = () => PersistenceCompositionExtensions.ValidatePlatformConnectionString(Valid + ";" + setting); + + act.Should().Throw().WithMessage("*No Reset On Close*"); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Tenancy/HostClassificationScopeTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Tenancy/HostClassificationScopeTests.cs index 17c90e898..a2c69202e 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Tenancy/HostClassificationScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Tenancy/HostClassificationScopeTests.cs @@ -76,7 +76,7 @@ public void The_Exclusion_List_Is_Pinned() // /healthz and /openapi all start being classified, each of which is a 404 // for a caller that has no host to resolve. HostClassificationMiddleware.UnclassifiedPrefixes.Should().Equal( - "/healthz", "/readyz", "/openapi", "/admin/hangfire", "/api/internal"); + "/healthz", "/readyz", "/openapi", "/admin/hangfire", "/api/internal", "/api/platform"); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs index 6f7bdc557..920971a88 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationPolicyCatalogTests.cs @@ -36,7 +36,7 @@ public void Real_sources_cover_every_actual_request_once_without_implicit_grants && type.GetInterfaces().Any(contract => contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IRequest<>))) .OrderBy(type => type.FullName, StringComparer.Ordinal).ToArray(); Assert.Equal(actual, catalog.All.Select(policy => policy.RequestType)); - Assert.Equal(131, actual.Length); + Assert.Equal(136, actual.Length); Assert.Equal(5, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.PublicRead)); Assert.Single(catalog.All, policy => policy.Kind == OperationPolicyKind.AccountRead); Assert.Equal(61, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.Protected)); @@ -64,7 +64,7 @@ public void Real_sources_cover_every_actual_request_once_without_implicit_grants Assert.Equal(new[] { typeof(WithdrawOwnMembershipFieldConsentCommand), typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), typeof(ListOwnFieldConsentScopesQuery), typeof(ListOwnMembershipFieldConsentsQuery) } .OrderBy(type => type.FullName, StringComparer.Ordinal), catalog.All.Where(policy => policy.Kind == OperationPolicyKind.OwnConsentEntry).Select(policy => policy.RequestType)); - Assert.Equal(46, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.FiniteTrusted)); + Assert.Equal(51, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.FiniteTrusted)); var admission = Assert.Single(catalog.All, policy => policy.Kind == OperationPolicyKind.NativeSessionAdmission); Assert.Equal(typeof(AdmitNativeSessionScopeCommand), admission.RequestType); Assert.Null(admission.RequiredPermission); @@ -106,6 +106,48 @@ public void Conflicting_or_unregistered_metadata_never_freezes_as_authority(stri Assert.Throws(() => new OperationPolicyCatalog([source])); } + [Fact] + public void Operator_acts_accept_only_the_operator_source_and_seed_acts_never_accept_it() + { + // ADR-0102 § 1: neither source is sufficient for the other's request. The operator source is the + // single allowed source of each operator command, and no other policy in the catalogue lists it. + var catalog = ProductionCatalog(); + Type[] operatorActs = + [ + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.OperatorProvisionTenantCommand), + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.OperatorMapHostCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorInitializeRoleCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorCreateFirstAdminCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorRecoverAdminCommand), + ]; + + foreach (var act in operatorActs) + { + Assert.True(catalog.TryGet(act, out var policy), act.Name); + Assert.Equal(OperationPolicyKind.FiniteTrusted, policy.Kind); + Assert.Equal(AuthorizationSourceKind.PlatformOperator, Assert.Single(policy.AllowedSources)); + } + + var withOperatorSource = catalog.All + .Where(policy => policy.AllowedSources.Contains(AuthorizationSourceKind.PlatformOperator)) + .Select(policy => policy.RequestType) + .ToArray(); + Assert.Equal(operatorActs.OrderBy(type => type.FullName, StringComparer.Ordinal), withOperatorSource); + + Type[] seedCounterparts = + [ + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.ProvisionTenantCommand), + typeof(LearnStack.Modules.Tenancy.Application.Contracts.Tenant.MapHostToTenantCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.Seeding.InitializeSeedRoleCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.Seeding.CreateFirstSeedAdminMembershipCommand), + ]; + foreach (var seed in seedCounterparts) + { + Assert.True(catalog.TryGet(seed, out var policy), seed.Name); + Assert.DoesNotContain(AuthorizationSourceKind.PlatformOperator, policy.AllowedSources); + } + } + [Fact] public void Inactive_definitions_remain_registered_without_acquiring_grants() { diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs new file mode 100644 index 000000000..85b693eb1 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs @@ -0,0 +1,421 @@ +using System.Data.Common; +using FluentAssertions; +using LearnStack.Application.Audit; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Tenancy.Application.Authorization; +using LearnStack.Modules.Tenancy.Application.Contracts.Seeding; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Application.Authorization; + +/// +/// The handler-side check of an operator act (ADR-0102 § 1, § 7): it admits the live act of the +/// right source in the right context and transaction, and refuses everything else before a lock is +/// taken or a row is written. +/// +/// +/// The guard is driven through the real authorization coordinator, so the invocation it reads is the +/// one the pipeline would have built. Only the source is a double: it mints the operator descriptor +/// the executor's source mints, and, for the cross-source case, a seed descriptor. +/// +public sealed class OperatorActGuardTests +{ + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + private static readonly DateTimeOffset Now = new(2026, 11, 19, 12, 0, 0, TimeSpan.Zero); + + private static OperatorProvisionTenantCommand Request() => new( + Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + private static IdentityMutationLockPlan Plan() => new([], Tenant, IdentityTenantLockMode.Exclusive); + + [Fact] + public async Task The_Live_Act_In_Its_Own_Context_Is_Admitted_And_Holds_Its_Locks() + { + using var rig = new Rig(); + var request = Request(); + + var result = await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsSuccess.Should().BeTrue(); + rig.Guard.RequireCurrent(admission.Value!).IsSuccess.Should().BeTrue(); + admission.Value!.TenantId.Should().Be(Tenant); + return Result.Ok(None.Value); + }); + + result.IsSuccess.Should().BeTrue(); + await rig.Locks.Received(1).AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task A_Call_Outside_Any_Invocation_Is_Refused_Before_A_Lock() + { + using var rig = new Rig(); + + var result = await rig.Guard.AdmitAsync(Request(), Plan(), default); + + result.IsFailure.Should().BeTrue(); + result.Error!.Code.Should().Be("forbidden"); + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task A_Request_That_Is_Not_The_Invocations_Own_Object_Is_Refused() + { + using var rig = new Rig(); + + await rig.ExpectRefusalAsync(Request(), () => Request()); + } + + [Fact] + public async Task A_Seed_Source_Is_Not_Sufficient_For_An_Operator_Guard() + { + using var rig = new Rig(); + var seed = new ProvisionTenantCommand(Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + rig.SourceKind = AuthorizationSourceKind.Seed; + + var result = await rig.RunAsync(seed, async () => + { + var admission = await rig.Guard.AdmitAsync(seed, Plan(), default); + admission.IsFailure.Should().BeTrue("the guard names the operator source alone"); + admission.Error!.Code.Should().Be("forbidden"); + return Result.Ok(None.Value); + }); + + result.IsSuccess.Should().BeTrue(); + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task A_Revoked_Source_Admits_Nothing() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, async () => + { + rig.Source.Dispose(); + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsFailure.Should().BeTrue(); + return Result.Ok(None.Value); + }); + + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("user")] + [InlineData("organization")] + [InlineData("host")] + [InlineData("unresolved")] + [InlineData("other_tenant")] + public async Task A_Context_That_Is_Not_The_Tenants_Ambient_One_Is_Refused(string change) + { + // Applied before the invocation starts, so the invocation's own drift check has nothing to catch and + // the guard's restatement of the context is the only thing that can refuse. + using var rig = new Rig(); + var request = Request(); + Apply(rig, change); + + await rig.ExpectRefusalAsync(request, () => request); + } + + private static void Apply(Rig rig, string change) + { + switch (change) + { + case "user": rig.Context.UserId.Returns(UserId.SystemActor); break; + case "organization": rig.Context.OrganizationId.Returns(OrganizationId.From(Guid.CreateVersion7())); break; + case "host": + rig.Context.HostScope.Returns(TenantContextFactory.Create( + new TenantResolutionAttempt { HostTenantId = Tenant }).Value!.HostScope); + break; + case "unresolved": rig.Context.IsResolved.Returns(false); break; + default: rig.Context.TenantId.Returns(TenantId.From(Guid.CreateVersion7())); break; + } + } + + [Theory] + [InlineData("no_transaction")] + [InlineData("read_only")] + [InlineData("rollback_only")] + [InlineData("announced_elsewhere")] + [InlineData("not_announced")] + [InlineData("global_identity")] + public async Task A_Transaction_That_Is_Not_The_Ordinary_Announced_Owner_Is_Refused(string change) + { + using var rig = new Rig(); + var request = Request(); + + await rig.ExpectRefusalAsync(request, () => + { + switch (change) + { + case "no_transaction": rig.Unit.HasActiveTransaction.Returns(false); break; + case "read_only": rig.Unit.Mode.Returns(TransactionMode.ReadOnly); break; + case "rollback_only": rig.Unit.IsRollbackOnly.Returns(true); break; + case "announced_elsewhere": + rig.Unit.GetTenantContextAnnouncement(Arg.Any()) + .Returns(new TenantContextAnnouncement(1, TenantId.From(Guid.CreateVersion7()), null)); + break; + case "not_announced": rig.Unit.GetTenantContextAnnouncement(Arg.Any()).Returns((TenantContextAnnouncement?)null); break; + default: rig.GlobalUnit.IsGlobalIdentityTransaction.Returns(true); break; + } + + return request; + }); + } + + [Fact] + public async Task A_Lock_That_Cannot_Be_Taken_Is_Unavailable_And_Rolls_The_Act_Back() + { + using var rig = new Rig(); + var request = Request(); + rig.Locks.AcquireAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromException(new IdentityMutationLockException())); + + await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsFailure.Should().BeTrue(); + admission.Error!.Code.Should().Be("dependency_unavailable"); + return Result.Ok(None.Value); + }); + + rig.Unit.Received(1).MarkRollbackOnly(); + } + + [Fact] + public async Task A_Lock_That_Was_Lost_Before_A_Write_Refuses_The_Write_And_Rolls_The_Act_Back() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsSuccess.Should().BeTrue(); + rig.Locks.When(value => value.RequireCurrent(Arg.Any())) + .Do(_ => throw new IdentityMutationLockException()); + + var current = rig.Guard.RequireCurrent(admission.Value!); + + current.IsFailure.Should().BeTrue(); + current.Error!.Code.Should().Be("dependency_unavailable"); + return Result.Ok(None.Value); + }); + + rig.Unit.Received(1).MarkRollbackOnly(); + } + + [Fact] + public async Task The_Live_Act_Check_Answers_Without_Taking_A_Lock() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, () => + { + rig.Guard.RequireLiveAct(request).IsSuccess.Should().BeTrue(); + rig.Guard.RequireLiveAct(Request()).IsFailure.Should().BeTrue("another request object is not this invocation's"); + return Task.FromResult(Result.Ok(None.Value)); + }); + + rig.Guard.RequireLiveAct(request).IsFailure.Should().BeTrue("outside an invocation there is no live act"); + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("user")] + [InlineData("organization")] + [InlineData("host")] + [InlineData("unresolved")] + public async Task The_Live_Act_Check_Refuses_A_Context_That_Is_Not_The_Tenants_Ambient_One(string change) + { + using var rig = new Rig(); + var request = Request(); + Apply(rig, change); + var refused = false; + + await rig.RunAsync(request, () => + { + refused = rig.Guard.RequireLiveAct(request).IsFailure; + return Task.FromResult(Result.Ok(None.Value)); + }); + + refused.Should().BeTrue(); + } + + [Fact] + public void A_Replay_Is_Recorded_On_The_Guard_And_Starts_Unrecorded() + { + using var rig = new Rig(); + + rig.Guard.Replayed.Should().BeFalse(); + rig.Guard.MarkReplayed(); + rig.Guard.Replayed.Should().BeTrue(); + } + + [Theory] + [InlineData(AuthorizationSourceKind.PlatformOperator, false)] + [InlineData(AuthorizationSourceKind.Seed, true)] + public async Task An_Authorization_Refusal_Of_An_Operator_Act_Writes_No_Durable_Denial_Row_Unlike_Any_Other_Source( + AuthorizationSourceKind source, bool writes) + { + // ADR-0033 Amendment 14. The control is the seed source, which records the same refusal, so the empty + // answer for the operator is the coordinator's decision and not a fixture that cannot write. + using var rig = new Rig { SourceKind = source }; + OperatorProvisionTenantCommand operatorRequest = Request(); + var seedRequest = new ProvisionTenantCommand(Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + await using var execution = rig.Evidence.BeginExecution(); + + Task> Refuse(object request) => rig.RunAsync(request, () => + { + rig.Evidence.RecordPolicyRefusal(rig.CurrentInvocation!, null, new Error(new LocalizedMessage("lockey_forbidden"))); + return Task.FromResult(Result.Fail(new Error(new LocalizedMessage("lockey_forbidden")))); + }); + + await (source == AuthorizationSourceKind.PlatformOperator ? Refuse(operatorRequest) : Refuse(seedRequest)); + await rig.Evidence.BeforeOwnerCompletionAsync(rig.Unit, CancellationToken.None); + await rig.Evidence.BeforeSuccessAsync(CancellationToken.None); + + (rig.EvidenceWrites().Length > 0).Should().Be(writes); + } + + [Fact] + public async Task A_Plan_For_Another_Tenant_Is_Not_Held_For_This_Act() + { + using var rig = new Rig(); + var request = Request(); + + await rig.RunAsync(request, async () => + { + var admission = await rig.Guard.AdmitAsync( + request, new IdentityMutationLockPlan([], TenantId.From(Guid.CreateVersion7()), IdentityTenantLockMode.Exclusive), default); + admission.IsFailure.Should().BeTrue("the act may lock only the tenant its context carries"); + return Result.Ok(None.Value); + }); + + await rig.Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + private sealed class Rig : IDisposable + { + private readonly OperationAuthorizationCoordinator _coordinator; + private IdentityMutationLockPlan? _held; + + public Rig() + { + Context.IsResolved.Returns(true); + Context.TenantId.Returns(Tenant); + Context.Origin.Returns(TenantContextOrigin.Ambient); + var transaction = Substitute.For(); + Unit.HasActiveTransaction.Returns(true); + Unit.Mode.Returns(TransactionMode.ReadWrite); + Unit.Transaction.Returns(transaction); + Unit.GetTenantContextAnnouncement(Arg.Any()).Returns(new TenantContextAnnouncement(1, Tenant, null)); + Locks.AcquireAsync(Arg.Any(), Arg.Any()).Returns(call => + { + _held = call.Arg(); + return Task.CompletedTask; + }); + Locks.When(value => value.RequireCurrent(Arg.Any())).Do(call => + { + if (!ReferenceEquals(_held, call.Arg())) throw new IdentityMutationLockException(); + }); + + Source = new OperatorSource(this); + var clock = Substitute.For(); + clock.UtcNow.Returns(Now); + OperationAuthorizationCoordinator? current = null; + Evidence = new AuthorizationEvidenceCoordinator( + Store, new AuditStateCapture(), Unit, clock, new SystemGuidFactory(), + () => current!, [], NullLogger.Instance); + _coordinator = current = new OperationAuthorizationCoordinator( + new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()]), + Substitute.For(), Context, [], [Source], Evidence); + Guard = new OperatorActGuard(_coordinator, Context, Unit, Locks); + } + + public ITenantContext Context { get; } = Substitute.For(); + + public IAuditStore Store { get; } = Substitute.For(); + + public AuthorizationEvidenceCoordinator Evidence { get; } + + public OperationInvocation? CurrentInvocation => _coordinator.CurrentInvocation; + + /// The authorization-evidence writes the store was asked for, by method name. + public string[] EvidenceWrites() => [.. Store.ReceivedCalls() + .Select(call => call.GetMethodInfo().Name).Where(name => name.StartsWith("WriteAuthorization", StringComparison.Ordinal))]; + + public IGlobalIdentityUnitOfWork GlobalUnit { get; } = Substitute.For(); + + public IUnitOfWork Unit => GlobalUnit; + + public IIdentityMutationLocks Locks { get; } = Substitute.For(); + + public OperatorActGuard Guard { get; } + + public OperatorSource Source { get; } + + public AuthorizationSourceKind SourceKind { get; set; } = AuthorizationSourceKind.PlatformOperator; + + public Task> RunAsync(TRequest request, Func>> body) where TRequest : notnull => + _coordinator.ExecuteRequestAsync>(request, body); + + /// Runs the guard after altered the world, and expects a refusal and no lock. + public async Task ExpectRefusalAsync(TRequest request, Func change) where TRequest : notnull + { + var refused = false; + await RunAsync(request, async () => + { + var asked = change(); + var admission = await Guard.AdmitAsync(asked, Plan(), default); + refused = admission.IsFailure && admission.Error!.Code == "forbidden"; + return Result.Ok(None.Value); + }); + + refused.Should().BeTrue(); + await Locks.DidNotReceive().AcquireAsync(Arg.Any(), Arg.Any()); + } + + public void Dispose() => _coordinator.Dispose(); + } + + private sealed class OperatorSource(Rig rig) : TrustedOperationDescriptor.MintingSource, ITrustedOperationSource + { + public TrustedOperationDescriptor? Capture(Type requestType, ITenantContext context) + { + if (!CanIssue) + { + return null; + } + + return rig.SourceKind == AuthorizationSourceKind.PlatformOperator + ? ForOperation( + AuthorizationSourceKind.PlatformOperator, requestType, context, null, + PlatformOperatorAttribution.From(TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now))) + : ForOperation(AuthorizationSourceKind.Seed, requestType, context); + } + + protected override bool IsEvidenceCurrent(object? evidence) => true; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs index 10d883e18..422387464 100644 --- a/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Identity/GlobalIdentityKeyTests.cs @@ -23,6 +23,17 @@ public void User_and_tenant_keys_have_independent_signed_network_order_vectors( userKey.Should().NotBe(tenantKey); } + // SHA-256 over the length-prefixed UTF-8 strings "learnstack.identity.lock.v1" and "authority-rebind", first + // eight bytes as a big-endian signed integer, calculated outside the C# helper. + [Fact] + public void The_rebind_key_is_one_fixed_value_that_no_user_tenant_or_subject_key_shares() + { + IdentityAdvisoryLockKey.ForAuthorityRebind().Should().Be(-6667816513393306176L); + IdentityAdvisoryLockKey.ForAuthorityRebind().Should().Be(IdentityAdvisoryLockKey.ForAuthorityRebind()); + IdentityAdvisoryLockKey.ForAuthorityRebind().Should().NotBe(IdentityAdvisoryLockKey.ForUser(UserId.From(Authority.Value))) + .And.NotBe(IdentityAdvisoryLockKey.ForTenant(TenantId.From(Authority.Value))); + } + [Fact] public void A_contextual_lock_plan_copies_deduplicates_and_orders_actual_users_and_keeps_mode() { diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs new file mode 100644 index 000000000..7578b3299 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindContinuityTests.cs @@ -0,0 +1,167 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// The continuity proof of a controlled issuer rebind as a pure function (ADR-0104 § 6). +public sealed class IdentityRebindContinuityTests +{ + private static readonly IdentityAuthorityId Authority = + IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501")); + + private static IdentityRebindStoredUser Active(string subject) => + new(IdentitySubjectKey.Compute(Authority, subject), subject, UserStatus.Active); + + private static IdentityRebindStoredUser Closed(string subject) => + new(IdentitySubjectKey.Compute(Authority, subject), null, UserStatus.Closed); + + private static IdentityRebindStoredUser Closing(string subject, bool retained) => + new(IdentitySubjectKey.Compute(Authority, subject), retained ? subject : null, UserStatus.Closing); + + [Fact] + public void A_Realm_That_Reports_Every_Active_Subject_Holds_And_Counts_The_Population() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Active("b")], ["a", "b"]); + + result.Should().Be(new IdentityRebindContinuityResult(2, 0, 0, 2, 0, 0, 0, 0)); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void An_Active_Subject_The_Realm_Does_Not_Report_Is_Counted_And_Fails_The_Proof() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Active("b")], ["a"]); + + result.MissingActive.Should().Be(1); + result.Holds.Should().BeFalse(); + } + + [Theory] + [InlineData("A")] + [InlineData(" a")] + [InlineData("a ")] + [InlineData("á")] + public void Presence_Is_The_Exact_Ordinal_Subject_Not_A_Normalized_One(string reported) + { + IdentityRebindContinuity.Evaluate(Authority, [Active("a")], [reported]).MissingActive.Should().Be(1); + } + + [Fact] + public void A_Reported_User_With_No_Stored_Key_Is_A_Person_Who_Has_Not_Signed_In_And_Is_Allowed() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a")], ["a", "new-1", "new-2"]); + + result.Unbootstrapped.Should().Be(2); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void A_Closed_Persons_Key_That_A_Reported_Subject_Would_Claim_Fails_The_Proof() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Closed("gone")], ["a", "gone"]); + + result.ReappearingClosed.Should().Be(1); + result.StoredClosed.Should().Be(1); + result.Holds.Should().BeFalse(); + } + + [Fact] + public void A_Closed_Persons_Absence_Holds_And_Never_Counts_Against_The_Active_Rule() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a"), Closed("gone")], ["a"]); + + result.ReappearingClosed.Should().Be(0); + result.MissingActive.Should().Be(0); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void A_Closing_User_That_Retains_Its_Subject_Is_Judged_By_Neither_Rule() + { + var absent = IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: true)], []); + var present = IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: true)], ["leaving"]); + + absent.Holds.Should().BeTrue("closure owns the transition, so its absence is not a lost person"); + present.Holds.Should().BeTrue("and its presence is not a reappearance"); + absent.StoredClosing.Should().Be(1); + } + + [Fact] + public void A_Closing_User_That_Retains_Only_Its_Key_Is_Judged_Like_A_Closed_One() + { + IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: false)], ["leaving"]) + .ReappearingClosed.Should().Be(1); + IdentityRebindContinuity.Evaluate(Authority, [Closing("leaving", retained: false)], []) + .ReappearingClosed.Should().Be(0); + } + + [Fact] + public void A_Subject_That_Cannot_Be_A_LearnStack_Subject_Is_Counted_And_Matches_Nothing() + { + var overlong = new string('x', 256); + + var result = IdentityRebindContinuity.Evaluate(Authority, [Active("a")], ["a", "", overlong, "ok"]); + + result.Unkeyable.Should().Be(2); + result.Unbootstrapped.Should().Be(1, "only the one reported subject that could be one and matches nothing stored"); + result.Holds.Should().BeTrue(); + } + + [Fact] + public void Every_Refusal_Class_Has_Its_Own_Closed_Outcome_Label() + { + var labels = Enum.GetValues().Where(refusal => refusal != IdentityRebindRefusal.None) + .Select(refusal => IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.Refused, refusal))) + .ToList(); + + labels.Should().OnlyHaveUniqueItems().And.NotContain("refused", "no class falls through to the default label"); + labels.Should().OnlyContain(label => label.StartsWith("refused_", StringComparison.Ordinal)); + IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.Applied)).Should().Be("applied"); + IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.AlreadyApplied)).Should().Be("already_applied"); + IdentityRebindMetrics.Label(new IdentityRebindOutcome(IdentityRebindResult.Unknown)).Should().Be("unknown"); + } + + [Fact] + public void A_Subject_Containing_Text_That_Cannot_Be_Stored_Is_Counted_Unkeyable() + { + var result = IdentityRebindContinuity.Evaluate(Authority, [], ["ok", "nul\0inside", "\ud800lone-surrogate"]); + + result.Unkeyable.Should().Be(2); + result.Unbootstrapped.Should().Be(1); + } + + [Fact] + public void Duplicate_Reported_Subjects_Are_One_Subject() + { + IdentityRebindContinuity.Evaluate(Authority, [Active("a")], ["a", "a", "a"]).Enumerated.Should().Be(1); + } + + [Fact] + public void An_Empty_Realm_Fails_Any_Active_Population_And_Holds_An_Empty_One() + { + IdentityRebindContinuity.Evaluate(Authority, [Active("a")], []).Holds.Should().BeFalse(); + IdentityRebindContinuity.Evaluate(Authority, [], []).Holds.Should().BeTrue(); + } + + [Fact] + public void A_Stored_Active_Row_Without_A_Subject_Cannot_Be_Present_And_Is_Counted_Missing() + { + var corrupt = new IdentityRebindStoredUser(IdentitySubjectKey.Compute(Authority, "a"), null, UserStatus.Active); + + IdentityRebindContinuity.Evaluate(Authority, [corrupt], ["a"]).MissingActive.Should().Be(1); + } + + [Fact] + public void The_Key_Of_A_Reported_Subject_Is_Computed_Under_The_Stored_Authority_Only() + { + var other = IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502")); + var foreignClosed = new IdentityRebindStoredUser(IdentitySubjectKey.Compute(other, "gone"), null, UserStatus.Closed); + + IdentityRebindContinuity.Evaluate(Authority, [foreignClosed], ["gone"]).ReappearingClosed + .Should().Be(0, "a key under another authority is not the same person"); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs new file mode 100644 index 000000000..1145088f2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/IdentityRebindDetailTests.cs @@ -0,0 +1,29 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// The closed detail tokens of a refusal and the timing invariants the run's fences rely on (ADR-0104). +public sealed class IdentityRebindDetailTests +{ + [Fact] + public void Every_Detail_Has_Its_Own_Lowercase_Token_And_None_Has_None() + { + var tokens = Enum.GetValues().Where(detail => detail != IdentityRebindDetail.None) + .Select(IdentityRebindDetails.Token).ToList(); + + tokens.Should().OnlyHaveUniqueItems().And.NotContain(string.Empty); + tokens.Should().OnlyContain(token => token.All(character => char.IsAsciiLetterLower(character) || character == '_')); + IdentityRebindDetails.Token(IdentityRebindDetail.None).Should().BeEmpty(); + } + + [Fact] + public void The_Servers_Idle_Fence_Outlasts_The_Run_Deadline_And_The_Statement_Bound_Fits_Inside_It() + { + // The fence frees the lock of a tool that is hung, never of one still inside its own deadline. + IdentityIssuerRebind.IdleTransactionTimeout.Should().BeGreaterThan( + IdentityIssuerRebind.RunDeadline + IdentityIssuerRebind.DefaultLockWait); + IdentityIssuerRebind.StatementTimeout.Should().BeLessThan(IdentityIssuerRebind.RunDeadline); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs index 818b5ac9f..6cb93589c 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakFederationProviderTests.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.Collections.Immutable; using System.Net; +using System.Reflection; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; @@ -273,8 +274,11 @@ public async Task Every_admitted_request_targets_the_enumerated_routes_only() await adapter.ApplyAsync(new(State(enabled: true), null)); await adapter.ReadAsync(Owner); await adapter.DeleteAsync(Owner); + using var operatorAdapter = CreateOperator(provider); + await operatorAdapter.ListAsync(0, 2); var admitted = new[] { + "GET /admin/realms/learnstack/identity-provider/instances", "POST /realms/learnstack/protocol/openid-connect/token", "POST /admin/realms/learnstack/identity-provider/instances", "GET /admin/realms/learnstack/identity-provider/instances/" + Owner.Alias, @@ -283,12 +287,386 @@ public async Task Every_admitted_request_targets_the_enumerated_routes_only() "GET /admin/realms/learnstack/identity-provider/instances/" + Owner.Alias + "/mappers", }; provider.Requests.Select(request => request.Method + " " + request.Path).Distinct().Should().BeSubsetOf(admitted); - provider.Requests.Should().OnlyContain(request => request.Query.Length == 0); + // Only the listing carries a query, and it is exactly the bounded page: no search, no filter, no other member. + provider.Requests.Where(request => request.Query.Length != 0).Should().OnlyContain( + request => request.Method == "GET" && request.Path == "/admin/realms/learnstack/identity-provider/instances" + && request.Query == "?first=0&max=2&briefRepresentation=false"); } private static KeycloakFederationProvider Create(FakeKeycloak provider, string? secret = AdminSecret) => new(new KeycloakFederationOptions(Issuer), new Secrets(secret), new Resilience(), provider); + private static KeycloakFederationProvider CreateOperator(FakeKeycloak provider, string? secret = AdminSecret) => + new(new KeycloakFederationOptions(Issuer), new Secrets(secret), new OperatorResilience(), provider); + + private static FederationBrokerOwner OwnerOf(Guid? connection = null, TenantId? tenant = null) + { + var id = connection ?? Guid.CreateVersion7(); + return new(tenant ?? Tenant, id, FederationBrokerOwner.AliasPrefix + id.ToString("N")); + } + + private static FederationBrokerState StateFor(FederationBrokerOwner owner, bool enabled = true) => State(enabled) with { Owner = owner }; + + /// A broker as the provider stores it after a tenant's create: conforming, with its secret. + private static JsonObject Stored(FederationBrokerOwner owner, bool enabled = true) => + KeycloakFederationProfile.Representation(StateFor(owner, enabled), Fresh()); + + /// An owned broker the adapter cannot read: its issuer is gone, as when an operator edited it in the provider. + private static JsonObject Unreadable(FederationBrokerOwner owner, bool enabled = true) + { + var broker = Stored(owner, enabled); + broker["config"]!.AsObject().Remove("issuer"); + return broker; + } + + private static string Foreign() => "lsf-" + new string('0', 32); + + [Fact] + public async Task A_listing_classifies_owned_brokers_and_ignores_everything_else() + { + var provider = new FakeKeycloak(); + var healthy = OwnerOf(); + var broken = OwnerOf(); + var drifted = OwnerOf(); + provider.Brokers[healthy.Alias] = Stored(healthy); + provider.Brokers[broken.Alias] = Unreadable(broken, enabled: false); + provider.Brokers[drifted.Alias] = Stored(drifted); + provider.Brokers[drifted.Alias]["config"]!["extra"] = "not-in-the-profile"; + // Not LearnStack's: an alias nobody derived, a derived alias with no marker, and a marker for another connection. + provider.Brokers["corporate-sso"] = new JsonObject { ["alias"] = "corporate-sso", ["config"] = new JsonObject() }; + var unmarked = OwnerOf(); + provider.Brokers[unmarked.Alias] = new JsonObject { ["alias"] = unmarked.Alias, ["config"] = new JsonObject() }; + var mismatched = OwnerOf(); + var stolen = Stored(mismatched); + stolen["config"]![KeycloakFederationProfile.OwnerKey] = $"{Tenant.Value:D}:{Guid.CreateVersion7():D}"; + provider.Brokers[mismatched.Alias] = stolen; + using var adapter = CreateOperator(provider); + + var page = await adapter.ListAsync(0, 20); + + page.Status.Should().Be(FederationOperatorStatus.Ok); + page.Scanned.Should().Be(6); + page.Ignored.Should().Be(3); + page.Owned.Select(facts => facts.Owner.Alias).Should().BeEquivalentTo([healthy.Alias, broken.Alias, drifted.Alias]); + var byAlias = page.Owned.ToDictionary(facts => facts.Owner.Alias); + byAlias[healthy.Alias].Should().Match(facts => facts.Readable && facts.Conforms && facts.Enabled + && facts.Protocol == FederationBrokerProtocol.Oidc); + byAlias[broken.Alias].Should().Match(facts => !facts.Readable && !facts.Conforms && !facts.Enabled + && facts.Protocol == null); + byAlias[drifted.Alias].Should().Match(facts => facts.Readable && !facts.Conforms); + provider.Requests.Where(request => request.Path.Contains("identity-provider", StringComparison.Ordinal)) + .Select(request => request.Method + " " + request.Path + request.Query).Should().Equal( + "GET /admin/realms/learnstack/identity-provider/instances?first=0&max=20&briefRepresentation=false"); + page.ToString().Should().NotContain(TenantSecret).And.NotContain(AdminSecret).And.NotContain("Acme"); + } + + [Fact] + public async Task A_listing_pages_by_offset_and_a_provider_that_ignores_the_page_size_is_unavailable() + { + var provider = new FakeKeycloak(); + var owners = Enumerable.Range(0, 5).Select(_ => OwnerOf()).OrderBy(owner => owner.Alias, StringComparer.Ordinal).ToArray(); + foreach (var owner in owners) provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + var first = await adapter.ListAsync(0, 2); + var second = await adapter.ListAsync(2, 2); + var last = await adapter.ListAsync(4, 2); + + (first.Scanned, second.Scanned, last.Scanned).Should().Be((2, 2, 1)); + first.Owned.Concat(second.Owned).Concat(last.Owned).Select(facts => facts.Owner.Alias).Should().Equal(owners.Select(owner => owner.Alias)); + + provider.ListIgnoresPaging = true; + (await adapter.ListAsync(0, 2)).Status.Should().Be(FederationOperatorStatus.Unavailable); + } + + [Theory] + [InlineData("object")] + [InlineData("5xx")] + public async Task A_listing_that_is_not_an_array_or_that_the_provider_fails_is_unavailable_and_returns_nothing(string defect) + { + var provider = new FakeKeycloak { ListDefect = defect }; + using var adapter = CreateOperator(provider); + + (await adapter.ListAsync(0, 5)).Should().Be(FederationBrokerPage.Unavailable); + } + + [Fact] + public async Task An_inspection_reports_absent_foreign_and_owned_with_the_mapper_count_of_a_readable_broker() + { + var provider = new FakeKeycloak { Mappers = 2 }; + var mine = OwnerOf(); + var broken = OwnerOf(); + provider.Brokers[mine.Alias] = Stored(mine); + provider.Brokers[broken.Alias] = Unreadable(broken); + provider.Brokers[Foreign()] = new JsonObject { ["alias"] = Foreign(), ["config"] = new JsonObject() }; + using var adapter = CreateOperator(provider); + + (await adapter.InspectAsync(OwnerOf().Alias)).Should().Be(FederationBrokerInspection.Absent); + (await adapter.InspectAsync(Foreign())).Should().Be(FederationBrokerInspection.NotOwned); + var owned = await adapter.InspectAsync(mine.Alias); + (owned.Status, owned.MapperCount, owned.Facts!.Owner.TenantId).Should().Be((FederationInspectionStatus.Owned, 2, Tenant)); + var unreadable = await adapter.InspectAsync(broken.Alias); + (unreadable.Status, unreadable.MapperCount, unreadable.Facts!.Readable).Should().Be((FederationInspectionStatus.Owned, 0, false)); + var notDerived = async () => await adapter.InspectAsync("not-a-derived-alias"); + await notDerived.Should().ThrowAsync("no route is built from an alias that is not the derived form"); + } + + [Fact] + public async Task A_remove_deletes_an_owned_broker_readable_or_not_and_confirms_its_absence() + { + var provider = new FakeKeycloak(); + var readable = OwnerOf(); + var broken = OwnerOf(); + provider.Brokers[readable.Alias] = Stored(readable); + provider.Brokers[broken.Alias] = Unreadable(broken); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(readable)).Should().Be(FederationOperatorOutcome.Applied); + (await adapter.RemoveAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + provider.Brokers.Should().BeEmpty(); + provider.Requests.Count(request => request.Method == "DELETE").Should().Be(2); + // The provider is read before the delete and again after it, so the outcome is the absence and not a status. + provider.Requests.Where(request => request.Path.EndsWith(readable.Alias, StringComparison.Ordinal)) + .Select(request => request.Method).Should().Equal("GET", "DELETE", "GET"); + } + + [Fact] + public async Task A_remove_of_an_absent_broker_is_already_applied_and_sends_nothing() + { + var provider = new FakeKeycloak(); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(OwnerOf())).Should().Be(FederationOperatorOutcome.AlreadyApplied); + + provider.Requests.Where(request => !request.Path.EndsWith("/token", StringComparison.Ordinal)).Select(request => request.Method) + .Should().Equal("GET"); + } + + [Fact] + public async Task A_remove_never_touches_an_instance_whose_marker_is_not_the_owner_the_caller_proved() + { + var provider = new FakeKeycloak(); + var claimed = OwnerOf(); + var other = Stored(claimed); + other["config"]![KeycloakFederationProfile.OwnerKey] = $"{Guid.CreateVersion7():D}:{claimed.ConnectionId:D}"; + provider.Brokers[claimed.Alias] = other; + var unmarked = OwnerOf(); + provider.Brokers[unmarked.Alias] = new JsonObject { ["alias"] = unmarked.Alias, ["config"] = new JsonObject() }; + using var adapter = CreateOperator(provider); + + // Another tenant's marker on the claimed connection, and an unmarked derived alias. + (await adapter.RemoveAsync(claimed)).Should().Be(FederationOperatorOutcome.NotOwned); + (await adapter.RemoveAsync(unmarked)).Should().Be(FederationOperatorOutcome.NotOwned); + + provider.Brokers.Should().HaveCount(2); + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + } + + [Theory] + [InlineData("refused", FederationOperatorOutcome.Refused)] + [InlineData("fails", FederationOperatorOutcome.Uncertain)] + public async Task A_delete_the_provider_refuses_changes_nothing_and_one_that_fails_after_it_was_sent_is_uncertain( + string kind, FederationOperatorOutcome expected) + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { DeleteStatus = kind == "refused" ? HttpStatusCode.Conflict : HttpStatusCode.InternalServerError }; + provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner)).Should().Be(expected); + + provider.Brokers.Should().ContainKey(owner.Alias); + } + + [Fact] + public async Task A_delete_the_provider_accepts_and_does_not_perform_is_uncertain_because_absence_is_the_confirmation() + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { IgnoreDelete = true }; + provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner)).Should().Be(FederationOperatorOutcome.Uncertain); + } + + [Theory] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", true)] + [InlineData("019A1929-5450-7BBB-8DF1-516E8E002501:019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019A1929-5450-7BBB-8DF1-516E8E002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502 ", false)] + [InlineData(" 019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501;019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("019a1929545 07bbb8df1516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", false)] + [InlineData("00000000-0000-0000-0000-000000000000:019a1929-5450-7bbb-8df1-516e8e002502", false)] // leakwatch:ignore + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-4bbb-8df1-516e8e002502", false)] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502:x", false)] + [InlineData("", false)] + public void The_owner_marker_is_parsed_strictly_and_names_only_the_connections_own_derived_alias(string marker, bool valid) + { + var alias = "lsf-019a192954507bbb8df1516e8e002502"; + + KeycloakFederationProfile.TryOwnerFromMarker(marker, alias, out var owner).Should().Be(valid, marker); + + if (valid) + { + (owner.TenantId.Value, owner.ConnectionId).Should().Be( + (Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501"), Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002502"))); + } + + // Another connection's alias never matches this marker, however well formed it is. + KeycloakFederationProfile.TryOwnerFromMarker( + "019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", "lsf-019a192954507bbb8df1516e8e002503", out _) + .Should().BeFalse(); + KeycloakFederationProfile.TryOwnerFromMarker(null, alias, out _).Should().BeFalse(); + KeycloakFederationProfile.TryOwnerFromMarker("019a1929-5450-7bbb-8df1-516e8e002501:019a1929-5450-7bbb-8df1-516e8e002502", null, out _) + .Should().BeFalse(); + } + + [Fact] + public async Task A_provider_that_cannot_be_reached_before_any_change_is_sent_is_unavailable_and_not_uncertain() + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { TokenDefect = "extra-role" }; + provider.Brokers[owner.Alias] = Unreadable(owner); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + (await adapter.DisableAsync(owner)).Should().Be(FederationOperatorOutcome.Unavailable); + provider.Requests.Select(request => request.Method).Should().NotContain(["DELETE", "PUT"]); + } + + [Fact] + public async Task A_disable_sends_back_what_the_provider_returned_with_only_enabled_changed_and_keeps_the_stored_secret() + { + var provider = new FakeKeycloak(); + var broken = OwnerOf(); + provider.Brokers[broken.Alias] = Unreadable(broken, enabled: true); + var before = provider.Brokers[broken.Alias].DeepClone().AsObject(); + using var adapter = CreateOperator(provider); + + (await adapter.DisableAsync(broken)).Should().Be(FederationOperatorOutcome.Applied); + + var after = provider.Brokers[broken.Alias]; + after["enabled"]!.GetValue().Should().BeFalse(); + // Nothing else moved, the computed members were never sent, and the secret the provider holds is the one it held. + before["enabled"] = false; + JsonNode.DeepEquals(after, before).Should().BeTrue("only enabled differs from what the provider held"); + after.ContainsKey("internalId").Should().BeFalse(); + after.ContainsKey("types").Should().BeFalse(); + after["config"]!["clientSecret"]!.GetValue().Should().Be(TenantSecret); + var put = provider.Requests.Single(request => request.Method == "PUT"); + put.Body.Should().NotContain(TenantSecret, "the secret travels as the provider's own mask, never as a value this adapter read"); + put.Body.Should().Contain("**********"); + } + + [Fact] + public async Task A_disable_of_a_disabled_broker_sends_nothing_and_one_that_is_not_the_proved_owners_is_never_written() + { + var provider = new FakeKeycloak(); + var off = OwnerOf(); + provider.Brokers[off.Alias] = Unreadable(off, enabled: false); + var claimed = OwnerOf(); + var other = Stored(claimed); + other["config"]![KeycloakFederationProfile.OwnerKey] = $"{Guid.CreateVersion7():D}:{claimed.ConnectionId:D}"; + provider.Brokers[claimed.Alias] = other; + using var adapter = CreateOperator(provider); + + (await adapter.DisableAsync(off)).Should().Be(FederationOperatorOutcome.AlreadyApplied); + (await adapter.DisableAsync(claimed)).Should().Be(FederationOperatorOutcome.NotOwned); + (await adapter.DisableAsync(OwnerOf())).Should().Be(FederationOperatorOutcome.Refused, "there is nothing to disable"); + + provider.Requests.Should().NotContain(request => request.Method == "PUT"); + } + + [Theory] + [InlineData("fails", FederationOperatorOutcome.Uncertain)] + [InlineData("refused", FederationOperatorOutcome.Refused)] + [InlineData("ignored", FederationOperatorOutcome.Uncertain)] + public async Task A_disable_is_confirmed_by_reading_the_instance_again(string kind, FederationOperatorOutcome expected) + { + var owner = OwnerOf(); + var provider = new FakeKeycloak + { + WriteStatus = kind == "fails" ? HttpStatusCode.InternalServerError : kind == "refused" ? HttpStatusCode.Conflict : null, + IgnorePut = kind == "ignored", + }; + provider.Brokers[owner.Alias] = Unreadable(owner, enabled: true); + using var adapter = CreateOperator(provider); + + (await adapter.DisableAsync(owner)).Should().Be(expected); + + provider.Brokers[owner.Alias]["enabled"]!.GetValue().Should().BeTrue("the provider did not take the change"); + } + + [Fact] + public async Task The_operator_port_never_returns_a_secret_or_provider_text() + { + var owner = OwnerOf(); + var provider = new FakeKeycloak { Mappers = 1 }; + provider.Brokers[owner.Alias] = Stored(owner); + using var adapter = CreateOperator(provider); + + var results = new object?[] + { + await adapter.ListAsync(0, 5), await adapter.InspectAsync(owner.Alias), await adapter.CountMappersAsync(owner), + await adapter.DisableAsync(owner), await adapter.RemoveAsync(owner), + }; + + string.Join('|', results.Select(result => result?.ToString())).Should() + .NotContain(TenantSecret).And.NotContain(AdminSecret).And.NotContain("Acme").And.NotContain("idp.example.com"); + } + + [Theory] + [InlineData("readable_disabled", false, false)] + [InlineData("unreadable_enabled", true, true)] + [InlineData("readable_enabled", false, true)] + public async Task A_remove_that_requires_an_unreadable_disabled_broker_proves_it_again_at_the_delete_and_sends_nothing_otherwise( + string kind, bool unreadable, bool enabled) + { + var owner = OwnerOf(); + var provider = new FakeKeycloak(); + provider.Brokers[owner.Alias] = unreadable ? Unreadable(owner, enabled) : Stored(owner, enabled); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(owner, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Refused, kind); + + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + provider.Brokers.Should().ContainKey(owner.Alias); + } + + [Fact] + public async Task A_remove_that_requires_an_unreadable_disabled_broker_deletes_one_and_an_unrequired_remove_deletes_any_owned_broker() + { + var gone = OwnerOf(); + var healthy = OwnerOf(); + var provider = new FakeKeycloak(); + provider.Brokers[gone.Alias] = Unreadable(gone, enabled: false); + provider.Brokers[healthy.Alias] = Stored(healthy, enabled: true); + using var adapter = CreateOperator(provider); + + (await adapter.RemoveAsync(gone, requireDisabledUnreadable: true)).Should().Be(FederationOperatorOutcome.Applied); + (await adapter.RemoveAsync(healthy)).Should().Be(FederationOperatorOutcome.Applied, "an orphan needs no live-row proof"); + + provider.Brokers.Should().BeEmpty(); + } + + [Fact] + public void The_operator_ports_result_types_can_carry_no_secret_or_provider_text_because_they_declare_no_member_that_could() + { + // ToString is a constant on these records, so a text check cannot see a new member. The members can be seen: each is an + // owner, a flag, a count, a closed status or a protocol, and there is no string for a display name, issuer or secret. + var closed = new HashSet + { + typeof(FederationBrokerOwner), typeof(bool), typeof(int), typeof(FederationBrokerProtocol?), typeof(FederationOperatorStatus), + typeof(FederationInspectionStatus), typeof(FederationBrokerFacts), typeof(IReadOnlyList), + }; + const BindingFlags declared = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; + + foreach (var type in new[] { typeof(FederationBrokerFacts), typeof(FederationBrokerPage), typeof(FederationBrokerInspection) }) + type.GetProperties(declared).Select(property => property.PropertyType).Should().BeSubsetOf(closed, type.Name); + } + private static FederationClientSecret Fresh() => FederationClientSecret.TryCreate(TenantSecret, out var secret) ? secret! : throw new InvalidOperationException(); @@ -316,6 +694,12 @@ private sealed class Resilience : IProviderResilience public string PortName => "federation"; } + private sealed class OperatorResilience : IProviderResilience + { + public ResiliencePipeline Pipeline => ResiliencePipeline.Empty; + public string PortName => "federation"; + } + internal sealed record Recorded(string Method, string Path, string Query, string Body); /// A scripted provider holding brokers by alias, as the pinned Admin REST API stores and masks them. @@ -326,6 +710,11 @@ private sealed class FakeKeycloak : HttpMessageHandler internal int Mappers { get; set; } internal string? TokenDefect { get; init; } internal HttpStatusCode? WriteStatus { get; init; } + internal HttpStatusCode? DeleteStatus { get; init; } + internal string? ListDefect { get; init; } + internal bool ListIgnoresPaging { get; set; } + internal bool IgnorePut { get; init; } + internal bool IgnoreDelete { get; init; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { @@ -345,6 +734,16 @@ protected override async Task SendAsync(HttpRequestMessage Brokers[alias] = created; return new(HttpStatusCode.Created); } + if (request.Method == HttpMethod.Get && path == prefix) + { + if (ListDefect == "5xx") return new(HttpStatusCode.InternalServerError); + if (ListDefect == "object") return Json(HttpStatusCode.OK, new JsonObject()); + var query = System.Web.HttpUtility.ParseQueryString(request.RequestUri.Query); + var page = Brokers.Values.OrderBy(broker => broker["alias"]!.GetValue(), StringComparer.Ordinal) + .Skip(int.Parse(query["first"]!, System.Globalization.CultureInfo.InvariantCulture)); + if (!ListIgnoresPaging) page = page.Take(int.Parse(query["max"]!, System.Globalization.CultureInfo.InvariantCulture)); + return Json(HttpStatusCode.OK, new JsonArray([.. page.Select(View)])); + } var rest = path[(prefix.Length + 1)..]; var mappers = rest.EndsWith("/mappers", StringComparison.Ordinal); var key = mappers ? rest[..^"/mappers".Length] : rest; @@ -352,15 +751,12 @@ protected override async Task SendAsync(HttpRequestMessage if (request.Method == HttpMethod.Get) { if (!Brokers.TryGetValue(key, out var broker)) return new(HttpStatusCode.NotFound); - var view = broker.DeepClone().AsObject(); - if (view["config"]!.AsObject().ContainsKey("clientSecret")) view["config"]!["clientSecret"] = "**********"; - view["internalId"] = Guid.NewGuid().ToString(); - view["types"] = new JsonArray("USER_AUTHENTICATION"); - return Json(HttpStatusCode.OK, view); + return Json(HttpStatusCode.OK, View(broker)); } if (request.Method == HttpMethod.Put) { if (WriteStatus is { } status) return new(status); + if (IgnorePut) return new(HttpStatusCode.NoContent); if (!Brokers.TryGetValue(key, out var existing)) return new(HttpStatusCode.NotFound); var replacement = JsonNode.Parse(body)!.AsObject(); var config = replacement["config"]!.AsObject(); @@ -370,10 +766,24 @@ protected override async Task SendAsync(HttpRequestMessage return new(HttpStatusCode.NoContent); } if (request.Method == HttpMethod.Delete) + { + if (DeleteStatus is { } deleteStatus) return new(deleteStatus); + if (IgnoreDelete) return new(HttpStatusCode.NoContent); return new(Brokers.TryRemove(key, out _) ? HttpStatusCode.NoContent : HttpStatusCode.NotFound); + } return new(HttpStatusCode.MethodNotAllowed); } + /// What the provider returns for a stored broker: the secret masked and the computed members added. + private static JsonNode View(JsonObject broker) + { + var view = broker.DeepClone().AsObject(); + if (view["config"]!.AsObject().ContainsKey("clientSecret")) view["config"]!["clientSecret"] = "**********"; + view["internalId"] = Guid.NewGuid().ToString(); + view["types"] = new JsonArray("USER_AUTHENTICATION"); + return view; + } + private static HttpResponseMessage Json(HttpStatusCode status, JsonNode value) => new(status) { Content = new StringContent(value.ToJsonString(), Encoding.UTF8, "application/json") }; diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs index 0464317b5..ed0e050f0 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobPhysicalCapacityTests.cs @@ -8,7 +8,7 @@ namespace LearnStack.Tests.Unit.Infrastructure.Jobs; public sealed class BackgroundJobPhysicalCapacityTests { [Fact] - public void Default_topology_counts_actual_invocation_and_recurrence_owners_and_requires_52_connections() + public void Default_topology_counts_actual_invocation_and_recurrence_owners_and_requires_54_connections() { var capacity = BackgroundJobPhysicalCapacity.Calculate(BackgroundJobInfrastructureRegistry.CreateDefault()); capacity.Pools.Should().Be(3); @@ -16,18 +16,18 @@ public void Default_topology_counts_actual_invocation_and_recurrence_owners_and_ capacity.ControlPools.Should().Be(1); capacity.InvocationOwners.Should().Be(16); capacity.RecurrenceConnections.Should().Be(2); - capacity.RequiredConnections.Should().Be(52); + capacity.RequiredConnections.Should().Be(54); } [Fact] - public void Maximum_valid_control_multiplicity_requires_158_connections() + public void Maximum_valid_control_multiplicity_requires_160_connections() { var capacity = BackgroundJobPhysicalCapacity.Calculate(Topology(6)); capacity.Pools.Should().Be(8); capacity.Workers.Should().Be(32); capacity.ControlPools.Should().Be(6); capacity.InvocationOwners.Should().Be(64); - capacity.RequiredConnections.Should().Be(158); + capacity.RequiredConnections.Should().Be(160); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs index 19ce6fa1c..d4ec216aa 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Jobs/BackgroundJobQuarantineHealthTests.cs @@ -85,7 +85,7 @@ public void Runtime_health_requires_a_fresh_known_negative_quarantine_sample(boo Recurrence = new(0, 0, 0, false, false, true, true, false, false, true), }; var snapshot = new BackgroundJobRuntimeSnapshot(BackgroundJobRuntimeState.Running, - new(3, 4, 1, 16, 52), 3, 0, 0, null, true, true, true, true, false, [], [], control); + new(3, 4, 1, 16, 54), 3, 0, 0, null, true, true, true, true, false, [], [], control); snapshot.IsHealthy.Should().Be(healthy); } diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs new file mode 100644 index 000000000..97db39976 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Messaging/OperatorRecoveryFaultsTests.cs @@ -0,0 +1,61 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Messaging; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.Messaging; + +/// +/// What an operator call reports as a retryable outage and what it leaves to surface as the defect it is +/// (ADR-0103 Amendment 1): a retry loop cannot cure a refused credential or a missing grant. +/// +public sealed class OperatorRecoveryFaultsTests +{ + private static PostgresException Server(string sqlState) => new("message", "ERROR", "ERROR", sqlState); + + [Theory] + [InlineData(PostgresErrorCodes.QueryCanceled)] + [InlineData(PostgresErrorCodes.LockNotAvailable)] + [InlineData(PostgresErrorCodes.TooManyConnections)] + [InlineData(PostgresErrorCodes.AdminShutdown)] + public void A_server_fault_that_waiting_can_cure_is_transient(string sqlState) => + OperatorRecoveryFaults.IsTransientDatabaseFault(Server(sqlState), CancellationToken.None).Should().BeTrue(sqlState); + + [Theory] + [InlineData(PostgresErrorCodes.InsufficientPrivilege)] + [InlineData(PostgresErrorCodes.InvalidPassword)] + [InlineData(PostgresErrorCodes.UndefinedTable)] + [InlineData(PostgresErrorCodes.UndefinedColumn)] + [InlineData(PostgresErrorCodes.InvalidAuthorizationSpecification)] + public void A_refused_credential_or_a_missing_grant_or_table_is_a_defect_and_never_transient(string sqlState) + { + OperatorRecoveryFaults.IsTransientDatabaseFault(Server(sqlState), CancellationToken.None).Should().BeFalse(sqlState); + OperatorRecoveryFaults.IsUnavailable(Server(sqlState), CancellationToken.None).Should().BeFalse(sqlState); + } + + [Fact] + public void An_unreachable_database_and_a_timeout_are_transient() + { + OperatorRecoveryFaults.IsTransientDatabaseFault( + new NpgsqlException("unreachable", new IOException("reset")), CancellationToken.None).Should().BeTrue(); + OperatorRecoveryFaults.IsTransientDatabaseFault(new TimeoutException(), CancellationToken.None).Should().BeTrue(); + } + + [Fact] + public void A_cancellation_is_an_outage_only_when_the_caller_did_not_ask_for_it() + { + using var asked = new CancellationTokenSource(); + asked.Cancel(); + + OperatorRecoveryFaults.IsTransientDatabaseFault(new OperationCanceledException(), CancellationToken.None).Should().BeTrue(); + OperatorRecoveryFaults.IsTransientDatabaseFault(new OperationCanceledException(), asked.Token).Should().BeFalse(); + } + + [Fact] + public void The_owners_own_refusals_are_unavailable_and_a_programmer_error_is_not() + { + OperatorRecoveryFaults.IsUnavailable(new InvalidOperationException("lane busy"), CancellationToken.None).Should().BeTrue(); + OperatorRecoveryFaults.IsUnavailable(new NotSupportedException("not configured"), CancellationToken.None).Should().BeFalse(); + OperatorRecoveryFaults.IsUnavailable(new ArgumentException("bad"), CancellationToken.None).Should().BeFalse(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index b0e7aecc6..32e7c42ec 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -1,166 +1,488 @@ -using LearnStack.Tests.Unit.Application.Jobs; -using LearnStack.Infrastructure.Persistence; using FluentAssertions; using LearnStack.Infrastructure.Audit; using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Modules.Tenancy.Application.Audit; using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Hosting; using LearnStack.SharedKernel.Identifiers; -using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using LearnStack.Tests.Unit.Application.Jobs; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; -using Npgsql; +using Microsoft.Extensions.Options; using Xunit; namespace LearnStack.Tests.Unit.Infrastructure.MultiTenancy; /// -/// What stands between a caller and a BYPASSRLS connection. +/// What stands between an operator and a BYPASSRLS connection (ADR-0101). /// /// -/// No Docker: every case here is refused before a connection is opened, which is the -/// property under test. The Lazy throws if forced, so a case that completes at all -/// is a case where nothing reached the credential. +/// No Docker: every case here is decided before a connection is opened, which is the property +/// under test. The data source throws if forced, so a case that completes is a case where +/// nothing reached the credential. /// public sealed class PlatformAdminGateTests { + private static readonly string Digest = PlatformOperatorSubject.Digest(TestPlatformAdmissions.Issuer, "operator-1"); + [Fact] - public async Task The_Registered_Gate_Permits_Nobody() + public async Task An_Operator_Holding_The_Grant_Is_Admitted_For_The_Operation() { - // Nothing else instantiates this type, so without this the only gate behaviour - // the corpus exhibits is the permissive double the Docker suite uses. Its own doc - // says it exists so nobody makes the default permissive to unblock a demo; this - // is the line that would notice. - var gate = new DenyAllPlatformAdminGate(); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); + + var result = await gate.AdmitAsync( + TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, "INC-1", CancellationToken.None); - (await gate.IsPermittedAsync("anything", CancellationToken.None)).Should().BeFalse(); - (await gate.IsPermittedAsync("gdpr-redaction:some-user", CancellationToken.None)) - .Should().BeFalse("a plausible reason is not a permission"); + result.IsAdmitted.Should().BeTrue(); + result.Admission!.Operation.Should().BeSameAs(PlatformOperations.KillswitchToggle); + result.Admission.Ticket.Should().Be("INC-1"); + result.Admission.Operator.SubjectDigest.Should().Be(Digest); } [Fact] - public async Task Entry_Is_Refused_Before_The_Credential_Is_Touched() + public async Task An_Operator_Without_The_Grant_Is_Refused_Even_With_A_Valid_Witness() { - // ADR-0036 asks for the permission to be "checked before the scope opens". A - // check after the connection exists would already have spent a BYPASSRLS - // connection on a caller who was never allowed one — and, in a deployment with no - // platform credential at all, would report the wrong failure entirely. - var scope = Build(new DenyAllPlatformAdminGate(), out var dataSource); + var gate = Gate(Grants("someone-else", PlatformPermissions.KillswitchWrite.Key)); - var act = async () => await scope.EnterAsync("test:denied", CancellationToken.None); + var result = await gate.AdmitAsync( + TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null, CancellationToken.None); - await act.Should().ThrowAsync(); - dataSource.IsValueCreated.Should().BeFalse("the gate runs before the credential"); + result.IsAdmitted.Should().BeFalse(); + result.Refusal.Should().Be(PlatformRefusal.MissingPermission); } [Fact] - public async Task Ordinary_job_is_refused_even_by_a_permissive_platform_gate_before_credential_resolution() + public async Task The_Rebind_Operation_Is_Admitted_Only_For_The_Identity_Authority_Admin_Grant() + { + // ADR-0104 § 3: the offline tool's operator holds platform.identity_authority.admin, and no other + // Platform grant stands in for it, the killswitch and the onboarding grants included. + var rebind = PlatformOperations.IdentityAuthorityRebind; + rebind.Permission.Key.Should().Be("platform.identity_authority.admin"); + + var admitted = await Gate(Grants("operator-1", PlatformPermissions.IdentityAuthorityAdmin.Key)) + .AdmitAsync(TestPlatformAdmissions.Witness(), rebind, "CHG-104"); + admitted.IsAdmitted.Should().BeTrue(); + admitted.Admission!.Operation.Should().BeSameAs(rebind); + admitted.Admission.Ticket.Should().Be("CHG-104"); + + foreach (var other in PlatformPermissions.All.Where(permission => permission != PlatformPermissions.IdentityAuthorityAdmin)) + { + (await Gate(Grants("operator-1", other.Key)).AdmitAsync(TestPlatformAdmissions.Witness(), rebind, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission, other.Key); + } + + // The converse: the rebind grant admits no other act. + foreach (var operation in PlatformOperations.All.Where(operation => !ReferenceEquals(operation, rebind))) + { + (await Gate(Grants("operator-1", PlatformPermissions.IdentityAuthorityAdmin.Key)) + .AdmitAsync(TestPlatformAdmissions.Witness(), operation, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission, operation.AuditSlug); + } + + // An admission for the rebind cannot be spent on the scope or the executor, neither of which is its owner. + rebind.NeedsPlatformRole.Should().BeFalse(); + } + + [Theory] + [InlineData("platform.delivery.inspect", "platform.delivery.read")] + [InlineData("platform.delivery.replay", "platform.delivery.write")] + [InlineData("platform.delivery.reset", "platform.delivery.write")] + [InlineData("platform.federation.report", "platform.federation.read")] + [InlineData("platform.federation.remove", "platform.federation.admin")] + [InlineData("platform.federation.disable", "platform.federation.admin")] + public async Task An_Operator_Operation_Is_Admitted_Only_For_Its_Own_Permission(string slug, string permission) + { + // ADR-0103 Decision table and ADR-0099 Amendment 10: a read needs the read key and an act needs the write or + // admin key. The pair is pinned both ways: the table says which key each operation binds, and no other + // Platform key, the sibling key and the killswitch key included, admits it. + var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == slug); + operation.Permission.Key.Should().Be(permission); + + var admitted = await Gate(Grants("operator-1", permission)) + .AdmitAsync(TestPlatformAdmissions.Witness(), operation, "CHG-103"); + admitted.IsAdmitted.Should().BeTrue(); + admitted.Admission!.Operation.Should().BeSameAs(operation); + + foreach (var other in PlatformPermissions.All.Where(candidate => candidate.Key != permission)) + { + (await Gate(Grants("operator-1", other.Key)).AdmitAsync(TestPlatformAdmissions.Witness(), operation, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission, other.Key); + } + } + + [Fact] + public async Task A_Grant_For_Another_Permission_Does_Not_Admit() + { + // The grant is the permission, matched exactly: a different Platform key, or a prefix + // of the right one, is not the key. + var gate = Gate(Grants("operator-1", "platform.killswitch")); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission); + } + + [Theory] + [InlineData("")] + [InlineData("has space")] + [InlineData("semi;colon")] + [InlineData("this-ticket-is-far-too-long-to-be-a-ticket-reference-it-exceeds-sixty-four")] + public async Task A_Malformed_Ticket_Is_Refused_For_An_Operator_Who_Holds_The_Grant_And_Only_For_Them(string ticket) + { + // The grant is read first: an operator without it is refused as such whatever the request + // carries, so a malformed ticket tells them nothing and is counted under the cause an alert on + // ungranted operators watches. + var granted = Grants("operator-1", PlatformPermissions.KillswitchWrite.Key); + (await Gate(granted).AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, ticket)) + .Refusal.Should().Be(PlatformRefusal.InvalidTicket); + granted.Reads.Should().Be(1); + + var ungranted = Grants("someone-else", PlatformPermissions.KillswitchWrite.Key); + (await Gate(ungranted).AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, ticket)) + .Refusal.Should().Be(PlatformRefusal.MissingPermission); + } + + [Fact] + public async Task Each_Refusal_Is_Counted_Under_A_Snake_Case_Cause() + { + var causes = new System.Collections.Concurrent.ConcurrentBag(); + using var listener = new System.Diagnostics.Metrics.MeterListener(); + listener.InstrumentPublished = (instrument, l) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName + && instrument.Name == PlatformOperatorMetrics.RefusalCounterName) + { + l.EnableMeasurementEvents(instrument); + } + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + if (tag is { Key: "cause", Value: string cause }) + { + causes.Add(cause); + } + } + }); + listener.Start(); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); + + await gate.AdmitAsync(TestPlatformAdmissions.Witness("someone-else"), PlatformOperations.KillswitchToggle, null); + await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, "has space"); + await gate.AdmitAsync(null!, PlatformOperations.KillswitchToggle, null); + + causes.Should().Contain(["missing_permission", "invalid_ticket", "invalid_witness"]); + } + + [Fact] + public async Task An_Unregistered_Operation_Is_Refused() + { + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); + + // A lookalike is not the registered instance, however identical its content. + var lookalike = typeof(PlatformOperation).GetConstructors( + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, PlatformOperationExecutor.PlatformScope, null]); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), (PlatformOperation)lookalike, null)) + .Refusal.Should().Be(PlatformRefusal.UnknownOperation); + } + + [Fact] + public async Task A_Missing_Witness_Is_Refused() + { + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key)); + + (await gate.AdmitAsync(null!, PlatformOperations.KillswitchToggle, null)) + .Refusal.Should().Be(PlatformRefusal.InvalidWitness); + } + + [Fact] + public async Task Entry_With_An_Unregistered_Operation_Never_Touches_The_Credential() + { + // The scope also refuses a registered operation that does not use the platform role, + // but the registry holds none yet, so that second guard cannot be driven until a + // packet registers one (P03-9 Step 2 adds the first) and is exercised there. + var scope = Build(out var dataSource); + var lookalike = typeof(PlatformOperation).GetConstructors( + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)[0] + .Invoke(["tenancy.killswitch.toggle", "killswitch_toggle", PlatformPermissions.KillswitchWrite, PlatformOperationExecutor.PlatformScope, null]); + + var act = async () => await scope.EnterAsync( + TestPlatformAdmissions.Admission((PlatformOperation)lookalike), CancellationToken.None); + + await act.Should().ThrowAsync(); + dataSource.IsValueCreated.Should().BeFalse(); + } + + [Fact] + public async Task Ordinary_job_is_refused_before_credential_resolution() { var fixture = new BackgroundJobExecutionAdmissionTests.Fixture(); - var gate = new PermissiveGate(); - var scope = Build(gate, out var source); + var scope = Build(out var source); using var admission = fixture.Enter(); - var enter = async () => await scope.EnterAsync("test:ordinary-job"); + + var enter = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission()); + await enter.Should().ThrowAsync().WithMessage("*Ordinary background-job*"); source.IsValueCreated.Should().BeFalse(); - gate.Calls.Should().Be(0, "ordinary admission refuses before the permissive platform gate"); } - [Theory] - [InlineData("")] - [InlineData(" ")] - [InlineData(null)] - public async Task A_Blank_Reason_Is_Refused_Before_Anything_Else(string? reason) + [Fact] + public async Task The_Gate_Stamps_The_Admission_With_Its_Own_Clock() { - // The reason is the value Packet 9 writes durably, and a blank one makes the - // record of a cross-tenant access say nothing about why it happened. Refused - // ahead of the gate so the failure names the caller's own mistake rather than a - // permission they may well hold. - var scope = Build(new PermissiveGate(), out var dataSource); + var instant = new DateTimeOffset(2026, 11, 19, 8, 0, 0, TimeSpan.Zero); + var gate = Gate(Grants("operator-1", PlatformPermissions.KillswitchWrite.Key), new FixedClock(instant)); - var act = async () => await scope.EnterAsync(reason!, CancellationToken.None); + var result = await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null); - await act.Should().ThrowAsync(); + result.Admission!.IssuedAt.Should().Be(instant, "the scope bounds the admission's age from this stamp"); + } + + [Fact] + public async Task A_Stale_Admission_Never_Reaches_The_Credential_And_Is_Not_Spent() + { + var scope = Build(out var dataSource); + var stale = TestPlatformAdmissions.Admission( + issuedAt: DateTimeOffset.UtcNow - PlatformAdmission.MaximumAge - TimeSpan.FromSeconds(5)); + + var act = async () => await scope.EnterAsync(stale, CancellationToken.None); + + await act.Should().ThrowAsync().WithMessage("*stale*"); + dataSource.IsValueCreated.Should().BeFalse("the age check precedes the credential"); + stale.TryConsume().Should().BeTrue("a refused-as-stale admission was never spent"); + } + + [Fact] + public async Task A_Future_Dated_Admission_Is_Refused_Like_A_Stale_One() + { + var scope = Build(out var dataSource); + var future = TestPlatformAdmissions.Admission( + issuedAt: DateTimeOffset.UtcNow + PlatformAdmission.MaximumAge + TimeSpan.FromHours(1)); + + var act = async () => await scope.EnterAsync(future, CancellationToken.None); + + await act.Should().ThrowAsync().WithMessage("*stale*"); + dataSource.IsValueCreated.Should().BeFalse(); + } + + [Fact] + public async Task An_Admission_Opens_One_Scope_Only() + { + // The first entry spends the admission and then fails at the absent credential; the + // second finds it spent and says so, rather than reaching for the credential again. + var scope = Build(out var dataSource); + var admission = TestPlatformAdmissions.Admission(); + + var first = async () => await scope.EnterAsync(admission, CancellationToken.None); + await first.Should().ThrowAsync().WithMessage("*not configured*"); + + var second = async () => await scope.EnterAsync(admission, CancellationToken.None); + await second.Should().ThrowAsync().WithMessage("*already used*"); dataSource.IsValueCreated.Should().BeFalse(); } + [Fact] + public void An_Admission_Is_Consumed_By_Exactly_One_Caller_Even_Concurrently() + { + var admission = TestPlatformAdmissions.Admission(); + + var winners = Enumerable.Range(0, 64).AsParallel().WithDegreeOfParallelism(16) + .Select(_ => admission.TryConsume()).Count(won => won); + + winners.Should().Be(1); + } + [Fact] public async Task A_Permitted_Caller_Reaches_The_Credential_And_Fails_There_When_It_Is_Absent() { - // The other side of the ordering: with the gate open, the next thing that can go - // wrong is the credential, and it must surface as the credential rather than as - // anything else. - var scope = Build(new PermissiveGate(), out var dataSource); - - var act = async () => await scope.EnterAsync("test:permitted", CancellationToken.None); - - // InvalidOperationException and not PlatformAdminScopeDeniedException — the two - // are unrelated types, so this assertion already distinguishes "refused entry" - // from "entry allowed, credential missing". - // The exception's TYPE is the evidence, not IsValueCreated: when a Lazy factory - // throws, Lazy caches the failure and leaves IsValueCreated false — measured. - // So "reached the credential" is shown by the failure being the credential's, - // which is exactly what distinguishes it from the refusal above. - // The TYPE, not the message. The Lazy under test is built by this file, so an - // assertion on its text would be matching the double rather than production - // code; the production message is covered where it is produced, in + var scope = Build(out var dataSource); + + var act = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission(), CancellationToken.None); + + // The TYPE, not the message: the Lazy under test is built by this file, so an assertion + // on its text would match the double. Production's message is covered in // PlatformAdminScopeTests.An_Absent_Credential_Names_The_Key_Rather_Than_Degrading. await act.Should().ThrowAsync(); - dataSource.IsValueCreated.Should().BeFalse( - "a Lazy whose factory threw never records a created value"); + dataSource.IsValueCreated.Should().BeFalse("a Lazy whose factory threw never records a value"); } [Fact] public async Task An_Operation_The_Catalogue_Does_Not_Declare_Never_Opens_A_Connection() { - // Third in the ordering, and it belongs before the credential rather than after - // the connection: a deployment whose catalogue lost the slug must not spend a - // BYPASSRLS connection discovering that it cannot record the entry. Fail-closed - // is the whole posture — an entry nothing can record is an entry that does not - // happen (ADR-0044 § 10). - var scope = Build(new PermissiveGate(), out var dataSource, new AuditCatalog([])); + // A deployment whose catalogue lost a slug must not spend a BYPASSRLS connection + // discovering that it cannot record the entry (ADR-0044 § 10). + var scope = Build(out var dataSource, new AuditCatalog([])); - var act = async () => await scope.EnterAsync("test:unclassified", CancellationToken.None); + var act = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission(), CancellationToken.None); (await act.Should().ThrowAsync()) .Which.Message.Should().Contain(PlatformAdminScope.EnterOperation); + dataSource.IsValueCreated.Should().BeFalse("the refusal precedes the credential"); + } + + [Fact] + public async Task A_Catalogue_That_Lost_Only_The_Operation_Slug_Never_Opens_A_Connection() + { + // The entry slug is declared, the operation's result slug is not: the scope must refuse before + // the credential rather than enter, run the act and discover that its MUST row cannot be + // classified (ADR-0044 § 10). + var scope = Build(out var dataSource, new AuditCatalog([new EntryOnlyCatalogSource()])); + + var act = async () => await scope.EnterAsync(TestPlatformAdmissions.Admission(), CancellationToken.None); + + (await act.Should().ThrowAsync()) + .Which.Message.Should().Contain(PlatformOperations.KillswitchToggle.AuditSlug); + dataSource.IsValueCreated.Should().BeFalse(); + } + + [Fact] + public void The_Shipped_Tenancy_Source_Declares_The_Slugs_The_Scope_Records() + { + var catalogue = new AuditCatalog([new TenancyAuditCatalogSource()]); + + catalogue.TryGetOffPath(PlatformAdminScope.EnterOperation, out var entry).Should().BeTrue(); + entry.OperationClass.Should().Be(OperationClass.Must); + entry.OperationType.Should().Be(OperationType.SecurityEvent); + entry.ModuleName.Should().Be("platform", "the scope belongs to no module's request path"); + + // Only the operations that enter the platform scope write their result row off-path; the + // onboarding acts run through the pipeline, whose request-keyed catalogue the audit-coverage + // rules join to the matrices. + foreach (var operation in PlatformOperations.All.Where(operation => operation.NeedsPlatformRole)) + { + catalogue.TryGetOffPath(operation.AuditSlug, out var declared) + .Should().BeTrue($"'{operation.AuditSlug}' must be declared so its result row can be recorded"); + declared.OperationClass.Should().Be(OperationClass.Must); + + // An operation with a checkpoint writes an intent row on its attempt slug, which must be declared too. + if (operation.AttemptAuditSlug is { } attempt) + { + catalogue.TryGetOffPath(attempt, out var declaredAttempt) + .Should().BeTrue($"'{attempt}' must be declared so its intent row can be recorded"); + declaredAttempt.OperationClass.Should().Be(OperationClass.Must); + declaredAttempt.OperationType.Should().Be(OperationType.SecurityEvent); + } + } + } + + [Fact] + public void The_Registry_Is_Closed_And_Every_Operation_Names_A_Registered_Platform_Permission() + { + PlatformOperations.All.Should().OnlyHaveUniqueItems(operation => operation.AuditSlug); + PlatformOperations.All.Should().OnlyHaveUniqueItems(operation => operation.ReasonSlug); + + // An attempt slug is its own row kind: no two operations share one and none equals any result slug. + var attempts = PlatformOperations.All.Select(operation => operation.AttemptAuditSlug).OfType().ToArray(); + attempts.Should().OnlyHaveUniqueItems(); + attempts.Should().NotIntersectWith(PlatformOperations.All.Select(operation => operation.AuditSlug)); + foreach (var operation in PlatformOperations.All) + { + PlatformPermissions.TryGet(operation.Permission.Key, out var registered).Should().BeTrue(); + registered.Should().BeSameAs(operation.Permission); + operation.Permission.Scope.Should().Be(LearnStack.SharedKernel.Permissions.PermissionScope.Platform); + } + } + + [Fact] + public void The_Grant_Validator_Refuses_Unregistered_Keys_And_The_Demo_Operator_Outside_Development() + { + var options = new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }; + options.Grants.Add(new PlatformOperatorGrant { Subject = "operator-1", Permissions = { "platform.never.write" } }); + new PlatformOperatorGrantOptionsValidator(DeploymentMode.Development).Validate(null, options).Failed.Should().BeTrue( + "a key no operation has registered is not a grant"); + + var demo = new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }; + demo.Grants.Add(new PlatformOperatorGrant + { + Subject = PlatformOperatorGrantOptions.DemoOperatorSubject, + Permissions = { PlatformPermissions.KillswitchWrite.Key }, + }); + new PlatformOperatorGrantOptionsValidator(DeploymentMode.Development).Validate(null, demo).Succeeded.Should().BeTrue(); + new PlatformOperatorGrantOptionsValidator(DeploymentMode.SaaS).Validate(null, demo).Failed.Should().BeTrue( + "the exported demo operator may hold a grant in Development only"); + } + + [Fact] + public async Task The_Configuration_Source_Matches_The_Digest_And_Fails_Closed_Without_An_Issuer() + { + var withIssuer = Source(new PlatformOperatorGrantOptions + { + Issuer = TestPlatformAdmissions.Issuer, + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }); + (await withIssuer.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeTrue(); + (await withIssuer.IsGrantedAsync(PlatformOperatorSubject.Digest("https://other/", "operator-1"), PlatformPermissions.KillswitchWrite.Key)) + .Should().BeFalse("the same subject at another issuer is another operator"); - dataSource.IsValueCreated.Should().BeFalse( - "the refusal precedes the credential, so no connection is spent on it"); + var noIssuer = Source(new PlatformOperatorGrantOptions + { + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }); + (await noIssuer.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeFalse(); } [Fact] - public void The_Shipped_Tenancy_Source_Declares_The_Slug_The_Scope_Enters_On() + public async Task A_Grant_Removed_From_A_Reloaded_Configuration_Is_Refused_On_The_Next_Act() { - // The other half of the case above, and the reason it uses an empty catalogue - // rather than a fake that declares the slug: something has to assert that the - // shipped source really does. Both together fail if the declaration is removed. - new AuditCatalog([new TenancyAuditCatalogSource()]) - .TryGetOffPath(PlatformAdminScope.EnterOperation, out var declared) + var options = new PlatformOperatorGrantOptions + { + Issuer = TestPlatformAdmissions.Issuer, + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }; + var monitor = new MutableMonitor(options); + var source = new ConfigurationPlatformOperatorGrantSource(monitor, NullLogger.Instance); + var gate = Gate(source); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null)).IsAdmitted .Should().BeTrue(); - declared.OperationClass.Should().Be(OperationClass.Must); - declared.OperationType.Should().Be(OperationType.SecurityEvent); - declared.ModuleName.Should().Be("platform", - "the scope belongs to no module\'s request path, whatever source declares it"); + monitor.Replace(new PlatformOperatorGrantOptions { Issuer = TestPlatformAdmissions.Issuer }); + + (await gate.AdmitAsync(TestPlatformAdmissions.Witness(), PlatformOperations.KillswitchToggle, null)).Refusal + .Should().Be(PlatformRefusal.MissingPermission, "withdrawal takes effect on the next act, not at token expiry"); + } + + [Fact] + public async Task A_Reload_That_Fails_Validation_Refuses_Every_Operator_Until_It_Is_Valid() + { + var monitor = new MutableMonitor(new PlatformOperatorGrantOptions + { + Issuer = TestPlatformAdmissions.Issuer, + Grants = { new PlatformOperatorGrant { Subject = "operator-1", Permissions = { PlatformPermissions.KillswitchWrite.Key } } }, + }); + var source = new ConfigurationPlatformOperatorGrantSource(monitor, NullLogger.Instance); + (await source.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeTrue(); + + monitor.FailWith(new OptionsValidationException( + nameof(PlatformOperatorGrantOptions), typeof(PlatformOperatorGrantOptions), ["a reload that is not valid"])); + + (await source.IsGrantedAsync(Digest, PlatformPermissions.KillswitchWrite.Key)).Should().BeFalse( + "an invalid reload fails closed rather than keeping the last good grants"); } - private static PlatformAdminScope Build( - IPlatformAdminGate gate, - out PrivilegedDataSource dataSource, - IAuditCatalog? catalog = null) + private static PlatformOperatorGate Gate(IPlatformOperatorGrantSource grants, IClock? clock = null) => + new(grants, clock ?? new SystemClock(), NullLogger.Instance); + + private static CountingGrants Grants(string subject, params string[] keys) => + new(TestPlatformAdmissions.Issuer, subject, keys); + + private static ConfigurationPlatformOperatorGrantSource Source(PlatformOperatorGrantOptions options) => + new(new FixedMonitor(options), NullLogger.Instance); + + private static PlatformAdminScope Build(out PrivilegedDataSource dataSource, IAuditCatalog? catalog = null) { dataSource = new PrivilegedDataSource(() => throw new InvalidOperationException( "ConnectionStrings:PlatformAdmin is not configured in this test.")); - // The catalogue is real and built from the shipped Tenancy source, because the - // lookup now sits between the gate and the credential: a fake declaring the slug - // would let this file pass while the source that has to declare it did not. - // Nothing here reaches the store — the credential throws first — so the scope - // factory is an empty provider's. + // The catalogue is real and built from the shipped Tenancy source, so a fake declaring + // the slugs cannot let this file pass while the source that must declare them did not. return new PlatformAdminScope( - gate, dataSource, catalog ?? new AuditCatalog([new TenancyAuditCatalogSource()]), new ServiceCollection().BuildServiceProvider().GetRequiredService(), @@ -169,13 +491,48 @@ private static PlatformAdminScope Build( NullLogger.Instance); } - private sealed class PermissiveGate : IPlatformAdminGate + private sealed class FixedClock(DateTimeOffset instant) : IClock { - public int Calls { get; private set; } - public ValueTask IsPermittedAsync(string reason, CancellationToken cancellationToken = default) + public DateTimeOffset UtcNow => instant; + } + + private sealed class CountingGrants(string issuer, string subject, string[] keys) : IPlatformOperatorGrantSource + { + public int Reads { get; private set; } + + public ValueTask IsGrantedAsync(string subjectDigest, string permissionKey, CancellationToken cancellationToken = default) { - Calls++; - return ValueTask.FromResult(true); + Reads++; + return ValueTask.FromResult( + subjectDigest == PlatformOperatorSubject.Digest(issuer, subject) && keys.Contains(permissionKey)); } } + + private sealed class MutableMonitor(PlatformOperatorGrantOptions initial) : IOptionsMonitor + { + private PlatformOperatorGrantOptions _value = initial; + private Exception? _failure; + + public PlatformOperatorGrantOptions CurrentValue => _failure is null ? _value : throw _failure; + public void Replace(PlatformOperatorGrantOptions value) => _value = value; + public void FailWith(Exception failure) => _failure = failure; + public PlatformOperatorGrantOptions Get(string? name) => CurrentValue; + public IDisposable? OnChange(Action listener) => null; + } + + /// Declares the scope's entry slug and nothing else, as a deployment that lost a slug would. + private sealed class EntryOnlyCatalogSource : IAuditCatalogSource + { + public string ModuleName => "tenancy"; + + public void Describe(IAuditCatalogBuilder builder) => + builder.DeclareOffPath("platform.admin_scope.enter", OperationType.SecurityEvent, OperationClass.Must); + } + + private sealed class FixedMonitor(PlatformOperatorGrantOptions value) : IOptionsMonitor + { + public PlatformOperatorGrantOptions CurrentValue => value; + public PlatformOperatorGrantOptions Get(string? name) => value; + public IDisposable? OnChange(Action listener) => null; + } } diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs new file mode 100644 index 000000000..5fa39873f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs @@ -0,0 +1,73 @@ +using FluentAssertions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.MultiTenancy; + +/// The closed act catalog never holds the offline issuer rebind (ADR-0104 § 3). +public sealed class PlatformOperatorActCatalogTests +{ + private sealed record Request; + + [Fact] + public void The_Rebind_Operation_Is_Not_A_Pipeline_Act_Even_Though_It_Needs_No_Platform_Role() + { + // NeedsPlatformRole is false for the rebind; what keeps it out is that it does not run in the pipeline. + PlatformOperations.IdentityAuthorityRebind.NeedsPlatformRole.Should().BeFalse(); + PlatformOperations.IdentityAuthorityRebind.RunsInPipeline.Should().BeFalse(); + + var act = () => new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(Request), new PlatformOperatorAct(PlatformOperations.IdentityAuthorityRebind))]); + + act.Should().Throw(); + } + + [Theory] + [MemberData(nameof(NonPipelineOperations))] + public void An_Operation_That_Runs_Anywhere_But_The_Pipeline_Is_Refused_By_The_Catalog(string auditSlug) + { + // The slug, not the operation, is the theory parameter: xUnit cannot serialize a PlatformOperation, and a + // case it cannot serialize is discovered as one case and executed as five, which hosted CI refuses. + var operation = PlatformOperations.All.Single(candidate => candidate.AuditSlug == auditSlug); + operation.RunsInPipeline.Should().BeFalse(); + + var act = () => new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(Request), new PlatformOperatorAct(operation))]); + + act.Should().Throw(); + } + + public static TheoryData NonPipelineOperations() => new() + { + PlatformOperations.KillswitchToggle.AuditSlug, + PlatformOperations.IdentityAuthorityRebind.AuditSlug, + PlatformOperations.DeliveryInspect.AuditSlug, + PlatformOperations.DeliveryReplay.AuditSlug, + PlatformOperations.DeliveryReset.AuditSlug, + }; + + [Fact] + public void Every_Registered_Operation_Runs_In_Exactly_One_Place_And_Only_The_Scope_Needs_The_Platform_Role() + { + foreach (var operation in PlatformOperations.All) + { + operation.NeedsPlatformRole.Should().Be(operation.Executor == PlatformOperationExecutor.PlatformScope, operation.AuditSlug); + operation.RunsInPipeline.Should().Be(operation.Executor == PlatformOperationExecutor.Pipeline, operation.AuditSlug); + } + + PlatformOperations.DeliveryReplay.Executor.Should().Be(PlatformOperationExecutor.RecoveryOwner); + PlatformOperations.DeliveryReset.Executor.Should().Be(PlatformOperationExecutor.RecoveryOwner); + PlatformOperations.DeliveryInspect.Executor.Should().Be(PlatformOperationExecutor.PlatformScope); + } + + [Fact] + public void An_Onboarding_Operation_Is_Still_Accepted() + { + var catalog = new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(Request), new PlatformOperatorAct(PlatformOperations.HostMap))]); + + catalog.TryGet(typeof(Request), out var found).Should().BeTrue(); + found.Operation.Should().BeSameAs(PlatformOperations.HostMap); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs new file mode 100644 index 000000000..47cfe8cec --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs @@ -0,0 +1,380 @@ +using System.Diagnostics.Metrics; +using FluentAssertions; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Tenancy.Application.Authorization; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.MultiTenancy; + +/// +/// What the operator act executor and its source decide before a handler runs (ADR-0102 § 1): which +/// requests and admissions it accepts, what context and provenance the act runs under, and that +/// both are gone when the act is. +/// +/// +/// No database and no pipeline: the sender is a double that observes the ambient context and asks the +/// scoped source for a descriptor while the act is in flight, which is the one moment the pair is +/// allowed to answer. +/// +public sealed class PlatformOperatorActExecutorTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 19, 12, 0, 0, TimeSpan.Zero); + private static readonly TenantId Tenant = TenantId.From(Guid.CreateVersion7()); + + private static OperatorProvisionTenantCommand Provision(TenantId? tenant = null) => new( + tenant ?? Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + [Fact] + public async Task An_Admitted_Act_Runs_On_A_Resolved_Ambient_Context_Of_The_Tenant_It_Names_And_Nothing_Else() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + + var result = await rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + result.IsSuccess.Should().BeTrue(); + var seen = rig.Observed.Should().ContainSingle().Subject; + seen.Context.IsResolved.Should().BeTrue(); + seen.Context.TenantId.Should().Be(Tenant); + seen.Context.Origin.Should().Be(TenantContextOrigin.Ambient); + seen.Context.UserId.Should().BeNull("an operator act names no user; the business actor is the registry actor"); + seen.Context.OrganizationId.Should().BeNull(); + seen.Context.HostScope.Should().BeNull(); + seen.Descriptor.Should().NotBeNull(); + seen.Descriptor!.SourceKind.Should().Be(AuthorizationSourceKind.PlatformOperator); + seen.Descriptor.RequestType.Should().Be(); + seen.Descriptor.Operator!.ReasonSlug.Should().Be("tenant_provision"); + seen.Descriptor.Operator.Issuer.Should().Be(TestPlatformAdmissions.Issuer); + seen.MatchedWhileLive.Should().BeTrue("the descriptor answers for its request in its context while the act is in flight"); + } + + [Fact] + public async Task The_Context_And_The_Provenance_Are_Gone_When_The_Act_Is() + { + await using var rig = new Rig(); + var before = Substitute.For(); + rig.Accessor.Current = before; + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + rig.Accessor.Current.Should().BeSameAs(before, "the executor restores what it found, it does not clear it"); + var seen = rig.Observed.Single(); + seen.Descriptor!.IsActive.Should().BeFalse("a descriptor kept past its act proves nothing"); + seen.Descriptor.Matches(typeof(OperatorProvisionTenantCommand), seen.Context).Should().BeFalse(); + seen.Source.Capture(typeof(OperatorProvisionTenantCommand), seen.Context).Should().BeNull( + "the frame is closed, so the same source in the same context answers nothing after the act"); + } + + [Fact] + public async Task A_Failing_Act_Still_Restores_The_Context_And_Closes_The_Provenance() + { + await using var rig = new Rig { Failure = new InvalidOperationException("handler failed") }; + + var act = () => rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + await act.Should().ThrowAsync().WithMessage("handler failed"); + rig.Accessor.Current.Should().BeNull(); + rig.Observed.Single().Descriptor!.IsActive.Should().BeFalse(); + } + + [Fact] + public async Task The_Source_Answers_Only_For_The_Operation_The_Admission_Is_For_And_Only_In_Its_Own_Context() + { + await using var rig = new Rig(); + rig.Probe = (provider, context) => + [ + provider.Capture(typeof(OperatorProvisionTenantCommand), context), + provider.Capture(typeof(OperatorMapHostCommand), context), + provider.Capture(typeof(ProvisionTenantCommand), context), + provider.Capture(typeof(OperatorProvisionTenantCommand), Substitute.For()), + provider.Capture(typeof(MapHostToTenantCommand), context), + ]; + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + var answers = rig.Observed.Single().Probed; + answers[0].Should().NotBeNull("the admitted operation's own request in the context the executor installed"); + answers[1].Should().BeNull("a host mapping is another operation: one admission, one act"); + answers[2].Should().BeNull("the seed command is not an operator act, whatever the context"); + answers[3].Should().BeNull("a context the executor did not install is not the act's"); + answers[4].Should().BeNull("a request whose policy does not name the operator source is not captured, even when the catalog lists it"); + } + + [Fact] + public async Task A_Request_Outside_The_Catalog_Is_Refused_Before_The_Admission_Is_Spent() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + var seed = new ProvisionTenantCommand(Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + + var act = () => rig.Executor.ExecuteAsync(admission, Tenant, seed); + + await act.Should().ThrowAsync(); + rig.Observed.Should().BeEmpty("the sender was never reached"); + admission.TryConsume().Should().BeTrue("a refusal before the act leaves the admission unspent"); + } + + [Theory] + [InlineData("host_map")] + [InlineData("killswitch_toggle")] + public async Task An_Admission_For_Another_Operation_Does_Not_Admit_The_Act(string operation) + { + await using var rig = new Rig(); + var other = operation == "host_map" ? PlatformOperations.HostMap : PlatformOperations.KillswitchToggle; + var admission = TestPlatformAdmissions.Admission(other, issuedAt: Now); + + var act = () => rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + await act.Should().ThrowAsync(); + rig.Observed.Should().BeEmpty(); + admission.TryConsume().Should().BeTrue(); + } + + [Fact] + public async Task The_Platform_Sentinel_And_An_Unassigned_Tenant_Are_Not_Tenants_An_Act_May_Name() + { + await using var rig = new Rig(); + + // An id nobody assigned. Vogen refuses `default` and `new` at compile time; an array element the + // runtime zeroed is the state a deserialized DTO's unset field reaches in production. + var slot = new TenantId[1]; + var unassigned = slot[0]; + foreach (var tenant in new[] { TenantId.PlatformSentinel, unassigned }) + { + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + var act = () => rig.Executor.ExecuteAsync(admission, tenant, Provision(tenant)); + await act.Should().ThrowAsync(); + admission.TryConsume().Should().BeTrue(); + } + + rig.Observed.Should().BeEmpty(); + } + + [Fact] + public async Task A_Stale_Admission_Is_Refused_And_Is_Not_Spent_By_The_Refusal() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission( + PlatformOperations.TenantProvision, issuedAt: Now - PlatformAdmission.MaximumAge - TimeSpan.FromSeconds(1)); + + var act = () => rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + (await act.Should().ThrowAsync()).WithMessage("*stale*"); + rig.Observed.Should().BeEmpty(); + admission.TryConsume().Should().BeTrue("the age check comes before the spend, so a stale admission is simply stale"); + } + + [Fact] + public async Task One_Admission_Admits_One_Act() + { + await using var rig = new Rig(); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now); + await rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + var again = () => rig.Executor.ExecuteAsync(admission, Tenant, Provision()); + + (await again.Should().ThrowAsync()).WithMessage("*already used*"); + rig.Observed.Should().ContainSingle("the second act never reached the pipeline"); + } + + [Fact] + public async Task Each_Act_Is_Counted_By_How_It_Ended() + { + using var counted = new ActCounter(); + await using var rig = new Rig(); + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + rig.Replay = true; + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + rig.Replay = false; + rig.Refusal = new Error(new LocalizedMessage("lockey_business_rule_violation")); + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + rig.Refusal = null; + rig.Failure = new InvalidOperationException("handler failed"); + var failed = () => rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + await failed.Should().ThrowAsync(); + + counted.Outcomes.Should().Equal( + ["tenancy.tenant.create:applied", "tenancy.tenant.create:replayed", "tenancy.tenant.create:refused", "tenancy.tenant.create:failed"]); + } + + [Fact] + public async Task An_Admitted_Act_The_Pipeline_Refuses_As_Forbidden_Is_Logged_As_A_Defect() + { + await using var rig = new Rig(); + rig.Refusal = new Error(new LocalizedMessage("lockey_forbidden")); + + await rig.Executor.ExecuteAsync( + TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), Tenant, Provision()); + + rig.LoggedEvents.Should().Equal([7109], "the warning an operator can alert on, since this refusal writes no audit row"); + } + + [Fact] + public void The_Act_Catalog_Refuses_An_Operation_That_Needs_The_Platform_Role_Or_No_Acts_At_All() + { + var bypass = () => new PlatformOperatorActCatalog( + [new KeyValuePair(typeof(OperatorProvisionTenantCommand), new(PlatformOperations.KillswitchToggle))]); + var empty = () => new PlatformOperatorActCatalog([]); + + bypass.Should().Throw("the platform role is the scope facade's, never a pipeline act's"); + empty.Should().Throw(); + } + + private sealed record Observation( + ITenantContext Context, + ITrustedOperationSource Source, + TrustedOperationDescriptor? Descriptor, + bool MatchedWhileLive, + IReadOnlyList Probed); + + private sealed class Rig : IAsyncDisposable + { + private readonly ServiceProvider _provider; + + public Rig() + { + var catalog = new PlatformOperatorActCatalog( + [ + new(typeof(OperatorProvisionTenantCommand), new(PlatformOperations.TenantProvision)), + new(typeof(OperatorMapHostCommand), new(PlatformOperations.HostMap)), + // A request whose policy admits the seed source and not the operator's: bound in the catalog + // here so the source's own check of the policy's sources is what has to refuse it. + new(typeof(MapHostToTenantCommand), new(PlatformOperations.TenantProvision)), + ]); + var clock = Substitute.For(); + clock.UtcNow.Returns(Now); + var services = new ServiceCollection(); + services.AddSingleton(Accessor); + services.AddSingleton( + new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()])); + services.AddSingleton(clock); + services.AddSingleton(typeof(ILogger<>), typeof(CapturingLogger<>)); + services.AddSingleton(LoggedEvents); + services.AddScoped(_ => new OperatorActGuard( + Substitute.For(), Substitute.For(), + Substitute.For(), Substitute.For())); + services.AddPlatformOperatorActs(catalog); + services.AddScoped(provider => + { + var sender = Substitute.For(); + sender.Send(Arg.Any>>(), Arg.Any()).Returns(_ => + { + var context = Accessor.Current!; + var source = provider.GetServices().Single(); + var descriptor = source.Capture(typeof(OperatorProvisionTenantCommand), context); + Observed.Add(new Observation( + context, source, descriptor, + descriptor?.Matches(typeof(OperatorProvisionTenantCommand), context) ?? false, + Probe?.Invoke(source, context) ?? [])); + if (Replay) + { + provider.GetRequiredService().MarkReplayed(); + } + + if (Failure is not null) + { + return Task.FromException>(Failure); + } + + return Task.FromResult(Refusal is { } refusal + ? Result.FailFor>(refusal) + : Result.Ok(new ProvisionedTenantDto(Tenant, "acme", OrganizationId.From(Guid.CreateVersion7()), "main"))); + }); + return sender; + }); + _provider = services.BuildServiceProvider(); + Executor = _provider.GetRequiredService(); + } + + public StaticTenantContextAccessor Accessor { get; } = new(null); + + public PlatformOperatorActExecutor Executor { get; } + + public List Observed { get; } = []; + + public Exception? Failure { get; set; } + + public bool Replay { get; set; } + + public Error? Refusal { get; set; } + + public List LoggedEvents { get; } = []; + + public Func>? Probe { get; set; } + + public ValueTask DisposeAsync() => _provider.DisposeAsync(); + } + + private sealed class CapturingLogger(List events) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + events.Add(eventId.Id); + } + + /// Records the operation:outcome of every act counted while it is alive. + private sealed class ActCounter : IDisposable + { + private readonly MeterListener _listener = new(); + + public ActCounter() + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName && instrument.Name == PlatformOperatorMetrics.ActCounterName) + { + listener.EnableMeasurementEvents(instrument); + } + }; + _listener.SetMeasurementEventCallback((_, _, tags, _) => + { + string? operation = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "operation") operation = tag.Value as string; + if (tag.Key == "outcome") outcome = tag.Value as string; + } + + lock (Outcomes) + { + Outcomes.Add(operation + ":" + outcome); + } + }); + _listener.Start(); + } + + public List Outcomes { get; } = []; + + public void Dispose() => _listener.Dispose(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj b/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj index 0de2998b7..64412d71f 100644 --- a/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj +++ b/backend/tests/LearnStack.Tests.Unit/LearnStack.Tests.Unit.csproj @@ -9,6 +9,7 @@ + diff --git a/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs b/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs index 3838d4797..ad871c4ea 100644 --- a/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Modules/Tenancy/SeedTenantWriteGuardTests.cs @@ -24,6 +24,7 @@ using LearnStack.SharedKernel.Time; using MediatR; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using Xunit; @@ -392,6 +393,7 @@ public Fixture(int locales = 0, bool second = true, bool host = true, bool resol services.AddSingleton(NoReservedHosts.Instance); services.AddSingleton(NullHostResolutionInvalidator.Instance); services.AddSingleton(Guard); + services.AddSingleton(new OperatorActGuard(execution, context, Unit, Locks)); _provider = services.BuildServiceProvider(); } public ISeedCustomizationPrerequisiteReader Customization { get; } = Substitute.For(); @@ -493,6 +495,10 @@ internal static void Register(ServiceCollection services, ITenantContext context customization.IsCompleteAsync(Arg.Any(), Arg.Any()).Returns(true); services.AddSingleton(customization); services.AddSingleton(); + services.AddSingleton(); + var existence = Substitute.For(); + existence.ExistsAsync(Arg.Any()).Returns(true); + services.TryAddSingleton(existence); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TenancySeedInvocationBehavior<,>)); } diff --git a/backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs new file mode 100644 index 000000000..d4de8bc73 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DeploymentModeParserTests.cs @@ -0,0 +1,48 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Hosting; +using Xunit; + +namespace LearnStack.Tests.Unit.SharedKernel; + +/// The one reading of a deployment mode that the API and the offline tools share. +public sealed class DeploymentModeParserTests +{ + [Theory] + [InlineData("Development", DeploymentMode.Development)] + [InlineData("saas", DeploymentMode.SaaS)] + [InlineData(" Dedicated ", DeploymentMode.Dedicated)] + [InlineData("SELFHOSTEDONLINE", DeploymentMode.SelfHostedOnline)] + [InlineData("selfHostedAirGapped", DeploymentMode.SelfHostedAirGapped)] + public void A_Declared_Name_Is_Read_Without_Regard_To_Case_Or_Padding(string text, DeploymentMode expected) + { + DeploymentModeParser.TryParse(text, out var mode).Should().BeTrue(); + + mode.Should().Be(expected); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("0")] + [InlineData("1")] + [InlineData("-1")] + [InlineData("Development,SaaS")] + [InlineData("Development SaaS")] + [InlineData("Production")] + [InlineData("Sass")] + public void Anything_That_Is_Not_A_Declared_Name_Is_Refused_Ordinals_And_Lists_Included(string? text) + { + DeploymentModeParser.TryParse(text, out _).Should().BeFalse(); + } + + [Fact] + public void Every_Declared_Name_Is_Accepted_As_It_Is_Spelled() + { + foreach (var name in Enum.GetNames()) + { + DeploymentModeParser.TryParse(name, out var mode).Should().BeTrue(name); + mode.ToString().Should().Be(name); + } + } +} diff --git a/docs/architecture/13-identity-and-auth.md b/docs/architecture/13-identity-and-auth.md index 6afee47e1..f9e7344cd 100644 --- a/docs/architecture/13-identity-and-auth.md +++ b/docs/architecture/13-identity-and-auth.md @@ -453,7 +453,9 @@ MFA is a Keycloak responsibility. Enforced for: - Tenant admin accounts (configurable, defaults to mandatory). - Other roles (tenant choice). -LearnStack does not read the `amr` claim today, and the access-token profile admits no assurance claim. A future MFA-gated operation needs an accepted decision that names its claim and source. Brokered sign-ins carry no LearnStack MFA assurance ([ADR-0099](../decisions/0099-confined-tenant-federation.md)). +LearnStack does not read the `amr` claim today, and the access-token profile admits no assurance claim. A future MFA-gated operation needs an accepted decision that names its claim and source; +[ADR-0101](../decisions/0101-platform-operator-authority.md) names `acr` and `auth_time` from the +deployment-controlled operator issuer for Platform operator acts. Brokered sign-ins carry no LearnStack MFA assurance ([ADR-0099](../decisions/0099-confined-tenant-federation.md)). ## Logout diff --git a/docs/architecture/15-event-and-outbox.md b/docs/architecture/15-event-and-outbox.md index 0cc4fd0c4..d8e302c47 100644 --- a/docs/architecture/15-event-and-outbox.md +++ b/docs/architecture/15-event-and-outbox.md @@ -691,7 +691,10 @@ Normal publication excludes that row permanently. The terminalizer writes on one fenced transaction, retaining the envelope for investigation. Audit failure retains terminal work for retry without publication; completed terminal rows leave pending gauges. A far-future availability time is never a terminal marker. -Phase 03 must decide producer reset/fencing before any operator replay endpoint. +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) decides it: a +narrow operator reset admits only a `retry_exhausted` row under the fence +`(attempts, dead_lettered_at)`, renews its six-attempt budget and writes a MUST row on +the same transaction. Every other reason is refused. ### Subscriber side — dispatch succeeded, handling did not @@ -707,8 +710,12 @@ It refuses pending terminalization, completed business deliveries and Pending, privileged, unknown or retired subscriptions. The reset clears attempts, bounded error and terminal state, invalidates old ownership and makes that tuple due. The scheduler later invokes only its executor, never `PublishAsync`. Completed siblings -remain inbox deduplicated; a completed inbox is never reset. Phase 03 owns operator -permission, HTTP routes and the separately decided producer replay contract. +remain inbox deduplicated; a completed inbox is never reset. Operator replay is +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)'s fenced +transition: the request carries `(replay_count, dead_lettered_at, terminal_reason)` +as the inspection showed it, `invalid_envelope` is always refused, the tenant must be +serving, and the MUST row commits with the reset. The producer reset is a separate +request with its own fence. P02b-8 owns erasure inventory, Phase 03 privileged redaction and Phase 11 retention purge. diff --git a/docs/architecture/21-feature-flags.md b/docs/architecture/21-feature-flags.md index c1c0370bb..af3683c37 100644 --- a/docs/architecture/21-feature-flags.md +++ b/docs/architecture/21-feature-flags.md @@ -399,10 +399,11 @@ CREATE TABLE platform_killswitches ( - **Policies** are role-qualified in the `platform_host_to_tenant` shape, with the read widened rather than keyed — a killswitch is global by construction, and hiding it from the role that must honour it would only fail open. Every write is reserved to - `learnstack_platform` through the audited `EnterPlatformAdminScope(reason)` path, which - is what gives `tenancy.killswitch.toggle` a real actor. The class and its policy DDL - live in [Database Standards § Table classes](../standards/05-database.md); the clauses - are deliberately not restated here. + `learnstack_platform` through the audited, admission-gated platform scope, which is + what gives `tenancy.killswitch.toggle` a MUST result row naming the operator. The + class and its policy DDL live in + [Database Standards § Table classes](../standards/05-database.md); the clauses are + deliberately not restated here. - **Reads go through the L1 cache**, not to the table per request, and are invalidated on toggle. Holding the answer needs a second allowed platform cache-key family, `platform:tenancy:killswitch`; `CacheKey.EnsureValid` admits that family and the host @@ -417,13 +418,14 @@ CREATE TABLE platform_killswitches ( **Packet 9 shipped the table and the read path, and no writer** ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). -The reason is reachability rather than scheduling: every killswitch write runs inside -`EnterPlatformAdminScope(reason)`, and the registered `IPlatformAdminGate` is -`DenyAllPlatformAdminGate` until the Platform-scope permission arrives with the registry -in [Phase 03](../roadmap/phase-03-identity-admin.md). A toggle command shipped now would -be unreachable code with a permission key nothing registers. **Phase 03 owns the toggle -command, its permission and its runbook**; every gated read honours a flipped switch the -day one exists, and what is absent until then is the flipping. +The reason was reachability rather than scheduling: every killswitch write runs inside +`EnterPlatformAdminScope`, and no Platform gate existed. **P03-9 Step 1 ships the +writer** as a service entered with an operator admission for +`platform.killswitch.write`, with a MUST result row on the same transaction and the +overlay cache entry dropped after the commit +([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)). Other instances see +the flip within the overlay's 60-second TTL; the +[killswitch runbook](../runbooks/killswitch.md) says so, and that the read fails open. A flippable killswitch pairs with a runbook entry describing when to use it and how to restore, and the obligation attaches to the phase that makes it flippable, not to the @@ -455,12 +457,14 @@ Both surfaces are MUST-audit security-events (see the inbound Hub event carries `hub_event_id` and is mirrored into an audit entry (`tenancy.entitlement.refresh`) with `before` and `after` snapshots of the `features` / `limits` jsonb. -- Killswitch flips are logged as `tenancy.killswitch.toggle` with the platform-admin - actor and a free-text reason field that the operator console makes required. The - classification is written ahead of the command: Packet 9 ships no writer, and - [Phase 03](../roadmap/phase-03-identity-admin.md) lands the toggle that raises the row - ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). - The operation is not a MediatR request, so its catalogue entry is registered by slug +- Killswitch flips are logged as `tenancy.killswitch.toggle`, a MUST row written on the + flip's own transaction by the witness-bound result method. The row names the operator + in `metadata.operator` (issuer, subject digest, accepted `acr`, executor) and carries + the closed reason slug `killswitch_toggle`; the optional ticket is on the + sentinel-tenant row only + ([ADR-0101 § 9](../decisions/0101-platform-operator-authority.md), + [runbook](../runbooks/killswitch.md)). The operation is not a MediatR request, so its + catalogue entry is registered by slug ([ADR-0044 Amendment 3 § 1](../decisions/0044-audit-write-path.md)). ## Risks @@ -503,8 +507,9 @@ Both surfaces are MUST-audit security-events (see the `AlterColumn` that makes `valid_until` nullable; `platform_killswitches`, the overlay and its cache family, read-only until Phase 03 ships the toggle; the architecture tests. -- **Phase 03** — the killswitch toggle command, its Platform-scope permission, the - permitting `IPlatformAdminGate` and the runbook that pairs with a flippable switch. +- **Phase 03** — the killswitch writer, its Platform-scope permission, the operator gate + ([ADR-0101](../decisions/0101-platform-operator-authority.md)) and the runbook that + pairs with a flippable switch. - **Phase 02c** (parallel Hub Foundation) — `HubEntitlementProvider` and the HTTPS projection push (`PUT /api/internal/tenants/{id}/entitlements`) that drives `RefreshAsync`. Limit **enforcement** lands here too — the `403` refusal and the diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 4c1fe39a6..201da2e43 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -62,10 +62,11 @@ platform-scoped, application-read-only `identity_authority` singleton owns the stable authority UUID and current exact issuer URI. The deployment installer creates it once with migration credentials before bootstrap; application code cannot insert, update or automatically replace it. Configuration issuer drift -refuses identity admission. P03-9/G13 owns an approved issuer rebind before the -first change, proving provider continuity and freezing bootstrap and old grants -while preserving authority, keys, actors and closed tombstones. Until that owner -is implemented, issuer renaming is unsupported; aliases and email matching supply +refuses identity admission. The only change is the controlled issuer rebind of +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md), an offline tool on a +confined role that proves provider continuity against the new realm and freezes starts +and User creation while it runs, preserving authority, keys, actors and closed +tombstones. Any other issuer change is unsupported; aliases and email matching supply no continuity proof. The subject key is SHA-256 over domain-separated, length-delimited stable @@ -227,7 +228,7 @@ remain in Database Standards: [Outbox](../standards/05-database.md#outbox), | Store | Copies and subject linkage | Existing constraint | |---|---|---| -| `outbox_messages` | `actor_user_id`, identifier-only `payload`, tenant/org, partition/causation/event IDs and `correlation_id`; new producer `metadata` is SQL NULL | Platform has SELECT/DELETE, no envelope rewrite grant | +| `outbox_messages` | `actor_user_id`, identifier-only `payload`, tenant/org, partition/causation/event IDs and `correlation_id`; new producer `metadata` is SQL NULL | Platform has `DELETE` and `SELECT` of twelve metadata columns only ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)), no envelope rewrite grant | | `event_deliveries` | Independent per-subscription envelope/`payload` copy with `actor_user_id`, tenant/org, causation/trace/partition, lease, closed failure descriptor and dead-letter/replay state | No DELETE grant to runtime roles; producer cleanup does not erase this copy | | `inbox_messages` | `(tenant_id, subscription_id, event_id)` and `recorded_at`; indirect subject linkage without actor, payload or org columns | Immutable completion history; no generic Platform purge | | `background_jobs` | `causal_actor_user_id`, identifier-only `parameters`/`plan`, trace/causation, lease, closed failure/terminal descriptors and parent/recipient/operation/final-attempt links | Envelope/prepared facts stay immutable; uncertain effects retain occupancy | @@ -504,10 +505,14 @@ remains in the phase Status block. grants, immutable-fact treatment, dependency/deletion order, replay/deduplication floor and evidence of completion. No such authority or policy is chosen by this inventory. Ordinary SystemActor delivery and dispatcher credentials supply none. -- `learnstack_platform` has no grants on inbox, delivery or LearnStack job - tables. `BYPASSRLS` bypasses policies, not SQL privileges, no-delete triggers or - write-once facts. Any required authority change needs its own bounded decision - and migration before the writer ships. +- `learnstack_platform` has no grant on inbox or delivery payloads, a job's + parameters or plan, or any outbox envelope column. It reads named metadata columns + of `outbox_messages`, `event_deliveries`, `background_jobs` and + `background_job_reservations` for the operator inspection of + [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), and keeps + `DELETE` on `outbox_messages` for the retention purge. `BYPASSRLS` bypasses policies, + not SQL privileges, no-delete triggers or write-once facts. Any further authority + change needs its own bounded decision and migration before the writer ships. - Live/uncertain effects, reservation accounting, immutable execution evidence, monotonic progress and same-transaction MUST audit remain intact. Erasure, elapsed time and operator authority prove neither quiescence nor permission to diff --git a/docs/architecture/28-platform-tenant-organization.md b/docs/architecture/28-platform-tenant-organization.md index c44e3b116..18ed4630d 100644 --- a/docs/architecture/28-platform-tenant-organization.md +++ b/docs/architecture/28-platform-tenant-organization.md @@ -58,8 +58,11 @@ flowchart TB LearnStack operators manage tenant lifecycle, plans, subscriptions, license issuance, custom domain admin, compliance caps. -LearnStack operators authenticate against the `learnstack-hub` Keycloak realm. They do -**not** have tenant data access; Hub holds tenant metadata only (ADR-0019). +LearnStack operators authenticate against the `learnstack-hub` Keycloak realm. They have +no tenant data access through the Hub, which holds tenant metadata only (ADR-0019). +Platform operator acts on LearnStack itself are permissioned, attributed and audited +([ADR-0101](../decisions/0101-platform-operator-authority.md)), and reach tenant data +only through the operations ADR-0102 to ADR-0104 define. ### Layer 2 — Tenant (LearnStack's customer) @@ -210,8 +213,8 @@ domain-specific shape comes from the tenant's customization data (ADR-0018). ## 5. Hub responsibilities (what LearnStack operators do) -Operators (LearnStack staff) work through Hub. They do **not** access tenant data; they -manage: +Operators (LearnStack staff) work through Hub. The Hub does **not** access tenant data; +they manage: - **Tenant lifecycle**: provision, suspend, archive, terminate. - **Plans & subscriptions**: define plans (features + limits + price), assign to tenants, diff --git a/docs/architecture/30-api-gateway.md b/docs/architecture/30-api-gateway.md index 6369e82e8..536737fe7 100644 --- a/docs/architecture/30-api-gateway.md +++ b/docs/architecture/30-api-gateway.md @@ -540,10 +540,10 @@ Phase 11 deliverables: - [ ] Per-tenant rate-limit override (consumer keys; requires etcd mode). - [ ] `KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true` for Keycloak issuer split (Docker network vs browser); document in 13-identity-and-auth.md. -- [ ] Hangfire dashboard route gated by BasicAuth at the gateway and the - application's Platform-scope permission; Phase 03 owns the dated ADR-0015 - disclosure before mapping, and Phase 11 owns gateway qualification. - (backend). +- [ ] The Hangfire dashboard stays unmapped + ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), ADR-0015 + Amendment 2). Any future admission needs its own decision and a Platform-scope + permission, and Phase 11 owns gateway qualification. - [ ] Production CORS allow-list (no `localhost`). - [ ] OpenAPI dev route gated by environment (404 in prod). - [ ] Real client IP forwarding via `real-ip` configured with trusted L4 LB ranges only. diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index be0d70bbd..ab3680f73 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -265,12 +265,25 @@ registers `platform.delivery.dead_letter`, both off-path under Tenancy. The subscriber witness binds the actual tenant/subscription/event tuple and uses a validated attempt trace without causal-envelope or payload SELECT. Outcome success describes terminal state, not publication. Producer terminal audit omits invalid -causal fields in favor of a fresh validated attempt trace. +causal fields in favor of a fresh validated attempt trace. The operator's reset of a +dead-lettered row is a sibling seam, `WriteOperatorRecoveryAsync` +([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)): its witness +carries the admitted operator and the fence before and after, the row names the real +event tenant with no actor and no ticket, and the outbox role needs no new policy arm +because it bypasses row security and already holds `INSERT`. Absent optional causal IDs are valid and do not alone invalidate the stored trace. Closed terminal values use bounded metadata; `Reason` stays for platform entry. Audit failure retains terminal work for retry without delivery; uncertain COMMIT is reconciled before retry and cannot duplicate a completed terminal audit. +The platform scope's intent seam, `WritePlatformOperatorIntentAsync` +([ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md)), is the sibling for an +operator act whose effect is outside the database: the scope handle's checkpoint writes +the intent row on the operation's attempt slug with the outcome `indeterminate`, commits +it, and only then lets the provider be called; the result row follows on a fresh +transaction. An effect that fails afterwards leaves the intent row standing, and the +result row is refused before an intent that its operation declares. + The existing outbox role gains audit INSERT-only in the Audit chain, with exact grants owned by [Database Standards](../standards/05-database.md#grant-matrix). Routine confined poll/claim/mark uses the accepted bounded audit exemption; @@ -1397,18 +1410,17 @@ guards are specified only in the Database standard: | Ordinary unresolved context, not provisioning/global identity | no row — there is no admitted attribution owner | — | **The third row has exactly one user in Packet 9**: entry into -`EnterPlatformAdminScope(reason)` itself, which is not a MediatR request and writes its own -row through the fourth write path. `tenancy.killswitch.toggle` — the operation +`EnterPlatformAdminScope(reason)` itself, which is not a MediatR request and writes its +own row through the fourth write path. `tenancy.killswitch.toggle` — the operation [ADR-0044 § 1](../decisions/0044-audit-write-path.md) names as the first to be performed -*inside* that scope — ships no writer here: the registered gate is -`DenyAllPlatformAdminGate` and the Platform-scope permission arrives with the registry in -[Phase 03](../roadmap/phase-03-identity-admin.md), which owns the toggle command -([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). +*inside* that scope — shipped no writer in Packet 9; P03-9 Step 1 ships it as a service +entered with an operator admission +([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), +[ADR-0045 Amendment 5](../decisions/0045-entitlement-and-feature-flag-socket.md)). [The Tenancy matrix](../modules/tenancy/audit.md) classifies it MUST and marks it -**both** `(off-path)` and `(planned)`: off-path because the scope is entered by a service -method rather than by a MediatR request, so there is no request type to key a catalogue -entry on (§ 13); planned because no writer performs it in this packet. A cell carries -every marker that applies, and this is the row that carries two. +`(off-path)`: the scope is entered by a service method rather than by a MediatR request, +so there is no request type to key a catalogue entry on (§ 13). It carried `(planned)` +as well until its writer shipped; a cell carries every marker that applies. The organization column is decided from the same source as the tenant and at the same moment, which is what keeps the two paths agreeing. On the in-transaction path the diff --git a/docs/decisions/0003-tenant-isolation-defense-in-depth.md b/docs/decisions/0003-tenant-isolation-defense-in-depth.md index 47f2c8448..d051feb07 100644 --- a/docs/decisions/0003-tenant-isolation-defense-in-depth.md +++ b/docs/decisions/0003-tenant-isolation-defense-in-depth.md @@ -600,3 +600,16 @@ global directory or generic bypass is added. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +## Amendment 14 — Confined identity-rebind role (2026-11-19) + +Accepted [ADR-0104](0104-controlled-issuer-rebind.md) adds `learnstack_identity_rebind`, +a sixth login role without `BYPASSRLS`, beside the fifth role of Amendment 13. It is +used only by an offline rebind tool. Its grants are `SELECT` and `UPDATE (issuer)` on +`identity_authority`, `SELECT` of four columns on `users`, and an `INSERT` on +`audit_log` that a policy limits to the platform sentinel, the identity module and the +two rebind operations. Its credential is never configured on an API or worker host. The +grants of the other roles and the canonical policy template are unchanged. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0004-authentication-strategy.md b/docs/decisions/0004-authentication-strategy.md index 362cd0805..3f1cdd7a1 100644 --- a/docs/decisions/0004-authentication-strategy.md +++ b/docs/decisions/0004-authentication-strategy.md @@ -84,3 +84,18 @@ user under the same identity, and vice versa. ## Amendment 2 — Federation adapter boundary (2026-11-13) Accepted [ADR-0099](../decisions/0099-confined-tenant-federation.md) adds the first runtime Keycloak adapter that writes to the Admin REST API, scoped to tenant-brokered identity-provider configuration. Its port is `IFederationProvider`, not the `IIdentityProvider` named in the Consequences above, which remains unimplemented. The domain depends on no provider type, and the adapter lives in `LearnStack.Infrastructure.Identity.Federation`. Realm-level brokering stays the mechanism of Amendment 1; ADR-0099 specifies its confinement. Tenants receive no realm administration authority. + +## Amendment 3 — Operator scheme at LearnStack (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) admits Amendment 1's operator +on LearnStack. A second bearer scheme, `PlatformOperator`, accepts a token from the +`learnstack-hub` realm, or from another issuer the deployment controls, for audience +`learnstack-platform` and a public PKCE client, with a lifetime of at most 15 minutes +and MFA shown by the `acr` and `auth_time` claims. It requires no `scope: "platform"` +claim and is confined to `/api/platform/v1`, which is what "platform endpoints" means +here. The Hub service-account chain stays independent of the operator JWT, and the +tenant scheme still refuses the operator issuer. Realm-level MFA enforcement stays Phase +11. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0015-api-gateway-apisix.md b/docs/decisions/0015-api-gateway-apisix.md index 9f2b0da29..27f5c082e 100644 --- a/docs/decisions/0015-api-gateway-apisix.md +++ b/docs/decisions/0015-api-gateway-apisix.md @@ -310,3 +310,22 @@ replay/reconciliation permission and surface; Phase 11 retains the edge surround Platform protection remains required for any later operator surface. No gateway, permission or recovery route is implemented by this acceptance. + +### Amendment 2 — Hangfire dashboard guidance withdrawn (2026-11-19) + +This amendment quotes and withdraws one bullet of the section "Architecture tests / CI +gates": "Hangfire dashboard route (`/admin/hangfire*`) gated by both APISIX (BasicAuth +or JWT) and backend (`HangfireAuthFilter.IsInRole("platform-admin")`). Architecture test +fails if the backend filter is bypassed in any environment." A realm-role gate +contradicts [Standard 19](../standards/19-permissions.md), the named filter and test do +not exist, and a gateway BasicAuth credential is shared, so it attributes no human. + +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md) replaces it. No dashboard is +mapped and `/admin/hangfire*` stays absent in every deployment mode. Any future +admission needs a Platform-scope permission through the operator gate of +[ADR-0101](0101-platform-operator-authority.md), never a realm role, and its own +decision. Phase 11 keeps the APISIX surround. Amendment 1 is unaffected. This is a +withdrawn design statement, not an ADR-0041 correction. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0033-audit-durability-model.md b/docs/decisions/0033-audit-durability-model.md index a684e47e9..964ccfd73 100644 --- a/docs/decisions/0033-audit-durability-model.md +++ b/docs/decisions/0033-audit-durability-model.md @@ -861,3 +861,33 @@ adds the separately attributed per-occurrence claim-context assertion record; ADR-0065's host allowance does not apply. P03-2 implements/proves this accepted extension before activation. Other durability rules and historical Accepted body/status/date remain unchanged. + +## Amendment 13 — Operator evidence in authorization audit composition (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds `PlatformOperator` as a +source of the authorization audit context. For that source the composition admits a null +actor, a closed reason slug and the fixed `metadata.operator` members of +[ADR-0101](0101-platform-operator-authority.md), as it admits a null actor only for the +seed source today. The in-transaction rule is unchanged: an operator act on the app role +writes its MUST rows in its own transaction under the real target tenant. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +## Amendment 14 — An operator act's authorization refusal writes no durable row (2026-11-19) + +Amendment 12 makes an authorization refusal a MUST `identity.authorization.deny` event. +For the `PlatformOperator` source of [ADR-0102](0102-production-tenant-onboarding.md) +the authorization evidence coordinator writes none, in either of its denial paths. +Operator refusals follow the decision [ADR-0101](0101-platform-operator-authority.md) § +11 records for denied entry: a counter and a log line by closed cause at the gate. An +authorization refusal inside an admitted act can only mean the request, source or +context was not what the executor built; the executor counts the act as `refused`, logs +event 7109 as a Warning, and the act fails closed with its response, with no durable +row. The pipeline's other rows are unchanged: a business refusal of an admitted act +writes the ordinary `failed` MUST row in the target tenant with `metadata.operator`, and +a success writes its MUST rows in the act's own transaction. Every other source keeps +Amendment 12 as written. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0036-tenant-resolution-trusted-inputs.md b/docs/decisions/0036-tenant-resolution-trusted-inputs.md index fd8a4551c..a6692bb91 100644 --- a/docs/decisions/0036-tenant-resolution-trusted-inputs.md +++ b/docs/decisions/0036-tenant-resolution-trusted-inputs.md @@ -1406,3 +1406,51 @@ origin inferred from provider data. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +### Amendment 21 — Platform URL space and confined operator target (2026-11-19) + +> **Erratum — 2026-11-19.** The second paragraph below says the target tenant of an +> admitted operator act is announced "by one confined setter". No setter was added: the +> operator act executor installs a resolved ambient context for the target and the +> ordinary transaction behavior announces it; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four` and `PlatformOperatorActExecutorTests`. +> The Decision is unchanged. Current authority: Amendment 22 below. Recorded in +> Amendment 22. + +Accepted [ADR-0101](0101-platform-operator-authority.md) fixes the platform URL space +this record left open: `/api/platform/v1/*`, unclassified by host like `/api/internal` +and authenticated by the operator scheme. This record's sentence that operator +cross-tenant work enters through `/api/internal/*` under the Hub chain is read as the +Hub's machine chain only, which carries no human operator. A human operator act uses the +platform prefix. + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds one announcement: the +target tenant of an admitted operator act, declared by the operation and never taken +from a header, query, cookie or body of an ordinary route, is announced to the unit of +work by one confined setter. The rule that no route resolves a tenant from a +request-supplied override stands for every route that resolves context from a host or a +claim. + + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +### Amendment 22 — The operator target is an executor-installed context (2026-11-19) + +Amendment 21 said the target tenant of an admitted operator act is announced by one +confined setter. As built by [ADR-0102](0102-production-tenant-onboarding.md) there is +no setter: `PlatformOperatorActExecutor` consumes the single-use admission, opens a +fresh scope and installs an immutable resolved context with `Ambient` origin, no user, +no organization and no host scope, for the tenant the operator named in the path of a +`/api/platform/v1/tenants/{tenantId}` route. It is the fifth writer of +`ITenantContextAccessor.Current`, alongside the four of Amendment 2, and +`SetTenant_Callers_Are_The_Enumerated_Four` names its file. The target comes from that +route's path and from nothing an ordinary route supplies; the rule that no route +resolves a tenant from a request-supplied override stands for every route that resolves +context from a host or a claim, and the operator surface resolves none. A request type +outside the executor's closed catalog, an admission for another operation, the platform +sentinel and an unassigned tenant are refused before the admission is spent. + +The Decision, Status, Date and prior amendments of this record are unchanged, apart from +the inline erratum beside Amendment 21. Acceptance of the linked records is not proof +that anything they decide is implemented. diff --git a/docs/decisions/0040-ambient-unit-of-work.md b/docs/decisions/0040-ambient-unit-of-work.md index 7c4e7049b..255124123 100644 --- a/docs/decisions/0040-ambient-unit-of-work.md +++ b/docs/decisions/0040-ambient-unit-of-work.md @@ -1002,3 +1002,50 @@ reader, outside that connection and its announcement. That read is no setter sta and writes nothing. Amendment 22's text is unchanged; the P03-8 Step 4 review round 2 (C5-4) in the [Phase 03 delivery log](../roadmap/phase-03-delivery-log.md) records the finding. + +### Amendment 24 — Eleventh logical setter: operator target (2026-11-19) + +> **Erratum — 2026-11-19.** The paragraph below counts an eleventh logical tenant +> setter, four unchanged context writers and a ninth definer. All three counts were +> wrong: there is no new setter (the census stays at fourteen), the context writers are +> five, and the resolver is the sixteenth definer; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four`, `GlobalIdentitySchemaTests` and +> `PlatformOperatorActExecutorTests`. The Decision is unchanged. Current authority: +> Amendment 25 below. Recorded in Amendment 25. + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) adds the eleventh logical +tenant setter, confined to the `PlatformOperator` source. It reads the target of an +admitted operation, announces it once per unit of work and refuses any other caller. The +four context writers do not change. The single-act resolver that maps a provider subject +to a `UserId` is a ninth definer function; its signature, owner, body and ACL land in +[Standard 05](../standards/05-database.md) with the packet that ships it. + + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +### Amendment 25 — Operator acts: a fifth context writer, no new setter (2026-11-19) + +Amendment 24 recorded accepted [ADR-0102](0102-production-tenant-onboarding.md) as +adding an eleventh logical tenant setter, leaving the four context writers unchanged and +counting the subject resolver as the ninth definer. The packet that implements it shows +all three counts wrong. + +- **No setter.** The operator act executor installs an immutable, resolved, ambient + context for the admitted target tenant, with no user, organization or host scope, and + the ordinary transaction behavior announces it as it announces a seed, delivery or job + context. The logical tenant setters stay at fourteen (Amendments 22 and 23). The + platform role is not used and the unit of work gains no method. +- **A fifth context writer.** The executor is the fifth writer of + `ITenantContextAccessor.Current`, named by file in + `SetTenant_Callers_Are_The_Enumerated_Four`, which keeps its name because three + Accepted records and the catalogue cite it. The claim that the four writers do not + change was unachievable: the query filters and the transaction behavior read the + accessor. +- **The sixteenth definer.** `fn_identity_operator_resolve_user(uuid, bytea)` follows + the fifteen the schema carried before it; [Standard 05](../standards/05-database.md) + carries its signature, owner, body and ACL. + +The Decision, Status, Date and prior amendments of this record are unchanged, apart from +the inline erratum beside Amendment 24. Acceptance of the linked records is not proof +that anything they decide is implemented. diff --git a/docs/decisions/0044-audit-write-path.md b/docs/decisions/0044-audit-write-path.md index d2815d6b1..256efc2c1 100644 --- a/docs/decisions/0044-audit-write-path.md +++ b/docs/decisions/0044-audit-write-path.md @@ -1309,3 +1309,57 @@ with SystemActor distinct from the affected subject and provider outcome. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +## Amendment 17 — Platform operator rows and witness-bound result writes (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md), +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md) and +[ADR-0104](0104-controlled-issuer-rebind.md) extend the seams of Amendment 14 by name: + +- The platform-scope class of § 1 includes a platform-wide MUST result row written on + the scope's work transaction through a new witness-bound method. + `WritePlatformScopeAsync` keeps its single entry-row caller and the § 10 entry-row + rule. +- Operator audit rows carry `actor_user_id` NULL, a closed reason slug, the correlation + id and `metadata.operator` with `issuer`, `subjectDigest`, `kind`, `acr` and + `executor`. The ticket appears only in sentinel-tenant rows. `AuditEntryDraft.Reason` + stays a closed slug. +- Two outbox-role witness kinds for targeted replay and producer reset, distinct from + the terminal witness, and two rebind methods for `learnstack_identity_rebind`. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +## Amendment 18 — Platform scope intent checkpoint (2026-11-20) + +Accepted [ADR-0099](0099-confined-tenant-federation.md) Amendment 10 gives two operator +acts an effect outside the database, in the identity provider: a removal and a disable +of a broker. The maintainer approved this seam before it was written, because the +platform scope of Amendment 17 writes one result row and closes at commit, which leaves +nothing durable before such an effect. [ADR-0099](0099-confined-tenant-federation.md) +Amendment 11 records the implementation. + +- **One new witness-bound write, the fifteenth.** + `IAuditStore.WritePlatformOperatorIntentAsync` writes the intent row of a + platform-scope act on its `PlatformOperation.AttemptAuditSlug`, with the outcome + `indeterminate`, the same closed reason, correlation id and `metadata.operator` as + the result row, the actor NULL and the class MUST. Like the result method it is bound + to the admission, takes the real target tenant, refuses a ticket on a tenant-readable + row and refuses the identity module's own rows. An operation with no attempt slug, or + one that does not enter the platform scope (the offline rebind, whose intent has its + own method), presents none. +- **A checkpoint on the scope handle.** `IPlatformAdminScopeHandle.WriteIntentAsync` + writes that row on the work transaction, commits it, and continues the scope in a + fresh transaction on the same connection. It is allowed once, only for an operation + that declares an attempt slug, and the result row of such an operation is refused + before it. A failure to write or to commit the intent row throws + `AuditWriteFailedException` and the effect must not start; an effect that fails + afterwards leaves the intent row standing, as § 10 requires of the entry row. The + scope still ends at the result row and the commit, or by disposal, which rolls back + whatever followed the checkpoint. +- **Declared like every off-path slug.** The attempt slugs are declared off-path + MUST/SecurityEvent in the Tenancy catalogue source beside the entry and result slugs, + and the scope refuses entry when any of them is undeclared. + +The Decision, Status, Date and prior amendments of this record are unchanged. +Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0045-entitlement-and-feature-flag-socket.md b/docs/decisions/0045-entitlement-and-feature-flag-socket.md index 3ea754b7a..e60e925a2 100644 --- a/docs/decisions/0045-entitlement-and-feature-flag-socket.md +++ b/docs/decisions/0045-entitlement-and-feature-flag-socket.md @@ -623,6 +623,29 @@ against the `platform_entitlement_cache` columns Packet 6 created. which records the mapping; and `EntitlementProjection`'s remarks in `IEntitlementProvider.cs`. No other Accepted ADR's body changes. +## Amendment 5 — Killswitch writer shape (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) § 13 lifts the withholding of +Amendment 1 § 4 once the writer ships. It is a service entered through the Platform +gate, not a MediatR request. `toggled_by` stays NULL because an operator is not a +`users` row, the bounded ticket goes in the `reason` column (see Amendment 6), the MUST +result row commits on the work transaction, and the overlay cache entry is removed after +the commit, including an indeterminate one. Section 5's statement that the scope gives +the row a real actor is read as the `metadata.operator` attribution; the shipped scope +writes a null actor. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +## Amendment 6 — The ticket is not stored in `platform_killswitches` (2026-11-19) + +Amendment 5 repeated [ADR-0101](0101-platform-operator-authority.md) § 13, which put the +bounded ticket in the `reason` column. +[ADR-0101 Amendment 1](0101-platform-operator-authority.md) corrects that: the +application role reads this table, and a ticket never appears in a row a tenant's +connection can reach. The writer leaves `reason` NULL and the ticket is on the sentinel +audit rows. Section 5's table definition is unchanged. + ## References - [ADR-0021 Feature-Based Entitlement Model](0021-feature-based-entitlement.md) diff --git a/docs/decisions/0046-durable-event-delivery-and-recovery.md b/docs/decisions/0046-durable-event-delivery-and-recovery.md index 04d4f5351..6edc825c6 100644 --- a/docs/decisions/0046-durable-event-delivery-and-recovery.md +++ b/docs/decisions/0046-durable-event-delivery-and-recovery.md @@ -524,6 +524,20 @@ general exemption. The producer/subscriber delivery policy, five existing audit writes and their shipped receipts remain unchanged. P02b-4 implements the new job control/seam and their proof obligations; acceptance claims no job runtime. +### Amendment 5 — Operator replay and reset contract (2026-11-19) + +Accepted [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) supplies the +"separately specified reset/fencing contract" this record requires before any operator +replay ships. Two transitions run on a confined owner that uses the outbox-role +credential and is a second status writer beside the dispatcher: targeted subscriber +replay, fenced and filtered by terminal reason, and a producer reset limited to +`retry_exhausted`. Neither adds a write grant. "Permanently excluded from dispatch" is +read as: until an operator reset under that record. Result audit uses two new witness +kinds. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + ## References - [ADR-0006](0006-events-and-outbox.md), [ADR-0010](0010-cross-module-communication.md) diff --git a/docs/decisions/0047-transactional-background-job-runtime.md b/docs/decisions/0047-transactional-background-job-runtime.md index 43c89278b..f4e69e8f8 100644 --- a/docs/decisions/0047-transactional-background-job-runtime.md +++ b/docs/decisions/0047-transactional-background-job-runtime.md @@ -1030,3 +1030,16 @@ source/operation/permission/audit/storage details live in Standards 01/04/05/07/11/18/19/20/21 and the Identity/Tenancy specifications. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and source-bound qualification; acceptance supplies no runtime proof. + +### Amendment 7 — Operator reconciliation is inspection only (2026-11-19) + +Accepted [ADR-0103](0103-operator-recovery-of-asynchronous-work.md) reads the "audited +operator reconciliation" that Phase 03 owns as metadata inspection only. No job requeue, +retry, probe re-arm or reservation release exists, quarantine stays nonterminal with +retained reservations, and no dashboard is mapped. For inspection, `learnstack_platform` +receives `SELECT` on named metadata columns of the job tables; this record's statement +that the platform role has no job privileges is read as applying to every other column +and to every write. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0064-tenant-api-authentication-boundary.md b/docs/decisions/0064-tenant-api-authentication-boundary.md index 78dbc5255..908c942a6 100644 --- a/docs/decisions/0064-tenant-api-authentication-boundary.md +++ b/docs/decisions/0064-tenant-api-authentication-boundary.md @@ -707,3 +707,14 @@ qualification; acceptance supplies no runtime proof. ### Amendment 8 — Federation adapter outside the API bearer boundary (2026-11-13) P02b-5 introduced no Keycloak admin adapter. [ADR-0099](../decisions/0099-confined-tenant-federation.md) adds one, `IFederationProvider`, confined to tenant-brokered identity-provider configuration. It uses a dedicated confidential client with `manage-identity-providers` only, admits a closed list of calls, and grants no tenant authority. The tenant API bearer boundary and the closed access-token profile are unchanged. Brokered ID tokens carry an `idp` claim that the BFF reads only for provenance and host binding; it is not an API authorization input. + +### Amendment 9 — Second scheme confined to the operator prefix (2026-11-19) + +"Register exactly one bearer scheme for the tenant API" stands: the tenant scheme is the +only scheme on `/api/v1`. Accepted [ADR-0101](0101-platform-operator-authority.md) +registers a second scheme, `PlatformOperator`, confined to `/api/platform/v1`. It never +authenticates a tenant route, and the tenant scheme still refuses the operator issuer +and `scope=platform`. "Platform execution remains unavailable to this scheme" stands. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0072-application-owned-identity-bootstrap.md b/docs/decisions/0072-application-owned-identity-bootstrap.md index 26e17c908..56b773680 100644 --- a/docs/decisions/0072-application-owned-identity-bootstrap.md +++ b/docs/decisions/0072-application-owned-identity-bootstrap.md @@ -401,3 +401,14 @@ and qualification; acceptance alone installs no runtime subject. ### Amendment 5 — Federation adapter does not allocate identity (2026-11-13) Amendment 2 mentions no runtime provider administrator in the context of identity allocation. [ADR-0099](../decisions/0099-confined-tenant-federation.md) adds a runtime provider adapter for tenant-brokered identity-provider configuration. It allocates no identity, reissues no subject and merges no email. The rejection of a provider allocator or runtime Admin API for identity allocation in Option 2 stands. A brokered person without a LearnStack binding enters through the existing global-self path and its opt-in budgets. + +### Amendment 6 — Production path and controlled rebind (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) supplies the production path +for tenant, host, Role-template and first-administrator setup, and Accepted +[ADR-0104](0104-controlled-issuer-rebind.md) supplies the controlled issuer rebind. +Rename stays unsupported until the packet that ships the rebind merges. The seed stays a +development tool, and the Seeder refuses to run outside Development. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md index 3cccd6b23..9275d0986 100644 --- a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md +++ b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md @@ -406,3 +406,28 @@ owns persistence, isolation and commit-spanning fences. Historical Accepted body, Status, Date, Deciders and prior rationale remain unchanged. Acceptance registers the bounded contract; actual P03-5 implementation and source-bound proof remain owned by the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). + +### Amendment 8 — Production first administrator and recovery (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) admits operator commands for +the first tenant-wide administrator and for recovery. Separate transactions stay. The +first-admin predicate, no Membership history, differs from the recovery predicate, no +active tenant-wide administrator, and both run under the ordered locks of +[ADR-0074](0074-membership-admission-under-ordered-locks.md). The statement that the +fixed seed capability grants no operator or system bypass stands. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +### Amendment 9 — Controlled issuer rebind (2026-11-20) + +Accepted [ADR-0104](0104-controlled-issuer-rebind.md) is the only path that changes +`identity_authority.issuer`, and it changes nothing else. It preserves `AuthorityId`, +the subject keys, the actor ids and the closed tombstones that this record's identity +foundation fixes, and it reads `users` through four columns of a confined sixth role +without adding an update or a delete owner for `users`. A trigger refuses any change +of the authority's `id` or `authority_id` for every role. The statements that the +anchor is installed once and that no runtime process rebinds it stand. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0074-membership-admission-under-ordered-locks.md b/docs/decisions/0074-membership-admission-under-ordered-locks.md index 3bc777e84..75168c8ce 100644 --- a/docs/decisions/0074-membership-admission-under-ordered-locks.md +++ b/docs/decisions/0074-membership-admission-under-ordered-locks.md @@ -244,3 +244,12 @@ or strongest-plan/no-upgrade rule. Historical Accepted body, Status, Date, Deciders and prior rationale remain unchanged. Acceptance registers the bounded contract; actual P03-5 implementation and source-bound proof remain owned by the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). + +### Amendment 2 — Operator recovery predicate under the ordered locks (2026-11-19) + +Accepted [ADR-0102](0102-production-tenant-onboarding.md) evaluates its recovery +predicate, no active tenant-wide administrator, inside the transaction and under this +record's ordered locks, not as a prior check. The lock order is unchanged. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0077-trusted-authorization-evidence.md b/docs/decisions/0077-trusted-authorization-evidence.md index 2470ed363..c6ebf218b 100644 --- a/docs/decisions/0077-trusted-authorization-evidence.md +++ b/docs/decisions/0077-trusted-authorization-evidence.md @@ -379,3 +379,14 @@ provenance or generalized evidence dictionary. The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns implementation and qualification; acceptance alone installs no runtime subject. + +### Amendment 2 — Operator admission denials (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) § 11 places denials of Platform +operator admission outside this record's typed denial event population. They are +tenantless, and this record's rule that a tenantless refusal invents no tenant and uses +no platform sentinel stands. Their evidence is a counter and a Warning log. The +reopening trigger is Phase 11 security monitoring that requires durable denial evidence. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0099-confined-tenant-federation.md b/docs/decisions/0099-confined-tenant-federation.md index 50f8c68e4..a76338a88 100644 --- a/docs/decisions/0099-confined-tenant-federation.md +++ b/docs/decisions/0099-confined-tenant-federation.md @@ -1077,3 +1077,230 @@ Decision is unchanged. The [Phase 03 delivery log](../roadmap/phase-03-delivery-log.md#p03-8-pr-review-disposition-2026-11-18) holds the review record, each finding's disposition and its proof. + +### Amendment 10 — Federation operator steps (2026-11-19) + +Accepted [ADR-0101](0101-platform-operator-authority.md) admits the operator steps this +record assigns to P03-9. The operator acts through a separate port, +`IFederationOperator`, held only by the operator service and never by the tenant runner, +so the rule that the provider port is held only by the runner stands. It uses the same +`learnstack-federation-admin` client and adds no realm authority. The admitted routes +grow from four to five by one paged listing of identity-provider instances. + +1. **Classes.** An alias that starts with `lsf-` and whose owner marker parses to a + tenant and connection is classified. An *orphan* has no live row: the row is absent + or a `Deleted` tombstone, so the text "its connection row was removed" is read that + way. An *unreadable owned* broker carries the marker but reads as foreign. A + *nonconforming* broker is readable and owned but has an extra mapper or a changed + profile (Amendment 9 item 5). An unmarked or marker-mismatched broker is never + touched. +2. **Report.** `platform.federation.read` reads the realm list first, then the rows, and + writes nothing. Reading the rows first would manufacture false orphans. +3. **Remove.** `platform.federation.admin` deletes an orphan or an unreadable owned + broker by its alias after re-reading its row immediately before the delete, and + refuses if a live row exists. Deleting an absent broker is applied. The provider's + deletion also removes the federated links, and the runbook says so. +4. **Disable.** The same permission sets `enabled=false` on a nonconforming broker, or + on one the tenant cannot reach, at the provider only and marker-proven. The row is + left to the tenant's next readback, which corrects it; until then the sign-in option + fails closed. +5. **Rows read.** `learnstack_platform` receives `SELECT` of `id`, `tenant_id`, `state` + and `deleted_at` on `federation_connections`, pinned by a column-privilege test. +6. **Audit.** Each remove or disable writes a MUST intent row before the provider call + and a completion row after it, as Amendment 2 does for the tenant path, under the + real tenant, with a closed reason slug, `metadata.operator` and a follow-up note that + an account review is owed. A lost completion is found by the next report. + + > **Erratum (2026-11-20, Amendment 11 item 3).** Amendment 2 is the Keycloak pin and + > has no intent-first pattern; the pattern the tenant path follows is the Decision's + > § Intent-first operations. The platform scope could not write the intent row before + > a provider call, so the seam it needed is + > [ADR-0044 Amendment 18](0044-audit-write-path.md). +7. **Account review.** It is a runbook step. No LearnStack credential may enumerate or + remove realm users (Decision Q1), Keycloak keeps link events for seven days and no + owner notification channel exists before Phase 08a. +8. **Residual.** No provider-side fence exists, so a tenant create that lands after a + sweep produces a new orphan, which the next report finds. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +### Amendment 11 — Federation operator steps: implementation contract (2026-11-20) + +Step 5 of the platform-authority packet implements Amendment 10. Each item below fixes +something the record left open or states where the code corrected it. The maintainer +approved items 3 and 6 before they were written. None of them changes Amendment 10's +choice of option, its two permissions, its classes or its refusal to enumerate or remove +realm users. + +1. **Where the code lives.** `IFederationOperator` sits beside the tenant provider port + and is held by the operator's owner, `FederationBrokerOperations` (Identity + Infrastructure), and by the adapter that implements it, the operator half of the + same Keycloak class. A second instance of that class is built with its own + resilience pipeline of the fixed shape, so a sweep cannot starve a tenant's calls. + The routes are `GET /api/platform/v1/federation/brokers`, + `POST .../{alias}/remove` and `POST .../{alias}/disable`, behind the keys + [ADR-0101](0101-platform-operator-authority.md) § 5 fixed, + `platform.federation.read` and `platform.federation.admin`, and each runs the gate + first. +2. **The grant is an Identity-chain migration.** `federation_connections` is created in + the Identity chain, which runs after the Platform chain, so the column grant of item + 5 is a hand-written forward-only Identity migration. The raw-reader census of + Standard 21 admits the operator's one statement beside the three tenant readers, + pinned whole: it reads by primary key through the four granted columns and sees + tombstones, which the shared live predicate would hide. +3. **Two rows around the provider call.** The tenant path's pattern is the Decision's + § Intent-first operations, not Amendment 2. The platform scope could write one + result row and no row before a provider call, so the seam is the scope handle's + checkpoint and a fifteenth `IAuditStore` write + ([ADR-0044 Amendment 18](0044-audit-write-path.md)): one admission, an intent row + with the outcome `indeterminate` on `platform.federation.remove_attempt` or + `platform.federation.disable_attempt`, committed before the provider call, and a + completion row on `platform.federation.remove` or `platform.federation.disable` with + the outcome and whether an account review is owed. The rows name the tenant the owner + marker names, never the platform sentinel, even when no `tenants` row exists, and + carry closed tokens only: no display name, issuer, configuration or secret, and no + ticket. An absent broker on a remove, a disabled broker on a disable, a refusal for a + live row, an unowned alias and a provider that is unavailable before any change + write no tenant row: the scope's entry row records the call, and nothing is known to + name a tenant. A provider that fails after a change was sent is recorded `uncertain` + in the completion row and answered `503` with the reason `outcome_unknown`. +4. **The report.** One call is one page of the provider's listing, from an opaque offset + cursor bound to the operation, 1 to 100 instances, in full representation. The realm + is read first and the rows second, because a tenant writes its row before it creates + the broker; the scope is entered before both, so the admission is spent fresh. A + broker is reported when its row is absent or a tombstone (`orphan`), when its + marker proves it LearnStack's and its representation does not read as an admitted + shape (`unreadable_owned`), or when it reads and differs from the fixed profile or + carries a mapper (`nonconforming`); a mapper is drift only a mapper read shows, so + the mappers of what looks healthy are counted one after another within the page's + ten seconds and an unread count is reported unknown, never zero. An instance with no + marker, a marker that does not parse strictly to a tenant and a connection whose + derived alias it is, or a marker that disagrees with its row about the tenant, is + counted and never named. +5. **The live-row refusal is literal.** A remove refuses while a live row names the + broker, for an unreadable owned broker as well. Such a broker is disabled by the + operator and removed by the tenant's own Delete, which this step leaves as the + residual Amendment 10 item 3 implies. + + > **Erratum (2026-11-20, Amendment 12 item 1).** The tenant's own Delete does not + > remove an unreadable owned broker: the tenant adapter reports it foreign + > (Amendment 9 item 5), the runner fails the Delete with an owner mismatch, and the + > row stays live. An unreadable owned broker with a live row therefore had no + > removal path at all. + > + > **Correction (2026-11-20, Amendment 13 item 3).** The rule that the tenant adapter + > reports a broker foreign when its marker matches and it no longer reads is + > Amendment 5 item 5. Amendment 9 item 5 is the readable nonconforming broker. +6. **Disable sends back what the provider returned.** An unreadable owned broker cannot + be rebuilt from the fixed profile, so the operator disable is the one provider write + that does not build its body from the allow-list: it reads the instance, proves the + marker, drops the two members the provider computes on every read, sets `enabled` to + false and writes the rest back, with the secret as the provider's own mask, which the + provider reads as "keep the stored value" (Amendment 3). It is confirmed by reading + the instance again. This is a bounded exception to the fixed broker profile, limited + to the operator port, and Amendment 9 item 5's "repair" is read as this disable. + "One the tenant cannot reach" means an unreadable or nonconforming owned broker; a + tenant that is archived or deleted with a live row is P03-10's. +7. **Verified against the pinned provider.** The federation admin client's one role, + `manage-identity-providers`, lists instances, the listing carries each member and the + owner marker with the secret masked, `first` and `max` page it, a write of the + returned representation with `enabled` false is accepted, and deleting a broker + deletes its federated links and leaves the account. So the admitted routes grow by + the one paged listing of Amendment 10, and "adds no realm authority" holds. The + route census admits the listing's collection route with its one exact query. +8. **Residual.** There is still no provider-side fence, so a tenant create that lands + after a sweep produces a new orphan, which the next report finds, and the disable is + a read and a write the tenant's own write can interleave with; the tenant's next + readback detects the drift. The account review stays a runbook step. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + +### Amendment 12 — Federation operator steps: review round 1 corrections (2026-11-20) + +The first review round of Step 5 found one dead end and five places where the record +or the code said less than the behaviour. The maintainer chose item 1; items 2 to 6 +state, without changing Amendment 10's choice of option, what the implementation does. + +1. **An unreadable owned broker is removed even with a live row.** Amendment 10 item 3 + and Amendment 11 item 5 refuse a remove while a live row names the broker, for both + classes. The refusal applies to a broker that reads, whose tenant Delete works and + retires the pair. An unreadable owned broker is removed by the operator on its + marker proof, with a live row or without one: the tenant's Delete cannot reach it + (Amendment 9 item 5), it already fails closed, and the tenant's next readback finds + it absent, after which the tenant's own Delete tombstones the row. The operator + never writes the tenant's row. The rows record the live state found, and the account + review is owed as for any remove. Amendment 10 item 3 and Amendment 11 item 5 are + read accordingly, and a readable nonconforming broker is still disabled, not removed. + + > **Erratum (2026-11-20, Amendment 13 item 1).** "It already fails closed" is not + > supported: an unreadable broker can still be enabled and serving, so the removal + > needs it disabled first. The pointer "Amendment 9 item 5" is Amendment 5 item 5 + > (Amendment 13 item 3). +2. **An unread mapper count is a page counter.** Amendment 11 item 4 reports an unread + count "unknown, never zero". A broker whose only possible class is an extra mapper + has no other class to carry the unknown, so the page carries it: `mappersUnread` + counts the healthy-looking live brokers whose mappers were not read (the provider + failed, its circuit was open or the page's ten seconds ran out). No item names them. +3. **The completion has its own budget.** After the intent row, the completion row is + written and committed on a bounded token of three seconds, detached from the + request, as the tenant runner completes on a detached token. A caller that leaves + while the provider works is recorded `uncertain`. A completion that cannot be + written after a change that landed or may have answers the unknown outcome (`503` + `dependency_unavailable` with the reason `outcome_unknown`) and leaves the intent + row standing; the account review is then owed if the broker is gone. When nothing + changed, a failed completion is the audit failure and is safe to repeat. A transient + database fault is a `503` with its cause in the log, and any failure to commit the + intent row stops the act. +4. **The ticket is recorded on the entry row.** Amendment 11 item 3 says the rows carry + no ticket. That holds for the intent and completion rows, which the tenant can read. + The platform scope's entry row, a row of the platform sentinel, carries the checked + ticket, as it does for every scope act. +5. **The completion row's audit outcome is `success`.** The scope's result row records + that the act ran to its end and is written only with that outcome. How the provider + call ended is the closed `outcome` of `after_state`, and an alert keys on it. +6. **An applied disable also owes the review.** Amendment 10 item 6 asks for the + follow-up note on both acts: `accountReviewOwed` is true for an applied remove, which + deleted the federated links, and for an applied disable, which closed the broker as + a sign-in option. An absent or already disabled broker owes none. + +The Decision, Status, Date and prior amendments of this record are unchanged, except +for the inline erratum beside Amendment 11 item 5 that item 1 records. Acceptance of +the linked records is not proof that anything they decide is implemented. + +### Amendment 13 — Federation operator steps: review round 2 corrections (2026-11-20) + +The second review round of Step 5 found that Amendment 12 item 1 rests on a premise the +code does not support, and three places where the behaviour or the record said less +than it should. The maintainer chose the removal in Amendment 12 item 1; item 1 below +narrows how it is done and is reported to the maintainer. + +1. **An unreadable owned broker is removed with a live row only after it is disabled.** + Amendment 12 item 1 said such a broker "already fails closed". It does not: + "unreadable" is the shape check of one read, a broker edited in the provider's + console can be unreadable and still serve sign-ins, and the tenant's brokered + publication does not depend on a provider read. A remove of a broker a live row + still names therefore needs it to read as unreadable **and** to be disabled. An + unreadable broker that is still enabled is refused (`errors.connection`): the + operator disables it, which is reversible, and removes it after. The adapter proves + both conditions again when the delete is about to be sent and sends nothing + otherwise (`refused`), so an inspection seconds old is not trusted. Amendment 12 + item 1 is read accordingly, and the tenant's row is still never written. +2. **A failure after a change is the unknown outcome, with its cause.** Any non-fatal + failure after a provider change landed or may have (the provider call itself, the + completion row, its commit, the handle's disposal) answers `503` + `dependency_unavailable` with the reason `outcome_unknown`, and the failure goes to + the route's log (event 7110) and never into a response. An unexpected provider + failure or a cancellation is recorded `uncertain` and still completed. Before any + change, a transient database fault is the plain `503` and anything else is the + defect it is. Amendment 12 item 3 is read accordingly. +3. **Pointers.** The rule that the tenant adapter reports a broker foreign when its + marker matches and it no longer reads is Amendment 5 item 5, and Amendment 9 item 5 + is the readable nonconforming broker. The erratum beside Amendment 11 item 5 and + Amendment 12 item 1 carry inline corrections. + +The Decision, Status, Date and prior amendments of this record are unchanged, except for +the inline errata beside Amendment 10 item 6 (recorded by Amendment 11), Amendment 11 +item 5 and Amendment 12 item 1 (recorded by Amendments 12 and 13). Acceptance of the +linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0100-p038-federation-contract-transition.md b/docs/decisions/0100-p038-federation-contract-transition.md index 38fb7e5f0..ae7f07200 100644 --- a/docs/decisions/0100-p038-federation-contract-transition.md +++ b/docs/decisions/0100-p038-federation-contract-transition.md @@ -370,6 +370,20 @@ or a failed comparison never creates success. `PublicSurface_Contract_Matches_Served_OpenApi` and the actual response and authority parsers are preserved. +## Amendments + +### Amendment 1 — A Platform key does not recur the refusal (2026-11-19) + +The Decision Drivers expect the permission keys of later modules, Platform among them, +to recur the refusal. Accepted [ADR-0101](0101-platform-operator-authority.md) registers +Platform definitions as non-assignable in a separate catalogue. They never enter the +administration grant union, so they change neither the tenant document nor this +mechanism, and they do not trigger gate G20. G20 stays Open for the first assignable +key. + +The Decision, Status, Date and prior amendments of this record are unchanged. Acceptance +of the linked records is not proof that anything they decide is implemented. + ## References - [ADR-0024](0024-api-versioning-policy.md), [ADR-0040](0040-ambient-unit-of-work.md) diff --git a/docs/decisions/0101-platform-operator-authority.md b/docs/decisions/0101-platform-operator-authority.md new file mode 100644 index 000000000..3650049d4 --- /dev/null +++ b/docs/decisions/0101-platform-operator-authority.md @@ -0,0 +1,315 @@ +# ADR-0101: Platform Operator Authority + +## Status + +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes gate G13 for human operator authority together with +[ADR-0102](0102-production-tenant-onboarding.md) and +[ADR-0104](0104-controlled-issuer-rebind.md), and authorizes the code it describes. It +is not proof that anything is implemented. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- `DenyAllPlatformAdminGate` refuses everyone, so no cross-tenant act, killswitch toggle + or privileged recovery exists. The gate's only input is a `reason` string, both the + gate and the scope are singletons, the entry row writes a null actor and a null + correlation id, and `EnterAsync` has no production caller. A real gate needs a + principal, an operation and a permission. +- [ADR-0004 Amendment 1](0004-authentication-strategy.md) places operators in the + separate `learnstack-hub` realm and says tenant routes refuse them. + [ADR-0064](0064-tenant-api-authentication-boundary.md) registers exactly one bearer + scheme for the tenant API and refuses every other issuer and `scope=platform`. No code + authenticates an operator, the realm export carries one public client with no audience + mapper and no assurance mapper, and `/api/internal/*` has no endpoint. +- [ADR-0036](0036-tenant-resolution-trusted-inputs.md) routes operator cross-tenant work + through `/api/internal/*` under the Hub chain. + [ADR-0034](0034-hub-contract-surface-invariant.md) and ADR-0004 define that chain as + machine-to-machine under a Hub service identity. It carries no human operator, so it + cannot supply C14's human attribution, and changing it is a coordinated decision in + two repositories. +- Every phase from 02d to 11 must work without a Hub + ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), including a Self-Hosted + deployment whose operator is the customer. +- C14 requires a real operator with a specific Platform permission, tenant and + wrong-purpose credentials refused before a bypass connection exists, surviving human + attribution, reason and correlation, and a retained connection that cannot run + autocommit after the scope completes. +- [Standard 19](../standards/19-permissions.md) refuses Keycloak roles as authority and + makes Platform definitions never assignable to tenant roles. The pinned OpenAPI gate + ([ADR-0100](0100-p038-federation-contract-transition.md)) refuses every new assignable + key, so the design must not touch the tenant grant union. + +## Considered Options + +1. **A separate strict operator scheme on a LearnStack-owned prefix, grants held by + LearnStack** (chosen). The pinned issuer and audience gate admission; a closed + Platform catalogue and a grant source decide authority per act. +2. **Hub-mediated operator identity on the `/api/internal` chain** (rejected). It needs + a new claim or endpoint, so a coordinated ADR-0034 change in two repositories. It + loses the no-Hub baseline and carries a service identity where C14 needs a human. +3. **Accept the `learnstack-hub` issuer on the tenant scheme** (rejected). + [ADR-0064](0064-tenant-api-authentication-boundary.md) refuses it, and a shared + scheme invites a tenant token into an operator route. +4. **Authority from Keycloak realm or client roles** (rejected). + [Standard 19](../standards/19-permissions.md) forbids it, and a role has no per-act + freshness or audit. +5. **A deployment tool with deployment credentials only** (rejected as the general + mechanism). It gives no verified human attribution. The offline rebind of + [ADR-0104](0104-controlled-issuer-rebind.md) is a tool, but it authenticates the + human through this ADR's scheme. + +## Decision + +LearnStack admits one human operator population, authenticated at a pinned operator +issuer, and gates every privileged act on a per-act, LearnStack-held Platform +permission. + +1. **Population.** Operators are LearnStack or deployment staff. The issuer is + `PlatformOperator:Issuer`, by default the `learnstack-hub` realm, and is always an + issuer the deployment controls, never a tenant-configured or brokered provider. No + service or machine operator is admitted: the Hub service-account chain carries no + operator, and background or external job frames are refused privileged entry + ([ADR-0047](0047-transactional-background-job-runtime.md)). An operator is never a + `users` row or a tenant member, and a tenant token never admits. +2. **Authentication.** A second bearer scheme, `PlatformOperator`, validates signature, + exact issuer, audience `learnstack-platform`, an allow-listed public PKCE `azp`, + `typ` and a finite `exp`, and refuses a token whose `exp - iat` exceeds 15 minutes. + It requires no `scope` claim: audience, client and assurance carry the purpose. The + scheme is bound to the operator prefix and the tenant scheme remains the only scheme + on `/api/v1`. The tenant scheme refuses the operator issuer and the operator scheme + refuses the tenant realm. Roles and any other claim carry no authority. +3. **Assurance.** An act requires the `acr` claim to be in + `PlatformOperator:AcceptedAcr` and `auth_time` to be no older than + `PlatformOperator:MaxAuthenticationAge` (default 15 minutes). This names the claim + and source that [Architecture 13](../architecture/13-identity-and-auth.md) requires, + and [ADR-0099](0099-confined-tenant-federation.md)'s rule that assurance comes only + from LearnStack-controlled authentication holds because the issuer is + deployment-controlled. An absent or unlisted value refuses. A Self-Hosted issuer must + emit `acr` and `auth_time` as the runbook specifies, or no operator can act. +4. **Surface.** Operator routes live under `/api/platform/v1/*`. The prefix is added to + `VersionedRouteConvention.UnversionedRoutePrefixes` and to the host-classification + prefixes beside `/api/internal`, joins its own route census and + `OperationHttpClassifier` entries, and is served as its own OpenAPI document, outside + the pinned tenant document and the tenant SDK. The controllers are present only when + the issuer is configured, and a test proves absence otherwise. The gateway scaffold + routes no `/api/platform` path; exposing it is a Phase 11 decision. A target tenant + is data of the act and populates `ITenantContext` only through the confined + announcement of [ADR-0102](0102-production-tenant-onboarding.md) § 1; no ordinary + route resolves a tenant from a request value + ([ADR-0036](0036-tenant-resolution-trusted-inputs.md)). +5. **Platform permissions.** Platform permission definitions live in a separate + catalogue. They are never `Assignable`, never enter the tenant grant union, and the + served tenant document stays byte-identical. Trusted operator policies may exist + beside it. The closed key set this ADR family registers is: + + | Key | Acts | Owner | + |---|---|---| + | `platform.killswitch.write` | Toggle a declared killswitch | this ADR | + | `platform.tenant.write` | Provision a Tenant and map its hosts | ADR-0102 | + | `platform.tenant_bootstrap.write` | Role templates, first admin, admin recovery | ADR-0102 | + | `platform.identity_authority.admin` | Controlled issuer rebind | ADR-0104 | + | `platform.delivery.read` | Inspect dead letters and quarantined jobs | ADR-0103 | + | `platform.delivery.write` | Targeted replay and narrow producer reset | ADR-0103 | + | `platform.federation.read` | Report orphan, unreadable and nonconforming brokers | ADR-0099 A10 | + | `platform.federation.admin` | Operator disable and orphan removal | ADR-0099 A10 | + + The `platform.*` examples in Standard 19 that no ADR registers stay unregistered, and + Standard 19 cites the catalogue instead. It owns the final spelling when Step 1 + lands. +6. **Grants.** `IPlatformOperatorGrantSource` maps an operator subject digest to + Platform keys. The shipped adapter binds `PlatformOperator:Grants` through + `IOptionsMonitor`, validates every entry against the catalogue at start, takes effect + on the next act when the configuration provider reloads (a provider that cannot + reload needs a restart, and the runbook says so), and is evaluated on every act, + never from claims. The adapter refuses a grant for the exported demo operator unless + `Deployment:Mode` is Development, and refuses to start on any grant that fails + validation. A database adapter is demand-gated + ([ADR-0035](0035-demand-gated-infrastructure.md)): the trigger is a need for audited + runtime grant changes, the owning phase is + [Phase 11](../roadmap/phase-11-production-hardening.md), and managing it through an + operator route needs its own decision. +7. **Admission.** `IPlatformOperatorGate.AdmitAsync(witness, operation, ticket)` + replaces `IPlatformAdminGate.IsPermittedAsync(reason)`. The witness is minted by one + minter class from a validated operator principal, and the closed minter census allows + two callers: the operator scheme handler and the offline tool of + [ADR-0104](0104-controlled-issuer-rebind.md), which validates the same token through + the same validator. An operation is a closed registry entry: permission, audit slug, + reason slug, and whether it needs the platform role. The reason is that slug. The + optional ticket is 1 to 64 characters of `[A-Za-z0-9._:/#-]`. A malformed ticket + answers 400 `validation_failed`. A missing permission or an unknown operation answers + 403. Admission runs before any privileged credential or connection is resolved. +8. **Scope.** `EnterAsync` takes a `PlatformAdmission` and keeps the compiler-supplied + caller attributes. Admission is required by every operator act; the platform role is + entered only by an act that needs it. The handle exposes no provider connection. + Work runs through a bounded facade, completion and abandonment close the underlying + connection, and a reference captured before completion cannot execute, begin a + transaction or reopen. A mutant test captures such a reference. Entry still refuses + job and external frames. +9. **Attribution.** An operator act writes `actor_user_id` NULL on its audit rows, the + closed reason slug, the correlation id and `metadata.operator` with fixed members: + `issuer`, `subjectDigest`, `kind` (`human`), `acr` and `executor`. The digest is the + unpadded base64url SHA-256 of `learnstack.operator.subject.v1`, a line feed, the + issuer, a line feed and `sub`; it is distinct from the identity subject key. The + optional ticket appears only in sentinel-tenant rows, which no tenant can read. Rows + a tenant can read carry the correlation id and never the ticket, and the response + returns the correlation id for the operator's own record. Business columns an + operator act writes use `UserId.SystemActor` for `created_by`, and + `platform_killswitches.toggled_by` stays NULL. +10. **Result audit.** A MUST result row commits in the transaction that changes the + state. A platform-role act writes it through a new witness-bound method on the + scope's work transaction; `WritePlatformScopeAsync` keeps its single entry-row + caller. An outbox-role act uses the fenced witnesses of + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md). An app-role act uses the + ordinary pipeline extended by [ADR-0102](0102-production-tenant-onboarding.md). The + rebind uses an intent row and a result row from its own role + ([ADR-0104](0104-controlled-issuer-rebind.md)). The sentinel tenant may appear only + on the platform-scope class of [ADR-0044](0044-audit-write-path.md) § 1, which this + family extends to the entry row and a platform-wide result row; a tenant-targeted + result row carries the real tenant. A forced audit failure rolls the act back and + answers 503. +11. **Denied evidence.** A pre-authentication refusal answers 401 with a counter and a + structured log and writes no row. An authenticated operator who lacks the permission + or names an unknown operation answers 403 before any connection opens, with a + counter and a Warning log carrying the operation slug and subject digest. No durable + denial row is written, because one needs a bypass connection for a refused caller or + a third sentinel arm. Operator denials are outside the tenant denial population of + [ADR-0077](0077-trusted-authorization-evidence.md) and the denied-outcome rule of + [Standard 18](../standards/18-audit-coverage.md), which receive dated disclosures + saying so. Reopening needs Phase 11 security monitoring that requires durable + denial evidence. +12. **No-Hub baseline.** The surface depends on the configured issuer and the grant + source only. Development has no permissive gate: its configuration grants the real + pinned `learnstack-hub` demo operator and the proof runs against real Keycloak. + Forwarding an operator identity from the Hub needs its own coordinated ADR. +13. **First consumer: the killswitch writer.** + [ADR-0045 Amendment 1 § 4](0045-entitlement-and-feature-flag-socket.md) withheld it + until a Platform gate existed. It is a service, not a MediatR request, and keeps the + matrix row `tenancy.killswitch.toggle` off-path with its `(planned)` marker removed + in the commit that registers it. It resolves a key only from `KillswitchKeys.All`, + reads the before state, upserts the row with the time and the ticket in the bounded + `reason` column, writes the MUST result row on the work transaction, and removes the + overlay cache entry after commit, including an indeterminate commit. Writes to + `platform_killswitches` are confined to it by an architecture rule; the overlay's + reads are unaffected. The runbook states the 60-second cross-instance lag, the + fail-open read, and that no production code reads a killswitch yet. + + > **Erratum (2026-11-19, Amendment 1 below).** The text above puts the ticket in + > the `reason` column. That table is readable by the application role, which § 9 + > forbids for a ticket, so the two sections disagreed when this record was accepted. + > § 9 governs: the writer leaves `reason` NULL and the ticket is on the sentinel + > audit rows only. +14. **Signals.** Counters record admissions by outcome and operation, refusals by cause, + and result rows by operation, so a monitoring owner can alert without a log search. + +## Context + +The gate was shaped as a refusal on purpose: a permissive Development gate would repeat +the inversion where the demo passes and production refuses. P03-9 now owns the +population that makes the refusal answerable. The corpus fixes three points: operators +live in their own realm, tenant schemes refuse them, and Keycloak roles are not +authority. Its one unfinished edge is the route: ADR-0036 reaches operators only through +a machine chain that has no human. This ADR gives the human a LearnStack-owned prefix +and scheme, and leaves the Hub chain as it is. + +A scheme per audience keeps each acceptor class closed, which is why a second scheme is +confined to its prefix instead of widening the tenant one. A grant source evaluated per +act gives revocation without a token wait, which a claim cannot. Configuration is enough +for a few staff and keeps the first packet free of a second platform table and its +writer; the port and the trigger make the table a plain addition. The result-audit +method is the real cost: the entry row commits before the work and records entry only, +so a result row needs the work transaction, which no platform write method takes today. + +What would reopen this: a Hub operator portal that needs delegated operator identity (an +ADR-0034 amendment in both repositories), durable denial evidence from Phase 11 +monitoring, or a service operator for scheduled platform work. + +## Consequences + +### Positive + +- C14's positive and negative controls become provable against real Keycloak, and + Self-Hosted works with no Hub. +- Tenant tokens cannot reach an operator route and operator tokens cannot reach a tenant + route, by two closed schemes and a disjoint prefix. +- The tenant contract does not change, so the OpenAPI gate and G20 are not triggered. +- Attribution survives in every row: who, why, through which assurance, under which + correlation, without leaking an operator's ticket to a tenant. + +### Negative + +- Two schemes and one new realm client and audience mapper in this repository's realm + export, plus an `acr` and `auth_time` profile every Self-Hosted issuer must meet. +- Configuration grants give no audited runtime grant change until the table adapter. +- No durable denial row: a refused operator leaves a counter and a log only. +- Operators have no browser screen here. The Hub operator portal, not started, is the + intended client of the served document. + +### Neutral + +- The scope's handle contract changes. Its only callers are tests today. +- `docs/runbooks/` begins here with operator access and the killswitch, earlier than the + Phase 11 deliverable that names it. + +## Implementation Notes + +- Step 1 delivers the scheme, witness minter, catalogue, grant source, gate, scope + redesign, result method, route mechanics, problem mapping, killswitch writer and + runbooks. Realm changes: one public PKCE client `learnstack-operator` with an audience + mapper for `learnstack-platform`, a client token lifetime of at most 15 minutes, and + an ACR-to-level mapping with step-up. The proof reads a real token and shows the + pinned realm emits `acr` and `auth_time`. +- The mutation targets are the gate call, its position before connection acquisition, + the admission refusal inside job frames, the closure fence, a null actor, a missing + result row and the cache removal after commit. +- Architecture rules: `PlatformAdminScope_Entry_Requires_Platform_Permission` conjunct B + is rewritten against the real gate, not deleted, and gains its marker clause; the + minter census is closed; a Platform definition is non-assignable and the tenant + document bytes are unchanged; the operator prefix census is exact. + +## Carriers + +Each is a dated disclosure, never a body edit. ADR-0004 (scheme and audience), ADR-0036 +(the platform URL space and the confined target announcement), ADR-0040 (the +announcement setter), ADR-0044 (the result method, the extended sentinel class and the +operator metadata), ADR-0045 (the writer's shape and the corrected actor claim), +ADR-0046 and ADR-0047 (through +[ADR-0103](0103-operator-recovery-of-asynchronous-work.md)), ADR-0064 (a second scheme +confined to its prefix), ADR-0077 (operator denials), ADR-0099 (Amendment 10) and +ADR-0100 (a Platform key does not recur the refusal). Standards 04, 11, 12, 13, 18, 19, +20 and 21, Architecture 13, 28 and 30, the glossary, the Tenancy and Identity module +specifications, and the Phase 03 and Phase 11 documents follow. + +## Amendments + +### Amendment 1 — The ticket stays out of a table the application role reads (2026-11-19) + +Step 1 review found that § 13 stored the optional ticket in +`platform_killswitches.reason` while § 9 promises that a row a tenant can read never +carries it. The application role holds `SELECT` on that table under `USING (true)`, so +the overlay can read it; a ticket there would be reachable by any future module query, +including one an injection steered. The writer sets `reason` to NULL on every flip and +the ticket is recorded on the sentinel-tenant audit rows, where § 9 puts it. The column +stays for a future non-ticket explanation; nothing writes it. The Decision, Status, Date +and every other section are unchanged. + +## References + +- [ADR-0102](0102-production-tenant-onboarding.md), + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md), + [ADR-0104](0104-controlled-issuer-rebind.md) +- [ADR-0004](0004-authentication-strategy.md), + [ADR-0034](0034-hub-contract-surface-invariant.md), + [ADR-0036](0036-tenant-resolution-trusted-inputs.md), + [ADR-0044](0044-audit-write-path.md), + [ADR-0045](0045-entitlement-and-feature-flag-socket.md), + [ADR-0064](0064-tenant-api-authentication-boundary.md), + [ADR-0077](0077-trusted-authorization-evidence.md) +- [Permission Standards](../standards/19-permissions.md), + [Security Standards](../standards/11-security.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/0102-production-tenant-onboarding.md b/docs/decisions/0102-production-tenant-onboarding.md new file mode 100644 index 000000000..06e134d7c --- /dev/null +++ b/docs/decisions/0102-production-tenant-onboarding.md @@ -0,0 +1,382 @@ +# ADR-0102: Production Tenant Onboarding + +## Status + +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes the production provisioning, first-administrator and recovery parts of +gate G13 together with [ADR-0101](0101-platform-operator-authority.md) and +[ADR-0104](0104-controlled-issuer-rebind.md), and authorizes the code it describes. It +is not proof that anything is implemented. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0072](0072-application-owned-identity-bootstrap.md) and + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) leave production + first-admin setup to P03-9. The fixed seed capability grants no operator authority. +- The tenant, host-mapping, Role-template and first-admin commands are `Seed`-only by + construction. Their handlers pass a seed guard that demands a single allowed source + `Seed`, an exact trusted `Seed` source and the fixed demo declaration, and the API + registers deny-all continuation and foundation admissions. Adding a source to their + policies would still be refused in the handler, so production onboarding needs its own + commands. +- The invariants that make an administrator safe, last-admin protection, the User fence + and ordered membership locks + ([ADR-0074](0074-membership-admission-under-ordered-locks.md)), live in app-role + domain code. A raw write on the platform connection skips them and the audit capture + of [ADR-0044](0044-audit-write-path.md) § 7. +- A tenant that resolves to no host is not onboarded, and the Hub endpoint that pushes + host mappings does not exist ([Phase 02c](../roadmap/phase-02c-hub-foundation.md)), so + the no-Hub baseline needs an operator-admitted mapping. +- The first-admin command refuses any tenant with Membership history, so recovery of a + tenant whose administrators are gone is a different predicate, not a repeat. +- C14 asks for positive and denied proof, partial-commit proof, unknown-COMMIT + reconciliation, and says seed authority is insufficient. + +## Considered Options + +1. **Operator-admitted commands of their own, on the app role, through the ordinary + pipeline** (chosen). They reuse the domain aggregates and extracted shared cores, and + keep the `Seed` commands untouched. +2. **Add the operator source to the existing `Seed` commands** (rejected). The seed + guard requires a single `Seed` source and the fixed declaration, so the handler + refuses it, and widening the guard weakens the seed's only-this-source property. +3. **Run onboarding as raw SQL on the platform connection** (rejected). It skips the + last-admin and User invariants and the audit capture, and widens a `BYPASSRLS` role. +4. **A platform-issued invitation for the first administrator** (rejected here). It + reuses [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) but needs an + exception for an inviter who holds no Membership and depends on automatic email + delivery, so recovery would depend on mail. + +## Decision + +> **Erratum — 2026-11-19.** Item 1 below says the target tenant is announced by "one +> new logical tenant setter", "the eleventh", and that "the four context writers do not +> change". No new setter exists, and the claim was unachievable when it was written: +> the query filters and the transaction behavior read the context accessor, so an act +> that is not installed in it is invisible to row security. The operator act executor +> installs an immutable resolved ambient context for the admitted target, the ordinary +> transaction behavior announces it, the setter census does not move, and the executor +> is a fifth writer of the accessor; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four` (`TenantContextConstructionTests`) and +> `PlatformOperatorActExecutorTests`. The Decision is unchanged: an admitted operator +> act runs on the application role under the admitted target tenant's announcement and +> the platform role is not used. Current authority: +> [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in Amendment 1. + +1. **A confined operator source and announcement.** `AuthorizationSourceKind` gains + `PlatformOperator`, minted only from an + [ADR-0101](0101-platform-operator-authority.md) admission for one of the operations + below. The five commands carry `FiniteTrusted` policies whose only source is + `PlatformOperator`, and the `Seed` policies and guards are unchanged, so neither + authority can perform the other's acts. The target tenant is announced to the unit of + work by one new logical tenant setter, confined to that source: it reads the admitted + operation's declared target, never an ambient or header value, announces once per + unit of work and refuses any other caller. It is the eleventh logical tenant setter; + [ADR-0040](0040-ambient-unit-of-work.md) and + [ADR-0036](0036-tenant-resolution-trusted-inputs.md) receive dated disclosures, and + the four context writers do not change. The platform role is not used. + +2. **The commands.** `OperatorProvisionTenant` creates a Tenant and its default + Organization. `OperatorMapHost` maps a host through the existing host-mapping store + and its reserved-host and platform-host rules. `OperatorInitializeRole` creates one + finite Role template. `OperatorCreateFirstAdmin` creates the first tenant-wide + administrator Membership. `OperatorRecoverAdmin` creates a replacement administrator. + `platform.tenant.write` covers the first two; `platform.tenant_bootstrap.write` + covers the other three. Shared cores are extracted from the seed handlers so the + domain logic exists once; the seed and operator handlers differ only in their guard. +3. **Identity of the acts.** The operator supplies a UUIDv7 `tenantId` and a slug, and + an act is idempotent on that pair: the same pair finds the existing tenant, and a + known slug under another id refuses. A lost response therefore loses nothing. The + business actor of every written row is `UserId.SystemActor`; the operator is recorded + in audit only, as [ADR-0101](0101-platform-operator-authority.md) § 9 fixes. Operator + policies do not use the membership-candidate path, which refuses `SystemActor`. +4. **Host mapping.** The operator asserts ownership of the host. LearnStack verifies no + DNS, and the seed does not either. The Hub's custom-domain approval for SaaS stays + the Hub's and is unreachable here. The runbook states that a Self-Hosted operator is + responsible for DNS and TLS. +5. **Naming the person.** The operator names the first administrator by provider subject + at the identity authority's issuer. The person must already have completed + global-self bootstrap at the tenant's mapped host, so a `users` binding exists. A + confined single-act resolver computes the canonical subject key under the stored + `AuthorityId`, the request supplying neither, and returns the `UserId` of an Active + user only. An unknown or non-Active subject refuses with a 409 `bootstrap_required` + problem. The operator creates no `User`, and an email address is never an identifier. +6. **Order.** Provision, map the host, the person signs in once at that host, each Role + template, then the first administrator. Each step commits in its own transaction, as + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) requires, and the + Role roots keep their pristine-prefix predicates. A retry resumes from the first + absent step by reading state, never by repeating a write blind. An unknown COMMIT is + reconciled by that read. Naming a tenant that does not exist, or a person who is not + bootstrapped, refuses before any write. +7. **First administrator.** `OperatorCreateFirstAdmin` refuses unless the tenant has no + Membership history, the seed command's predicate, evaluated under the ordered locks + of [ADR-0074](0074-membership-admission-under-ordered-locks.md) inside the + transaction. A tenant that already has an administrator, or ever had a Membership, + cannot gain one this way, so the act is not an escalation path. +8. **Recovery.** `OperatorRecoverAdmin` refuses unless, under the same locks, the tenant + has no active tenant-wide administrator Membership. It has its own audit slug and + reason slug, accepts the same person-naming rule, and leaves the last-admin invariant + unchanged. It is the only act that may add an administrator to a tenant with + Membership history. +9. **Audit.** Each step writes its MUST rows in its own transaction through the ordinary + pipeline, under the real target tenant. Provisioning writes two, the Tenant and the + Organization. The pipeline's authorization audit context, evidence coordinator and + draft composer, which today admit a null actor, a missing tenant and a null reason + only for `Seed`, gain a `PlatformOperator` branch that records the closed reason slug + and `metadata.operator` of [ADR-0101](0101-platform-operator-authority.md) § 9. The + rows never carry the ticket. +10. **Seed capability.** The Seeder refuses to run when `Deployment:Mode` is not + Development. A test proves the seed source cannot perform an operator act and the + operator source cannot perform a seed act. +11. **Signals.** Counters record each act by operation and outcome, and a resumed setup + by the step it resumed at. + +## Context + +> **Erratum — 2026-11-19.** The first paragraph below counts "one new confined setter" +> among the costs. No setter was added and the context writers are five, not four; +> shown by `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + +Onboarding is not the platform scope's job. The scope exists to cross tenants and write +platform tables, and the platform role bypasses row security. A first administrator is +the opposite case: one tenant, ordinary tables, and the strongest invariants in the +Identity module. Running it on the app role keeps those invariants and the capture of +[ADR-0044](0044-audit-write-path.md) § 7, and costs one new authorization source, one +new confined setter and five commands, which the closed censuses make visible and +testable. The cost is real: the source enum, the setter census and the audit composition +all change, and their existing negative controls must keep refusing everything else. + +The seed guard is the reason for separate commands. It is a deliberate only-this-source +check, and the operator authority must not borrow it. Extracting shared cores keeps the +duplication to the guard. + +Naming a person by provider subject keeps email out of authority. It asks the person to +sign in once first, which is the zero-membership entry P03-3 already ships. The operator +reads the `sub` from the issuer's own console, which the operator already holds. The +operator-supplied tenant id is safe because the command is reachable only with an +admission, and it makes a retry exact. + +What would reopen this: a Hub that pushes provisioning and mappings, a need for a +self-service first administrator, or an operator population too large for subject-based +naming. + +## Consequences + +### Positive + +- No production onboarding depends on the development seed, and a test proves the two + authorities cannot substitute. +- The last-admin and User invariants and the audit capture are unchanged and exercised. +- The no-Hub baseline can create a reachable tenant with an administrator, and recover + one. + +### Negative + +> **Erratum — 2026-11-19.** The first bullet below counts "a new confined setter" among +> the widened sets. No setter was added and the context writers are five, not four; +> shown by `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + +- A new authorization source kind, a new confined setter and a new resolver widen closed + sets that tests pin, so each census is edited deliberately. +- An operator needs the person's `sub`, and the person must sign in first at a mapped + host. +- The operator, not LearnStack, vouches for host ownership. + +### Neutral + +- Shared cores are extracted from the seed handlers; the seed behavior does not change. +- Seeded Development tenants are unaffected. + +## Implementation Notes + +> **Erratum — 2026-11-19.** The first bullet below says Step 2 delivers "the setter". No +> setter was added and the context writers are five, not four; shown by +> `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + +- Step 2 delivers the source, setter, resolver, commands, routes, audit-composition + branch, Seeder mode refusal and the onboarding runbook. It touches the source enum, + `OperationPolicy` and `TrustedOperationDescriptor` source guards, the authorization + audit context, the evidence coordinator and the draft composer. + > **Erratum — 2026-11-19.** The proof item below reads "succeeding after the last one + > is revoked". The database refuses that state: the deferred last-administrator guard + > rejects any commit that leaves a tenant without an available administrator, so no + > ordinary write reaches it; shown by SQLSTATE `P0303` in + > `PlatformOperatorOnboardingTests`. The proof reaches the state by an owner-level + > repair that steps around that guard and shows the invariant intact after the + > recovery, and "the setter's operation binding" reads as the executor's binding of + > the admitted operation to its request type. The Decision is unchanged. Current + > authority: Amendment 1 item 4. Recorded in Amendment 1. +- Proof: positive and denied acts; wrong tenant; unbootstrapped person; interruption + between every pair of steps with a retry that completes once; an unknown COMMIT; a + tenant with history refusing the first-admin act; recovery refusing a tenant with an + active administrator and succeeding after the last one is revoked; the last-admin + invariant after recovery; seed insufficiency in both directions. The mutation targets + are the source check, the in-transaction predicates, the resolver's Active filter and + the setter's operation binding. + +## Carriers + +> **Erratum — 2026-11-19.** The first paragraph below names "the eleventh logical +> setter" as ADR-0040's disclosure. No setter was added and the context writers are +> five, not four; shown by `SetTenant_Callers_Are_The_Enumerated_Four` and +> `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. The Decision is unchanged. +> Current authority: [ADR-0040 Amendment 25](0040-ambient-unit-of-work.md). Recorded in +> Amendment 1. + +Dated disclosures in [ADR-0036](0036-tenant-resolution-trusted-inputs.md) (the target +announcement), [ADR-0040](0040-ambient-unit-of-work.md) (the eleventh logical setter), +[ADR-0044](0044-audit-write-path.md) and [ADR-0033](0033-audit-durability-model.md) (the +audit-composition branch), [ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) (the production +path), [ADR-0074](0074-membership-admission-under-ordered-locks.md) (the recovery +predicate under its locks), Standards 05, 18 and 19, the Identity and Tenancy module +specifications, and the Phase 03 Status. + +## Amendments + +### Amendment 1 — As built: an executor-installed context, no new setter (2026-11-19) + +Step 2 of the packet shipped the five acts. Two statements of this record were false +when it was accepted, and each carries an inline erratum above it: the new tenant setter +and unchanged context writers of § 1, repeated in Context, Consequences, Implementation +Notes and Carriers, and the proof item that revokes the last administrator. Both were +shown by the shipped code and its tests +(`SetTenant_Callers_Are_The_Enumerated_Four`, `PlatformOperatorActExecutorTests`, and +SQLSTATE `P0303` in `PlatformOperatorOnboardingTests`). The items below refine what the +record left open or stated differently from what was built; they are history, not +errata. + +1. **No new setter; a fifth context writer.** The operator act executor + (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs`) + consumes the single-use admission, opens a fresh scope, installs an immutable + resolved `Ambient` context for the admitted tenant (no user, no organization, no host + scope) and sends the command through the ordinary pipeline, which announces that + context as it does for seed, delivery and job acts. The logical setter census stays + at fourteen ([ADR-0040](0040-ambient-unit-of-work.md) Amendments 22 and 23), the + platform role is not used, and the executor is the fifth writer of the context + accessor ([ADR-0036](0036-tenant-resolution-trusted-inputs.md) Amendment 2). The one + source that may mint the operator descriptor is the fourth minting source, scoped to + the executor's frame and bound to the operation of the admission. The routes that may + call the executor are pinned by + `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act`. +2. **Provisioning on a resolved context.** The new tenant's id is the act's target, so + the executor installs a resolved context for an id that has no `tenants` row yet, and + the ordinary insert policy admits it. The operator provisioning command therefore + needs no provisioning announcement, and the seed command keeps its own. +3. **The resolver is the sixteenth definer.** + `fn_identity_operator_resolve_user(uuid, bytea)` takes the stored authority id and + the derived subject key. The application derives the key with the one + `IdentitySubjectKey` implementation under the deployment's qualified authority, and + the function refuses any other authority, any session but the application role, any + key that is not 32 bytes and any transaction that is not an ordinary read-write + tenant one, then answers an Active user's id or null. The handlers ask the guard + whether the act is live before they call it. The function is nonetheless callable by + any application-role transaction that announces a tenant, so what it protects is the + subject lookup's confinement to the application role and not a witness bound to an + act; [Database Standards](../standards/05-database.md) records the residual. +4. **Recovery is a break-glass for repaired states.** The last-administrator guard is + deferred to commit and rejects any write that leaves a tenant without an available + administrator, which means a Membership with an Active tenant-wide administrator Role + whose User is Active. Revoking or suspending the last administrator is therefore not + reachable through any ordinary path, and Users have no admitted update or removal + owner today. § 8's predicate is a Membership predicate, as accepted, and is + implemented as written: the act refuses while an Active tenant-wide administrator + Membership exists. A tenant whose only administrator Membership is nominally Active + but unusable is not a recoverable tenant under it, and a predicate that also reads + the User's eligibility would need a second confined definer. The maintainer decides + whether that is wanted. +5. **"Membership history" is tenant-wide history.** § 7 refuses a tenant that "ever had + a Membership". The predicate is evaluated under the act's own context, which carries + no organization and no tenant-wide read witness, so row security shows it + tenant-wide Memberships only. A tenant whose only Memberships are organization-scoped + reads as having had none. Ordinary writes cannot produce that state, because the + graph guard requires a tenant-wide administrator, so it is reachable only after an + owner-level repair, as recovery's state is, and the database's own guard reads the + same way. +6. **"Bootstrapped" means a global binding.** §§ 5 and 6 say the person signs in at the + tenant's mapped host first. The resolver finds an Active user of the stored authority + with that subject, wherever they signed in, because `users` is global per authority. + The runbook says so and asks the operator to confirm the subject belongs to the + intended person. +7. **Idempotency as built.** An exact repeat of an act answers from what was stored; a + repeat that changes any value under the same identifiers is refused + (`lockey_identifier_taken`). The administrator and Role acts find their own + Membership or Role before judging the Role's present state, so a template the new + administrator edited afterwards does not make the original act's retry fail. A + repeated act commits its ordinary MUST rows with no captured change, so the trail + shows every attempt. The host-mapping retry drops the host's cached resolution again. +8. **Signals (§ 11).** `learnstack_platform_operator_acts_total{operation,outcome}` + counts each act as `applied`, `replayed`, `refused` or `failed`; a `replayed` count + by operation is a setup resumed at that step. Event 7109 (Warning) records an + admitted act the pipeline itself refused as forbidden, which writes no durable row. +9. **Shared cores.** § 2 and Consequences promise shared cores extracted from the seed + handlers so the domain logic exists once. Tenancy shares by handling the seed and + operator commands in the same classes. Identity does not extract a core: its operator + handlers compose the same aggregates and gates (`Role.Create`, `Membership.Create`, + `SeedFoundationGate`, `SeedMembershipCreation.IsDeclaredRole`) in their own + choreography, because the seed handlers' declaration, prerequisite and guard + plumbing is the part that differs. What is duplicated is the order of the steps, not + a domain rule. +10. **The ticket is not recorded.** The gate validates the optional ticket's grammar and + the five acts record it nowhere, because + [ADR-0101](0101-platform-operator-authority.md) § 9 keeps it only on tenantless + sentinel rows and these acts write none; the audit rows carry the correlation id the + answer returns, and the operator keeps the ticket beside it. +11. **Request shape.** Every identifier is a UUIDv7 and the platform sentinel is refused + as a tenant (400). A host mapping must state both `isActive` and `isPubliclyLive`, + because no act unmaps a host. A blank provider subject or one over 255 characters is + a 400, template and scope names are matched exactly and not parsed, and a refused + storage write answers in the vocabulary the sibling Identity handlers use + (`concurrency_conflict`, `dependency_unavailable`, or + `identity_foundation_refused`). An unqualified identity authority is + `dependency_unavailable`, and every 503 an act answers carries `Retry-After`. The Tenancy writes of the two Tenancy acts classify + only a unique violation: a lock timeout on a unique-index wait, as when two operators + map one host to two tenants at once, surfaces as a 500, and the same request repeated + gets the right answer. A host mapping needs only that the tenant exists and is not + deleted, where the Identity acts also need it to be Trial or Active. + +The business actor of every written row is `UserId.SystemActor` and the audit actor is +NULL, as § 3 and [ADR-0101](0101-platform-operator-authority.md) § 9 say. A refused +operator act writes the ordinary `failed` MUST row in the target tenant, carrying the +operator in `metadata.operator`, and an authorization refusal of an operator request +writes no durable denial row ([ADR-0033](0033-audit-durability-model.md) Amendment 14). + +Carriers changed with this amendment: ADR-0033 Amendment 14, ADR-0036 Amendment 22 and +ADR-0040 Amendment 25, each with an inline erratum beside the false text; Database +Standards, Security Standards, Audit Coverage, Permission Standards and the +Architecture-Tests Catalogue; the Identity and Tenancy module specifications; the +glossary and the onboarding runbook. +[ADR-0072](0072-application-owned-identity-bootstrap.md), +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](0074-membership-admission-under-ordered-locks.md) are read and unchanged: no +sentence of theirs is stale. The Decision, Status, Date and every other section are +unchanged. Acceptance of the linked records is not proof that anything they decide is +implemented. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0103](0103-operator-recovery-of-asynchronous-work.md), + [ADR-0104](0104-controlled-issuer-rebind.md) +- [ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md), + [ADR-0074](0074-membership-admission-under-ordered-locks.md), + [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) +- [Identity module](../modules/identity/README.md), + [Database Standards](../standards/05-database.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 diff --git a/docs/decisions/0103-operator-recovery-of-asynchronous-work.md b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md new file mode 100644 index 000000000..496bc6cd1 --- /dev/null +++ b/docs/decisions/0103-operator-recovery-of-asynchronous-work.md @@ -0,0 +1,367 @@ +# ADR-0103: Operator Recovery of Asynchronous Work + +## Status + +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes gate G14 and, with [ADR-0101](0101-platform-operator-authority.md), +decides the dashboard question that D13 raises. It authorizes the code it describes and +is not proof that anything is implemented. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0046](0046-durable-event-delivery-and-recovery.md) says "operator replay is Phase + 03, with a separately specified reset/fencing contract before any endpoint ships". + `DeliveryDispatchStore.ReplayAsync` exists and has no production caller. It takes no + actor, reason or stale-state token, filters no terminal reason and writes no audit + row, so a second operator can reset a row a first operator already re-terminalized, + and an `invalid_envelope` delivery can be reset to fail again. +- [ADR-0047](0047-transactional-background-job-runtime.md) keeps a quarantined job + frozen for every role by trigger, retains its reservations, and releases capacity only + on confirmed completion, no-start or quiescence. Operator authority, elapsed time and + a missing worker are not that proof. The external definitions today are the two + invitation-email ones, whose outcome can end `Unknown`, and the mail adapter offers no + fence an operator could cite. +- `learnstack_platform` holds no privilege on inbox, delivery or job tables + ([Data Protection](../architecture/23-data-protection.md)), which says any change + needs its own bounded decision and migration. The outbox role holds table-wide + `SELECT` on `outbox_messages`, so a payload exclusion there would rest on code + discipline alone. +- Only ADR-0046's confined dispatcher writes outbox status today; a second writer is a + decision, not an implementation detail. +- The Hangfire dashboard needs a browser session on an API with none + ([ADR-0004](0004-authentication-strategy.md)). The runtime's storage runs on the + privileged source, so a dashboard write control reaches past the job fences. The stock + statistics are suppressed ([ADR-0058](0058-bounded-stock-hangfire-maintenance.md)), a + vendor "Succeeded" is not business success, and the runtime maps no dashboard: an + architecture rule refuses any dashboard type. + [ADR-0015](0015-api-gateway-apisix.md) still guides a backend filter on the realm role + `platform-admin`, which [Standard 19](../standards/19-permissions.md) forbids. +- C15 requires dashboard and recovery to remain absent until admitted, and then proof of + positive and denied routes, stale fences, producer-versus-subscriber separation, + unchanged siblings, quiescence and reservations, MUST result audit and usable + runbooks. + +## Considered Options + +1. **Metadata inspection through the platform scope on column-limited grants, and fenced + transitions on a confined outbox-role owner, with no dashboard** (chosen). The + database enforces the projection, the scope entry row audits each inspection, and + each transition carries a stale-state fence and a same-transaction result row. +2. **Admit the Hangfire dashboard read-only** (rejected now). It adds a browser session + path and a second source borrower, and shows state the runtime says is not + authoritative. Its read-only form shows less than the inspection set below. +3. **Run the transitions in the platform scope with new platform write grants** + (rejected). It widens a `BYPASSRLS` role with writes on tables the corpus holds + closed, and none of the transitions crosses tenants. +4. **Inspect through the outbox role** (rejected). It reads cross-tenant on a role whose + `SELECT` is table-wide, with no per-call audit. +5. **Release or requeue quarantined jobs on operator attestation** (rejected). It would + supersede [ADR-0047](0047-transactional-background-job-runtime.md)'s quiescence rule + and let an unfenced external start run again. +6. **Admit nothing and ship a runbook** (rejected). An exhausted dead letter would have + no remedy, and C15's stale-fence and sibling proofs would have no subject. + +## Decision + +LearnStack admits a metadata-only inspection and two fenced transitions, and no +dashboard. + +| Operation | Permission | Principal | Audit | +|---|---|---|---| +| `platform.delivery.inspect` | `platform.delivery.read` | platform scope, column grants | scope entry row | +| `platform.delivery.replay` | `platform.delivery.write` | outbox-role owner | result row, `delivery_replay` | +| `platform.delivery.reset` | `platform.delivery.write` | outbox-role owner | result row, `delivery_reset` | + +1. **Inspection.** Cursor-paged metadata for dead-lettered outbox rows, rows whose + terminal request is pending, terminal delivery rows and quarantined jobs with their + reservation occupancy. A migration gives `learnstack_platform` `SELECT` on named + metadata columns of `outbox_messages`, `event_deliveries`, `background_jobs` and + `background_job_reservations`, excluding every envelope, parameter, plan, outcome and + causal column, so the database refuses what the projection must not return. Grant + tests read column privileges. Each row returns the fence its transition needs. A row + whose terminal request is pending shows its state and is not actionable. + + > **Erratum (2026-11-20, Amendment 1 items 2 and 6).** The platform role already + > held table-wide `SELECT` on `outbox_messages`, so named column grants beside it + > would have excluded nothing: the migration revokes it first. The scope's entry row + > carries the operation `platform.admin_scope.enter` and the reason + > `delivery_inspect`, not the slug `platform.delivery.inspect` as an operation. +2. **Targeted subscriber replay.** `platform.delivery.replay` resets one + `(tenant, subscription, event)` delivery. The request carries the fence read at + inspection: `replay_count`, `dead_lettered_at` and `terminal_reason`. It is refused + unless the fence still matches, the row is dead-lettered and unleased, the + subscription is an Active ordinary one and the event's tenant is Active. A delivery + that ended `invalid_envelope` is always refused, because an immutable envelope cannot + become valid, and `unknown_type` and `retired_type` follow the registry at replay + time. A completed delivery, its inbox row, every sibling delivery and the producer + row are untouched, and a privileged subscription is refused. +3. **Narrow producer reset.** `platform.delivery.reset` resets a dead-lettered outbox + row whose `terminal_reason` is `retry_exhausted` and which is not processed, under + the fence `(attempts, dead_lettered_at)`. It clears the terminal fields and the + lease, resets attempts and sets `available_after` to now. Every other reason is + refused. The reset deliberately renews the six-attempt budget. A publication that + already reached a subscriber is absorbed by stable event-id acceptance + ([ADR-0046](0046-durable-event-delivery-and-recovery.md): terminal state does not + prove that no subscriber accepted). Acceptance never reopens an existing delivery + row, so the next dispatch reaches the Active subscriptions that have no delivery row, + and a delivery that already ended terminal needs its own subscriber replay. Producer + reset is not a power of subscriber replay: the two are separate requests with + separate fences and neither writes the other's table. +4. **Principal.** A new confined owner uses the outbox-role credential behind an + [ADR-0101](0101-platform-operator-authority.md) admission. It is a second writer of + outbox and delivery status beside the dispatcher, recorded by an + [ADR-0046](0046-durable-event-delivery-and-recovery.md) disclosure. + `LearnStack_OutboxAdmin_Role_OnlyUsedBy_OutboxProcessor` gains exactly that owner, + `ReplayAsync` moves behind it with its new signature, and no HTTP path resolves the + dispatcher's store directly. The tenant lifecycle test reads the existing lifecycle + projection the outbox role already holds. +5. **Result audit.** A new witness kind, not the terminal witness, is minted from the + fenced `UPDATE ... RETURNING` on the same outbox-role transaction and writes the row + with the real event tenant, the closed reason slug, `metadata.operator` and + `metadata.fence` (before and after). The terminal witness demands the system actor, a + null reason and no metadata, so it cannot carry an operator. A forced audit failure + rolls the transition back and answers 503 with no state change. A stale fence answers + 409 `stale_fence`, a refused state 409 `not_recoverable`, and neither writes a row or + changes state. + + > **Erratum (2026-11-20, Amendment 1 items 3 and 4).** The witness is a sibling + > class with two kinds, not a new kind of the terminal witness, and `stale_fence` + > and `not_recoverable` are reasons on the fields `fence` and `state` of the code + > `business_rule_violation`, because the status map is closed. A commit whose + > answer was lost is `503` `dependency_unavailable` with the reason + > `lockey_outcome_unknown` on the field `outcome`. +6. **Not admitted: job recovery.** No job requeue, retry, probe re-arm, reservation or + capacity release exists. A quarantined job stays frozen, retains its reservation and + keeps `jobs` unhealthy, exactly as + [ADR-0047](0047-transactional-background-job-runtime.md) says. The trigger to admit + one is the first external definition whose adapter can supply provider fencing or + process-tree termination evidence; none can today, and the phase that ships such an + adapter owns the decision, with + [Phase 11](../roadmap/phase-11-production-hardening.md) owning operational + reconciliation. For the invitation path, reissue helps only while a tenant slot is + free: it does not reconcile or release the old effect + ([ADR-0093](0093-verified-invitation-acceptance-and-handoff.md)), and four unresolved + effects can hold every slot with no operator remedy. That limit is stated, not + softened. +7. **Not admitted: recurrence recovery.** No recurrence, occurrence or recipient skip, + abandon, pause or resume exists. No production recurrence exists; Phase 11 owns it. +8. **Dashboard.** `/admin/hangfire*` stays unmapped and answers 404 in every deployment + mode, and the catalogue's dashboard-absence rule stays. The inspection set is the + operator's view. A dashboard write control is never admitted. A read-only dashboard + needs its own decision on authentication, the dependency and the source borrower. +9. **Erasure.** The Active-tenant test in § 2 and § 3 is the guard until P03-10 (G16) + defines a replay floor after erasure, and P03-10 re-verifies these transitions at its + first writer. The runbook states the limit. +10. **Signals and runbook.** Counters record each operation by outcome and fence + refusals separately, so a monitoring owner can see a replay storm. + `docs/runbooks/operator-recovery.md` covers the signal, inspection, the + replay-versus-reset choice, what is not recoverable, the invitation limit and how to + verify that the row became due and the real executor completed it. + +## Context + +The existing replay is correct in shape and unsafe in use: it checks the row state and +nothing about which state the operator saw. A fence token is the smallest change that +makes a second operator's stale decision refuse instead of act. Inspection moves to the +platform scope because it is the only act that reads across tenants, and column grants +make the projection a database fact with the scope's entry row as its audit. The +transitions stay on the outbox role because they cross no tenant and need no new write +grant. + +The producer side is admitted narrowly because its one recoverable case is real. A burst +of dispatch failures longer than the six-attempt budget strands an event with no remedy, +and acceptance is idempotent by stable identity, so a deliberate redispatch is safe. + +Job recovery is left closed because the closing condition is evidence the runtime cannot +get from an operator. That is a real limit, not a deferral for convenience. + +The dashboard is the one place this ADR departs from the roadmap's wording of D13. The +roadmap says the dashboard is admitted behind the Platform gate. The findings above show +that the gate cannot make it safe: authentication is the wrong shape, and its controls +write around the fences. The inspection set gives the operator the same facts in a +contract this repository owns and tests. + +What would reopen this: a Hub or Phase 11 need for a read-only dashboard, a provider +adapter that supplies quiescence proof, or a measured need to re-arm reconciliation. + +## Consequences + +### Positive + +- C15's stale-fence, sibling, producer-versus-subscriber and audit proofs have real + subjects, and the projection is enforced by grants. +- An operator sees exactly what a transition will act on, and a stale decision refuses. +- ADR-0015's false guidance is withdrawn with a dated disclosure. + +### Negative + +- A column-grant migration on a `BYPASSRLS` role, and a second outbox status writer. +- The operator has no dashboard, only an API and a runbook, until a UI exists in the Hub + operator portal. +- A stuck external job has no operator remedy, which is + [ADR-0047](0047-transactional-background-job-runtime.md)'s rule restated, not + softened. +- The producer reset renews the retry budget, and the runbook says so. + +### Neutral + +- [Phase 11](../roadmap/phase-11-production-hardening.md)'s statements that producer + replay and job requeue exist are rewritten as conditional on this ADR. + +## Implementation Notes + +- Step 4 delivers the grants migration with the canonical SQL, the owner, routes, + fences, the two witness kinds, census edits, the ADR-0015 and ADR-0046 disclosures and + the runbook. The grant expectations and the delivery-boundary signature census change + with the code. +- Proof: a replay with a current fence completes and the real executor runs once; a + stale fence, a completed, live, pending, privileged, retired, `invalid_envelope` and + inactive-tenant delivery each refuse; the sibling, another tenant, another event, the + inbox and the producer row are byte-identical; a reset of every other reason and of a + processed row refuses; a forced audit fault leaves no change; a tenant token, a + wrong-purpose token and a different Platform permission fail before any credential is + resolved; the platform role cannot select an excluded column; `/admin/hangfire` is 404 + in every mode; quarantined job rows are byte-identical after every act. The mutation + targets are the fence comparison, the reason filter, the tenant test and the result + row. + +## Carriers + +Dated disclosures in [ADR-0015](0015-api-gateway-apisix.md) (Amendment 2: the realm-role +gate bullet quoted and withdrawn, the route stays absent), +[ADR-0046](0046-durable-event-delivery-and-recovery.md) (the replay and reset contract +and the second writer), [ADR-0047](0047-transactional-background-job-runtime.md) +(operator reconciliation is inspection only, and the platform column grants), +[ADR-0044](0044-audit-write-path.md) (the two witness kinds). +[Phase 11](../roadmap/phase-11-production-hardening.md)'s replay and requeue statements, +Standards 05 and 20, the Tenancy audit matrix, the Phase 03 D13 wording, and the stray +fragment in the checklist of [Architecture 30](../architecture/30-api-gateway.md) +follow. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0102](0102-production-tenant-onboarding.md) +- [ADR-0015](0015-api-gateway-apisix.md), + [ADR-0046](0046-durable-event-delivery-and-recovery.md), + [ADR-0047](0047-transactional-background-job-runtime.md), + [ADR-0058](0058-bounded-stock-hangfire-maintenance.md), + [ADR-0093](0093-verified-invitation-acceptance-and-handoff.md) +- [Event and Outbox](../architecture/15-event-and-outbox.md), + [Data Protection](../architecture/23-data-protection.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G14, D13, C15 + +## Amendment 1 — Implementation contract of the recovery owner (2026-11-20) + +Step 4 of the platform-authority packet implements the decision. Each item below fixes +something the Decision left open or states where the code meets it; items 2, 3 and 4 +correct a statement the code could not satisfy as written. None of them changes the +Decision's choice of option, its two transitions, its permissions or its refusal of job +recovery. + +1. **Where the code lives.** The owner is `OperatorRecovery`, a singleton behind + `IOperatorRecovery`. It holds the two dispatcher stores and no credential, so the + credential census gains no reader and no keyed binding. `ReplayAsync` stays on + `DeliveryDispatchStore` with its new signature, and `ResetAsync` is new on + `OutboxDispatchStore`; both are partial-class files, and neither store's claim, fail + or terminalize code changed. Each store gained a third connection slot, reserved for + the operator lane: the dispatcher's own two slots (the main owner and its + uncertain-COMMIT reconciliation) are never taken by an operator, a second concurrent + operator call on a store is refused as unavailable instead of waiting, and the + physical-capacity ledger grows by the two lanes, from 52 to 54 for the default + topology and from 158 to 160 for the maximum. +2. **The platform role already read `outbox_messages` whole.** § 1 says a migration + gives the role `SELECT` on named columns so that the database refuses the rest. The + role held table-wide `SELECT` and `DELETE` there since the first platform migration, + so a column grant beside it would exclude nothing. The migration revokes the + table-wide `SELECT`, grants twelve named columns, keeps `DELETE` for the retention + purge that Phase 11 owns (its predicate has to read only granted columns), and grants named + columns on the other three tables: fifteen on `event_deliveries`, twenty-seven on + `background_jobs` and every column of `background_job_reservations`. No envelope, + parameter, plan, outcome, causal, trace, lease-token or operation-key column is among + them. It adds two partial indexes on the dead-lettered rows, because no index served + that scan. The canonical SQL is in Database Standards, and the platform-role tests + that read `correlation_id` moved to the owner and dispatcher roles. +3. **One witness class with two kinds, and no audit DDL.** § 5 says a new witness kind, + and the carrier disclosures say two. The code has one sibling class, + `OperatorRecoveryTransition`, whose protected minting seam is subtyped only by a + private nested class in each of the two stores and whose two factories are the replay + and the reset. It is not a third factory on the terminal witness, whose census pins + two. One new `IAuditStore` method, `WriteOperatorRecoveryAsync`, writes the row, + which makes fourteen writes. The outbox role already holds `INSERT` on `audit_log` + and bypasses row security, so no policy arm or grant changed: the binding of the row + to the real event tenant is the witness's, which composes the exact `metadata` (the + operator attribution, the event and subscription, and the fence before and after) and + refuses a draft that differs. +4. **The error vocabulary.** The API's status map is closed and answers an unknown + top-level code with `500`, so `stale_fence` and `not_recoverable` are not codes. A + stale fence is `409` `business_rule_violation` with the reason `lockey_stale_fence` + on the field `fence`, and a refused state is `409` with `lockey_not_recoverable` on + the field `state`, as the onboarding acts already answer. A missing row is `404`. A + MUST row that cannot be written, an unavailable lane or database, a failed + inspection read and a commit whose answer was lost are `503` with `Retry-After`. The + last is `dependency_unavailable` with the reason `lockey_outcome_unknown` on the + field `outcome`, so the body's status agrees with the response's: a new top-level + code would have answered `500` in the body under a `503` response. The cause of an + unavailable owner is logged and never returned. A page parameter that is refused + (`state`, `limit`, `cursor`) is `400` naming itself in `errors`; a `limit` of zero or + less is refused and a larger one, however large, is clamped, as Standard 04 says, + the quarantined-jobs list takes no `state`, and a parameter the route does not know + is refused as `query` without being echoed. A refused state names the rule that + refused it as the `cause` parameter of its reason: `processed`, `leased`, + `invalid_envelope`, `reason_refused`, `subscription_not_active`, + `type_not_dispatchable` or `tenant_not_serving`. Only a transient fault, a timeout + or the server's statement timeout is unavailable: a refused credential or a missing + grant surfaces as a `500`, because a retry cannot cure it. +5. **"The event's tenant is Active."** The test is the lifecycle projection the + dispatcher role already reads, read in the same transaction as the reset: the tenant + is not deleted, has its default organization and is Trial or Active, which is the + serving-tenant meaning the job runtime uses. Suspended and Archived tenants are + refused. A producer reset also refuses a row whose stored type the registry has since + retired or no longer knows, because a reset would only dead-letter it again with a + second MUST row. +6. **Inspection.** Each page is one entered platform scope on the platform role's column + grants, so the scope's entry row is the audit. Its operation is + `platform.admin_scope.enter` and its reason is `delivery_inspect`, the reason of the + admitted operation `platform.delivery.inspect`; it carries the ticket and the + operator's attribution, and it does not say which of the three lists was read. The + scope reads and changes nothing, so it writes no result row and ends by disposal; the + slug is still declared off-path, because the scope refuses an operation that is not. + A row's `lastError` is shown only when it has the shape of the dispatcher's + descriptors (`publish:failed:provider`) and is `unrecognized` otherwise, because the + database bounds the length of that column and not its content. `actionable` is the + row's and the registry's advice: the tenant's service state is read by the + transition, so a row of a suspended tenant can be listed actionable and refused. + Pages are keyset cursors bound to their resource and state, 1 to 100 rows, and a + cursor carries no authority. The fence timestamp is the stored microsecond, + returned and compared exactly. +7. **An unknown COMMIT is not reconciled automatically.** A reset and its row commit + together, so a lost answer leaves nothing to repair. A landed act leaves the + dead-lettered list, so the operator lists again, and a repeat of a landed act answers + `409` on the fence; the tenant's audit row, read by the correlation id, tells the act + from another operator's. The runbook says so. Any fault after the COMMIT was sent, + the connection's cleanup included, is reported the same way, because the answer is + then unknown. A cleanup fault on the operator lane seals its store as one on the + dispatcher's lanes does: the three lanes of one store share its unconfirmed-cleanup + seal, which only a restart clears, and the two stores do not share one. A sealed + store also never reports its privileged source released, so the shutdown of the + host waits as it does after a dispatcher fault. +8. **Signals.** `learnstack_platform_operator_recoveries_total{operation,outcome}` + counts each transition as applied, stale fence, not recoverable, not found, + unavailable or commit unknown, so a replay storm is visible. +9. **A producer reset of a type that is not yet Active.** The reset refuses a retired + or unknown type and acts on a pending one, whose row the dispatcher claims once the + type is Active, as it claims any row of that type; a replay refuses it, because it + needs an Active ordinary subscription. +10. **The tenant test is not locked.** The lifecycle read and the transition share a + transaction but not a lock, so a suspension that commits between them does not stop + the transition. P03-10 (G16) re-verifies this with the replay floor after erasure. + +The Decision, Status, Date and prior amendments of this record are unchanged. +Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/0104-controlled-issuer-rebind.md b/docs/decisions/0104-controlled-issuer-rebind.md new file mode 100644 index 000000000..2a63d80f0 --- /dev/null +++ b/docs/decisions/0104-controlled-issuer-rebind.md @@ -0,0 +1,308 @@ +# ADR-0104: Controlled Issuer Rebind + +## Status + +Accepted — 2026-11-19, after the maintainer's decisions on the dashboard, the producer +reset, the operator client and the grant store, and after three independent reviews and +the corrections they led to. The dated record is the +[Phase 03 acceptance record](../roadmap/phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19). +Acceptance closes the controlled issuer-rebind part of gate G13 together with +[ADR-0101](0101-platform-operator-authority.md) and +[ADR-0102](0102-production-tenant-onboarding.md), and authorizes the code it describes. +It is not proof that anything is implemented. + +**Date:** 2026-11-19 +**Deciders:** @cemil + +## Decision Drivers + +- [ADR-0072](0072-application-owned-identity-bootstrap.md) installs `identity_authority` + once and says P03-9 owns "a frozen-admission, privileged issuer rebind after proven + provider continuity, preserving AuthorityId, actors, keys and closed tombstones". + Until then rename is unsupported, and the installer refuses any conflicting anchor. +- Subject keys hash the stable `AuthorityId` and the exact opaque `sub`, never the + issuer URL ([Database Standards](../standards/05-database.md)). An origin change that + preserves both leaves every key valid, and a changed `AuthorityId` re-keys every + person and can resurrect a closed tombstone. +- The API qualifies `identity_authority` once per process in a read-only transaction and + refuses admission on a mismatch. The read takes no lock, so a process that starts + while a rebind runs can qualify against the old value and keep it until restart. +- The platform role runs in the API and worker hosts and bypasses row security. A column + grant on it would let any platform-scope code path change the issuer, and a + transaction-local setting is not a control, because any session can set it. +- The owner role used by the installer cannot write `audit_log`, so an owner-credential + change could not commit with its audit row. +- C14 asks for positive and denied proof, partial-commit proof and identity-continuity + proof, and says the dev seed authority is insufficient. + +## Considered Options + +1. **A dedicated rebind role used only by an offline tool that authenticates the human** + (chosen). The credential never reaches a runtime host, the change and its audit row + share one transaction, and the proof runs before the change. +2. **A column grant to the platform role guarded by a transaction setting** (rejected). + Every runtime platform connection holds it, and the setting is settable by any + session. +3. **The owner credential through the installer** (rejected). It cannot commit an audit + row with the change, and the installer is built to refuse a conflicting anchor. +4. **An HTTP operator act under a runtime admission freeze** (rejected). It adds a + database read to every authentication, and running processes keep the old issuer + because qualification is startup-only. + +## Decision + +1. **What changes.** Only the origin of `identity_authority.issuer`, under the same + realm path. `AuthorityId`, subject keys, actor ids and closed tombstones are + preserved, no realm rename is admitted, and the new realm must preserve each `sub`, + which a realm export and import does. +2. **The role.** A sixth login role, `learnstack_identity_rebind`, without `BYPASSRLS`, + holds exactly: `SELECT` and `UPDATE (issuer)` on `identity_authority`; `SELECT` of + `authority_id`, `subject_key`, `provider_subject` and `status` on `users`; and an + `INSERT` on `audit_log` that a policy limits to the platform sentinel, the identity + module and the two rebind operations, written only through the witness-bound methods + of [ADR-0101](0101-platform-operator-authority.md) § 10. Its connection string, + `ConnectionStrings:IdentityRebind`, exists only in the tool's environment, and an + architecture rule confines the key to the tool. +3. **The tool.** A new project, `LearnStack.Tools.IdentityAuthorityRebind`, separate + from the install-once installer. It reads the human's operator access token from + standard input or the environment, never an argument, validates it with the operator + validator of ADR-0101, and is the second sanctioned caller of the witness minter. The + operator must hold `platform.identity_authority.admin`. A refusal exits non-zero with + no change. +4. **A read-only realm credential.** The continuity proof enumerates users with a + `view-users` credential the operator supplies at run time. It is not a LearnStack + runtime or federation credential, and + [ADR-0099](0099-confined-tenant-federation.md)'s refusal of user-level authority for + LearnStack is unaffected. +5. **Freeze.** The tool runs in one transaction on a direct, non-pooled connection and + takes an exclusive transaction-level advisory lock on a fixed key as its first + statement. Authority qualification and the User-creation admission transaction take + the shared form of that lock, so a start or a new binding waits for the rebind and + then reads the new value. The tool also refuses while it sees a session of the + application, outbox or ingress role other than its own. A process that holds no + database connection is invisible to that check, so the runbook's stop step is the + control for it. Such a process keeps the old issuer only until it restarts, because + qualification then fails on the mismatch. +6. **Continuity proof.** Inside the lock, the tool reads the new issuer's discovery + document and key set and requires its `issuer` to equal the new value. It enumerates + the new realm's users completely or refuses. Every Active `provider_subject` must be + among the enumerated `sub` values. The canonical subject key of no enumerated `sub` + may equal a Closed user's key, so a closed person cannot reappear. A new-realm user + with no stored key is allowed, because that person has not bootstrapped. A refusal + reports counts and never identifiers. +7. **The change.** `UPDATE identity_authority SET issuer = @new WHERE id = 1`. A trigger + refuses any change to `id` or `authority_id`. The issuer grammar stays in the tool + and in qualification, which refuses a malformed or mismatched issuer, and is not + duplicated in SQL. +8. **Audit.** A short standalone transaction commits an intent row first, so an aborted + attempt is on record. The main transaction writes the MUST result row with the + change, and a forced audit failure rolls the change back. Both rows use the platform + sentinel and `metadata.operator`, and carry the ticket, because no tenant can read + them. +9. **Retry.** Every refusal leaves the state unchanged and a retry repeats the whole + proof. A tool run whose target already equals the stored issuer succeeds without + writing a row. An unknown COMMIT is reconciled by reading the issuer. +10. **After the change.** Processes configured with the old issuer fail qualification at + their next start. Deploying the new issuer configuration is the unfreeze. +11. **Signals.** Counters record each run by outcome and the continuity result by class. + +## Context + +A rebind is rare and dangerous, so it is shaped to be hard to do by accident. An HTTP +act would need a freeze on every authentication and still could not retire the issuer +that running processes hold. A dedicated role makes the strongest claim cheap to check: +no runtime host has the credential, so no runtime code path can change the issuer, +whatever it does. The cost is a sixth role, whose precedent is the fifth, +`learnstack_identity_ingress`, added the same way by +[ADR-0097](0097-retained-provider-events-and-tenant-audit-mirror.md). + +The advisory lock closes the start race without a request-path read: qualification runs +once per process and user creation is rare, so a shared lock on each costs nothing +measurable. What it cannot close is a process that is running, idle and connectionless +when the tool runs. The honest statement is that the operator's stop step and the +restart requirement bound that case, not the database. + +The proof compares against the stored facts rather than trusting an attestation. Active +rows retain the exact subject, so presence is a direct comparison; Closed rows retain +only the key, so absence needs the canonical encoding. + +What would reopen this: a realm rename, a federated authority change, or a need to +rebind without a downtime window. + +## Consequences + +### Positive + +- No runtime role or host can change the issuer, and the change, its proof and its + result row are checkable. +- Starts and new bindings cannot straddle the change. +- Denied, partial and continuity cases have exact subjects. + +### Negative + +- A sixth database role, its provisioning, grants and census. +- A downtime window, and an operator-supplied read credential for the new realm. +- A connectionless survivor is bounded by procedure, not by the database. + +### Neutral + +- The install-once installer and its refusal of a conflicting anchor are unchanged. +- Development environments never need a rebind. + +## Implementation Notes + +- Step 3 delivers the role and its provisioning in the local stack and test fixtures, + the grants and trigger migration with the canonical SQL, the tool, the lock calls in + qualification and the creation transaction, the two audit methods and the runbook. + Grant tests read column privileges, not table privileges, because table-level views do + not show column grants. +- Proof: positive; no token, wrong audience, missing permission, stale authentication; + killed between the intent row and the main transaction, and before commit; an unknown + COMMIT; a forced audit failure; a missing Active subject; an extra new-realm user + allowed; a Closed key present refusing; a live second session refusing; a start that + blocks on the lock and then fails the mismatch; an unchanged `AuthorityId`; the + trigger refusing an `authority_id` change; the architecture rule on the + connection-string key. The mutation targets are the continuity comparison, the + Closed-key check, the lock and the rollback on audit failure. + +## Carriers + +Dated disclosures in [ADR-0003](0003-tenant-isolation-defense-in-depth.md) (the sixth +role), [ADR-0044](0044-audit-write-path.md) (the rebind rows), and +[ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) (the rebind +contract). Standards 05 and 11, the Identity module specification, the Phase 03 Status +and the runbook follow. + +## References + +- [ADR-0101](0101-platform-operator-authority.md), + [ADR-0102](0102-production-tenant-onboarding.md) +- [ADR-0003](0003-tenant-isolation-defense-in-depth.md), + [ADR-0072](0072-application-owned-identity-bootstrap.md), + [ADR-0097](0097-retained-provider-events-and-tenant-audit-mirror.md) +- [Database Standards](../standards/05-database.md) +- [Phase 03](../roadmap/phase-03-identity-admin.md): G13, D12, C14 + +## Amendment 1 — Implementation contract of the rebind tool (2026-11-20) + +Step 3 of the platform-authority packet implements the decision. Each item below fixes +something the Decision left open or states where the code meets it. Item 4 widens the +freeze check beyond the roles § 5 lists, and items 10 and 11 record residuals the +Decision did not state; none of them changes the Decision's choice of option, the +role's grants or the proof's rules. + +1. **Where the code lives.** The database half, `IdentityIssuerRebind`, lives in the + Identity module's Infrastructure `Bindings` namespace so unit and integration + tests reach it, beside the install-once installer. The tool project holds + configuration, the operator token, the new-realm reader and exit codes. The operator + validator moved from the API project into Infrastructure, so the API's bearer scheme + and the tool take one definition of the parameters, the bounded metadata manager and + the closed profile. The witness minter stays one class; the tool is a second caller + of the profile, with the executor `operator.rebind`, which is the "second sanctioned + caller" of § 3. An architecture rule pins the callers of the profile and of the + offline validator. +2. **The order.** The exclusive lock is the first statement of the transaction, held + by a server-side `lock_timeout` of 30 seconds, so the tool waits for another rebind + and refuses with a class. Under the lock it reads the stored authority. A run whose + target already equals the stored issuer, under the same authority, ends there, with + no row. Otherwise the intent row commits on a second connection before the freeze + check, the proof or the change. An authority that is not the configured one is a + continuity refusal, so it follows the intent row. An unknown COMMIT is reconciled on + a fresh connection that first takes the shared lock, so it reads the issuer only + once the original transaction has ended. +3. **The audit rows.** The two operations are `identity.authority.rebind_attempt`, + outcome `indeterminate`, and `identity.authority.rebind`, outcome `success`, with the + reason slug `issuer_rebind`, the entity type `IdentityAuthority` and the authority + id as the entity. The policy arm admits exactly those two operation-and-outcome pairs + and no other row, the ordinary tenant arm excludes the role so that an announced + tenant cannot widen it, and the central audit installer owns the `audit_log` SQL, as + it does for the creation witness. The result row carries counts and no subject. +4. **The freeze check counts the platform role too.** The platform role runs in the same + hosts as the application role, and an idle pooled connection of any of the four is + still a session. The check reports a count and never a session's identity. A pooled + connection stays a session until its idle lifetime ends, so the runbook's stop step + includes waiting for it. The check runs before the realm is read and again just + before the change, and each time it first drops the server's per-transaction snapshot + of the activity view, which would otherwise return the first count again. A host that + never takes the rebind lock (the outbox dispatcher, the ingress poller, the platform + role) is held only by this check. +5. **"Reads the new value" needs a comparison, and "waits" is bounded.** A lock alone + only makes a creation wait. Authority qualification takes the shared lock and then + reads under a fresh snapshot, and the User-creation admission takes the shared lock, + reads the stored authority and issuer, and refuses the creation when they are not + the facts its process qualified with. A creation waits for the lock for the two + seconds of its `lock_timeout` and is refused after that, and a start waits for the + command timeout, thirty seconds, and then fails its start with the fixed + qualification error. The two auxiliary read sources of the authorization and + evidence lanes take no lock: they run under a five-second total startup deadline, + and a start that straddles the change already fails at the locking read or at their + own comparison. +6. **The role is checked before it is used.** The tool refuses unless the session is the + rebind role, it holds no inherited, bypass, superuser, creation or replication + attribute, no membership, no owned object and no privilege on any other relation (a + sequence included, and the maintenance privilege of PostgreSQL 17), and exactly the + declared grants on the three it uses, compared column by column in both directions. A + relation that belongs to an extension is not counted, so a production database that + carries `pg_stat_statements` in `public` is not locked out; any other + `PUBLIC`-readable relation in `public` is. The tool also reads the session's own + `lock_timeout`, `statement_timeout` and `idle_in_transaction_session_timeout` from + the server and refuses when they are not what it asked for, as a connection pooler + that drops startup options would leave them. A refusal names the check that failed + with a closed `detail`, never a value. +7. **Continuity details the Decision left open.** A Closing user that still holds its + subject is judged by neither rule, because closure owns that transition; a Closing + user that holds only its key is judged like a Closed one. A reported subject that + cannot be a LearnStack subject is counted and cannot equal any stored one. Presence + is the exact ordinal subject. The new realm is read in full twice and the reads must + report the same users with none repeated, so a realm that changes while it is read is + refused; a realm above 200,000 users is refused because the proof cannot finish in + the tool's ten-minute deadline; a token that expires mid-enumeration is acquired + again once per request; and the credential is sent only after the realm's discovery + document names the target issuer. +8. **Inputs and exit codes.** The operator token comes from the environment or one line + of standard input and the ticket, the realm client and its secret from the + environment; an argument is refused. The deployment mode is a declared name, read as + the API reads it (case and padding do not matter, an ordinal or a list is refused), + because it decides whether a loopback operator issuer and the demo operator's grant + are admitted, and outside Development the target issuer must be HTTPS. The tool + prints one line of classes and counts to standard output, with the correlation id + that finds the rows, a closed `detail` where a class has more than one cause, and + exits `0` for applied or already applied, `2` for a refusal that left the state + unchanged and `3` when the commit's outcome could not be read back. A failure to read + back an unknown commit is `unknown`, never a refusal. An interrupt, a termination + signal or a hang-up ends the run as the deadline does. +9. **Signals in a short-lived process.** The counters are defined in the library and + exported by the tool only when an OTLP endpoint is configured in its environment, + under the label the printed line carries, including the refusals that happen before + the database is reached. The tool writes no log. The printed line and the audit rows + are the record otherwise, and a refusal at the operator gate leaves no row by design, + so the line is its only record unless the counter is exported. +10. **What the credential holder can do, and "the same realm path".** The tool checks + the operator's token, grant and attribution; the database does not force them. The + role holds `UPDATE (issuer)` and can insert a row of the admitted shape, so whoever + holds its password can change the issuer, or record a rebind that did not happen, + without the tool. The platform and outbox roles bypass row security and can insert + `audit_log` rows too, so the rebind rows are evidence under the same trust as every + other platform-sentinel row; no trigger confines these two operations to the rebind + role as one confines `identity.user.create`. The runbook keeps the password apart + from the operator's identity and retires it after the window; the grant and the + password sit in the tool's one environment, so that separation is a practice. A + database-enforced pairing of the change and its result row would need a confined + definer that reads `audit_log`, and is the maintainer's decision. "The same realm + path" means the realm name: the issuer must still end in `/realms/learnstack`, and + the path before it may change. +11. **What the move out of the API project loosened.** The operator token profile's + reader, `PlatformOperatorTokenProfile.TryRead`, is a public method of Infrastructure + so that the tool can call it, and it mints the witness the operator gate accepts. + Before the move the API project kept it internal and the compiler confined it. Its + callers are now confined by two census rules, the source census of the witness + minter and the IL census of the validator's callers, which cover the production + assemblies; a test assembly or reflection is outside them. The tool also leaves the + server's idle fence in force: it turns Npgsql's application keepalive off, because a + keepalive message restarts the server's idle-in-transaction clock, and asks the + operating system for TCP probes instead, so a hung tool is ended at fifteen minutes + and its lock freed. + +The Decision, Status, Date and prior amendments of this record are unchanged. +Acceptance of the linked records is not proof that anything they decide is implemented. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 075fbb2ed..0530e17d1 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -141,8 +141,12 @@ records hosted qualification. Phase 11 owns production qualification. | 0096 | [P03-5 Administration Contract Baseline](0096-p035-administration-contract-baseline.md) | Accepted 2026-11-10 after maintainer review and development-only/no-active-use confirmation: one exact snapshot/finding/comparator-bound incompatibility, with coordinated consumers and separate runtime/CI proof. Delivery stays in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | | 0097 | [Retained Provider Events and Tenant Audit Mirror](0097-retained-provider-events-and-tenant-audit-mirror.md) | Accepted 2026-11-11 after maintainer review: confined machine intake, finite pull recovery, nonblocking durable problem handling and frozen tenant Audit targets; implementation/qualification stay in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | | 0098 | [Session-Targeted Back-Channel Logout](0098-session-targeted-back-channel-logout.md) | Accepted 2026-11-12 after maintainer review: signed sid-targeted native notification, bounded replay/late-publication fences and owned callback-only TLS reachability; delivery/proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | -| 0099 | [Confined Tenant Federation](0099-confined-tenant-federation.md) | Accepted 2026-11-13 after three review rounds and the maintainer's decisions: a fixed-alias, LearnStack-owned connection per tenant; a dedicated Admin adapter with a fixed broker profile; a bounded egress guard with a documented Standard 11 A10 exception; a link-only first-broker flow with no broker-created accounts and no self-unlink; the broker enabled at the provider only in test windows and when Active; host-bound brokered sessions; serialized, readback-verified provider writes. Implementation Step 0 (Keycloak pin to 26.7.5) is committed in `ed168594`; Step 1 (registry v4 key, connection aggregate and storage) is committed in `7928fc8b`–`37af223c` with fixes through `30d94bb5`; Step 2 (application operations and API) is committed in `8e435ed6`–`91501770` with round-one and round-two review corrections; Step 3 (egress fetcher, Keycloak adapter and realm invariants) is committed in `d166e12d` with round-one and round-two review corrections; Step 4 (native BFF host binding and `federation_test`, the Studio page and the brokered SAML proof) is committed with round-one and round-two review corrections. [Amendment 2](0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13) pins 26.7.5 because no 26.6.5 image is published; [Amendment 3](0099-confined-tenant-federation.md#amendment-3--a-changed-oidc-configuration-needs-a-fresh-secret-2026-11-14) requires a fresh secret for a changed OIDC configuration; [Amendment 4](0099-confined-tenant-federation.md#amendment-4--corrective-disable-writes-and-gated-rotate-and-activate-2026-11-14) records the corrective disabling writes and the gated Rotate secret and Activate; [Amendment 5](0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14) records the Step 3 egress, allow-list, adapter-defence and reset-action decisions and the open brokered SAML login; [Amendment 6](0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) records the host-alias setter and the `federation.test_record` carrier; [Amendment 7](0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) records the Step 4 review's purpose, test-freshness, detail-load and availability statements; [Amendment 8](0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15) records the test-session replacement and scope-confinement corrections; [Amendment 9](0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18) records the PR review's behavior corrections and recorded decisions. | +| 0099 | [Confined Tenant Federation](0099-confined-tenant-federation.md) | Accepted 2026-11-13 after three review rounds and the maintainer's decisions: a fixed-alias, LearnStack-owned connection per tenant; a dedicated Admin adapter with a fixed broker profile; a bounded egress guard with a documented Standard 11 A10 exception; a link-only first-broker flow with no broker-created accounts and no self-unlink; the broker enabled at the provider only in test windows and when Active; host-bound brokered sessions; serialized, readback-verified provider writes. Implementation (Steps 0–4, including the Keycloak pin move to 26.7.5) is delivered and merged in PR #45; the [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns packet state. [Amendment 2](0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13) pins 26.7.5 because no 26.6.5 image is published; [Amendment 3](0099-confined-tenant-federation.md#amendment-3--a-changed-oidc-configuration-needs-a-fresh-secret-2026-11-14) requires a fresh secret for a changed OIDC configuration; [Amendment 4](0099-confined-tenant-federation.md#amendment-4--corrective-disable-writes-and-gated-rotate-and-activate-2026-11-14) records the corrective disabling writes and the gated Rotate secret and Activate; [Amendment 5](0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14) records the Step 3 egress, allow-list, adapter-defence and reset-action decisions and the open brokered SAML login; [Amendment 6](0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) records the host-alias setter and the `federation.test_record` carrier; [Amendment 7](0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) records the Step 4 review's purpose, test-freshness, detail-load and availability statements; [Amendment 8](0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15) records the test-session replacement and scope-confinement corrections; [Amendment 9](0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18) records the PR review's behavior corrections and recorded decisions. | | 0100 | [P03-8 Federation Contract Transition](0100-p038-federation-contract-transition.md) | Accepted 2026-11-18 after the maintainer's review, four independent reviews and the development-only/no-active-use confirmation: one exact snapshot-, finding- and comparator-bound incompatibility for registry v4, federation administration and the self `federationAlias`, one carrier per ADR and a stated end of the exception's basis; the later growth of the closed grant contract stays open as G20; delivery and proof remain in the [Phase 03 Status](../roadmap/phase-03-identity-admin.md). | +| 0101 | [Platform Operator Authority](0101-platform-operator-authority.md) | Accepted 2026-11-19 after the maintainer's decisions and three independent reviews: one human operator population at a deployment-controlled issuer, a second strict scheme confined to `/api/platform/v1`, per-act grants held by LearnStack, an admission witness, attributed result audit and the killswitch writer. | +| 0102 | [Production Tenant Onboarding](0102-production-tenant-onboarding.md) | Accepted 2026-11-19: operator-admitted tenant, host, Role-template, first-administrator and recovery commands on the app role, with a confined operator source and target announcement; the seed stays seed-only. | +| 0103 | [Operator Recovery of Asynchronous Work](0103-operator-recovery-of-asynchronous-work.md) | Accepted 2026-11-19: metadata inspection on column grants, fenced targeted subscriber replay and a narrow producer reset on a confined outbox-role owner; no job release and no dashboard. | +| 0104 | [Controlled Issuer Rebind](0104-controlled-issuer-rebind.md) | Accepted 2026-11-19: an offline operator act through a dedicated rebind role, with advisory-lock freeze, a continuity proof over every stored subject key, intent and result audit rows. | ## Proposed ADRs diff --git a/docs/glossary.md b/docs/glossary.md index e6b57900b..09c2a7434 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -11,8 +11,12 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Tenant** | A logical education platform or brand running on LearnStack. One LearnStack deployment can host many tenants. Each tenant has its own domain, branding, content, courses, and members. | | **Organization** | A sub-unit within a tenant — a branch, campus, studio, department, or cohort. Two-level hierarchy strict (`Tenant → Organization`, no nesting) per [ADR-0017](decisions/0017-tenant-organization-hierarchy.md). Every tenant has at least one default organization. | | **Brand** | Synonym for Tenant in product-facing language. In code, prefer `Tenant`. | -| **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm. Operates above tenants. | -| **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; finer-grained roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`). | +| **Platform Admin** | A LearnStack operator who manages tenants, plans, infrastructure-level settings. Authenticates against the `learnstack-hub` Keycloak realm, or another issuer the deployment controls. Authority comes from LearnStack-held Platform grants, never from realm roles ([ADR-0101](decisions/0101-platform-operator-authority.md)). Operates above tenants. | +| **Platform Admission** | The gate's proof that one authenticated operator may perform one registered operation now: the operator witness, the operation, an optional ticket and the correlation id. Minted only by the operator gate after it evaluates a grant, required by the platform scope and by every operator act ([ADR-0101](decisions/0101-platform-operator-authority.md)). | +| **Operator act** | One operation an admitted platform operator performs: the killswitch toggle, an inspection or a fenced recovery of asynchronous work, the federation report, remove or disable ([Federation operator](#federation-operator)), or one of the five onboarding acts of [ADR-0102](decisions/0102-production-tenant-onboarding.md) (provision a tenant, map its host, initialize a Role template, create the first administrator, recover an administrator). The gate admits one operation per act. The killswitch act, an inspection and the federation acts run in the platform scope; a recovery transition runs on the dispatcher's outbox role; an onboarding act runs on the application role through the ordinary pipeline under the target tenant's resolved ambient context, with `PlatformOperator` as its only authorization source (not a Seed act, not a Membership act), and is idempotent on operator-supplied identifiers. | +| **Federation operator** | The platform operator's report, remove and disable of identity-provider brokers a tenant's federation left **orphaned** (no live connection row names them), **unreadable owned** (the owner marker proves them LearnStack's and they no longer read as an admitted broker) or **nonconforming** (they differ from the fixed profile or carry a mapper). It acts only on a broker whose marker parses strictly to a tenant and a connection whose derived alias it is, writes an intent row before and a completion row after the provider call, removes an unreadable owned broker that is disabled even when a live row names it (the tenant's own Delete cannot reach one) and refuses to remove one that reads, or that is still enabled, while a live row names it, and cannot list or remove a realm user, so the account review a remove or a disable owes is a runbook step ([ADR-0099 Amendment 10](decisions/0099-confined-tenant-federation.md), corrected by Amendments 12 and 13, and the [runbook](runbooks/federation-operator.md)). | +| **Operator recovery** | The operator's inspection of dead-lettered outbox rows and deliveries and of quarantined jobs, and its two fenced transitions: a **replay** resets one dead-lettered subscriber delivery and a **producer reset** resets one retry-exhausted outbox row, which renews its six-attempt budget. Each transition carries a **fence**, the state the operator read at inspection (for a replay the replay count, the dead-letter instant to the microsecond and the terminal reason; for a reset the attempts and the instant), and is refused with a stale-fence conflict when the row no longer shows it. It writes a MUST audit row on the same transaction. Job recovery and a dashboard do not exist ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md), [runbook](runbooks/operator-recovery.md)). | +| **Hub Operator** | A subset of Platform Admins who use the operator portal (`operator-portal`). Same Keycloak realm; the finer-grained realm roles (`hub-platform-admin`, `hub-operator`, `hub-billing-viewer`) are Hub portal roles and grant no LearnStack authority. | | **Tenant Admin** | A user with administrative rights inside a single tenant. Authenticates against the `learnstack` Keycloak realm. Cannot see other tenants. | | **Org Admin** | A user with administrative rights inside a single organization within a tenant. | | **Deployment Mode** | One of `Development` / `SaaS` / `Dedicated` / `SelfHostedOnline` / `SelfHostedAirGapped` per [ADR-0020](decisions/0020-triple-deployment-hybrid-license.md). Selected at composition root; module code never branches on it. The two `SelfHosted*` variants differ on phone-home availability (entitlement source). | @@ -27,9 +31,10 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Provider event target** | Immutable tenant projection of one provider-global fact, with its own stable outbox event identity. It describes provider history rather than a tenant-authorized action; [ADR-0097](decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) owns the attribution contract. | | **ProviderEventRecipient** | Single-use machine execution witness for one claimed provider event target, separate from a human Membership or a generic integration-event envelope. [ADR-0097](decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) owns its scope boundary. | | **User** | A global application binding identified by the existing strongly typed `UserId`, separate from contextual Memberships. The permanent authority/subject-key mapping and lifecycle follow Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). | -| **Identity authority** | Stable provider namespace identified by a UUID and anchored to one current exact issuer URI in a deployment-installed, application-read-only singleton. Issuer drift cannot replace it. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) assigns installation to P03-1 and controlled rebind to P03-9/G13. | +| **Identity authority** | Stable provider namespace identified by a UUID and anchored to one current exact issuer URI in a deployment-installed, application-read-only singleton. Issuer drift cannot replace it. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) assigns installation to P03-1; only the controlled issuer rebind of [ADR-0104](decisions/0104-controlled-issuer-rebind.md) changes the issuer. | | **Identity subject binding** | Permanent mapping from stable identity authority and exact opaque subject, through the subject key, to one application actor. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) / [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md) contract. | | **Identity subject key** | Nonsecret SHA-256 equality and audit-linkage key derived from stable authority UUID and exact opaque subject under Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). It remains personal data, including for low-entropy subjects vulnerable to guessing. The [Database standard](standards/05-database.md#proposed-p03-1-identity-storage-annex) owns canonical encoding; [Data Protection](architecture/23-data-protection.md#proposed-identity-foundation-and-classification-ownership) owns retention purpose. | +| **Issuer rebind** | The controlled change of the one current issuer URI of the identity authority, under the same realm path, that preserves the stable `AuthorityId`, every subject key, actor id and closed tombstone. Run only by an offline tool on the confined `learnstack_identity_rebind` role, after the operator's token and `platform.identity_authority.admin` grant are admitted, a freeze (an exclusive advisory lock, with no session of a runtime role open) and a continuity proof against the new realm: every Active subject is still reported, and no closed person's key reappears. Writes an intent row and a result row under the platform sentinel. [ADR-0104](decisions/0104-controlled-issuer-rebind.md), [runbook](runbooks/identity-issuer-rebind.md). | | **Global-self bootstrap** | Admitted creation of only the verified provider subject's application binding, with no tenant Membership or permission. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) supplies the common internal owner; Accepted [ADR-0078](decisions/0078-native-session-scope-and-self-entry.md) defines bounded opt-in new-user HTTP/BFF entry. Implementation and qualification live in the [Phase 03 Status block](roadmap/phase-03-identity-admin.md). | | **Bootstrap admission** | Eligibility of a verified provider subject to attempt binding creation under independently admitted operation, authority, lifecycle, source and allocation-budget checks. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) and [ADR-0078](decisions/0078-native-session-scope-and-self-entry.md) establish no tenant Membership, invitation acceptance or ordinary BFF session merely by creating the actor. | | **Closure tombstone** | Retained Closed binding preserving subject key and actor indefinitely to refuse recreation, with raw subject removed by separately authorized closure. It remains linkable personal data, not anonymisation or a reusable actor reservation. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) defines the foundation; [Data Protection](architecture/23-data-protection.md#erasure-authority-and-first-writer-prerequisites) assigns actual closure/retained-copy fulfillment to P03-10. | @@ -193,7 +198,7 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **`TenantContextFactory`** | The single entry point that constructs the sealed `TenantContext`: it returns `Result.Fail` on any disagreement between the signals and never a partially populated context. `TenantContext` has no public constructor; `TenantContext_Is_Constructed_Only_By_The_Factory` enforces both halves. Per [ADR-0036 § The reconciliation matrix](decisions/0036-tenant-resolution-trusted-inputs.md). | | **`IOrganizationScopeValidator`** | The reader that answers "does this organization belong to this tenant", resolving `organizations` by the composite key `(tenant_id, id)` in its own short read-only transaction that sets `app.tenant_id` as its first statement — one of the sanctioned out-of-band setters of that GUC ([Security Standards § The out-of-band setters](standards/11-security.md), per [ADR-0040 Amendment 3](decisions/0040-ambient-unit-of-work.md)). A valid organization id from another tenant is a mismatch, not an override. | | **`DenyAllTenantMembershipReader`** | The Packet 7 `ITenantMembershipReader` that denies every membership question, so the reconciliation matrix's rows 7, 10 and 14 fail closed until [Phase 03](roadmap/phase-03-identity-admin.md) ships `Membership`. It makes the Studio tenant switcher 404 for everyone in that window; that is correct and it will look like a bug. Per [ADR-0036](decisions/0036-tenant-resolution-trusted-inputs.md). | -| **`EnterPlatformAdminScope`** | The explicit, scoped entry to cross-tenant access: a connection and transaction opened on a second, separately-credentialed data source that connects as `learnstack_platform` — never `SET ROLE`, which would make the four-role separation a naming convention rather than a boundary. Not one of the `ITenantContextAccessor` writers, and not an out-of-band setter of `app.tenant_id` — a `BYPASSRLS` role has no policy to announce to. **Logged in Packet 7, audited in Packet 9:** Packet 7 records entry through `ILogger` at `Warning`; Packet 9 adds the durable `security-event` row, written through `IAuditStore.WritePlatformScopeAsync` — a fourth *write* method with exactly one caller, and no relaxation of "no update method" — on the scope's own platform-role connection, in a transaction of its own that commits **before** the operation's begins, so an operation that later fails — or is abandoned — is still recorded. That row carries `TenantId.PlatformSentinel` ([ADR-0044 §§ 1, 10](decisions/0044-audit-write-path.md)). The C# member is `IPlatformAdminScope.EnterAsync`; `EnterPlatformAdminScope(reason)` is how the corpus names the path. See [Database Standards § How `EnterPlatformAdminScope(reason)` reaches `learnstack_platform`](standards/05-database.md). | +| **`EnterPlatformAdminScope`** | The explicit, scoped entry to cross-tenant access: a connection and transaction opened on a second, separately-credentialed data source that connects as `learnstack_platform` — never `SET ROLE`, which would make the four-role separation a naming convention rather than a boundary. Not one of the `ITenantContextAccessor` writers, and not an out-of-band setter of `app.tenant_id` — a `BYPASSRLS` role has no policy to announce to. **Logged in Packet 7, audited in Packet 9:** Packet 7 records entry through `ILogger` at `Warning`; Packet 9 adds the durable `security-event` row, written through `IAuditStore.WritePlatformScopeAsync` — a fourth *write* method with exactly one caller, and no relaxation of "no update method" — on the scope's own platform-role connection, in a transaction of its own that commits **before** the operation's begins, so an operation that later fails — or is abandoned — is still recorded. That row carries `TenantId.PlatformSentinel` ([ADR-0044 §§ 1, 10](decisions/0044-audit-write-path.md)). The C# member is `IPlatformAdminScope.EnterAsync`; `EnterPlatformAdminScope(reason)` is how the corpus names the path. See [Database Standards § How `EnterPlatformAdminScope(reason)` reaches `learnstack_platform`](standards/05-database.md). Entry takes a `PlatformAdmission` minted by the operator gate; there is no caller-supplied reason ([ADR-0101 § 7](decisions/0101-platform-operator-authority.md)). | ## Extension Model @@ -233,7 +238,7 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | **Entitlement Projection** | The read-only copy LearnStack holds, delivered by `PUT /api/internal/tenants/{id}/entitlements` or embedded in a signed licence key, stored durably in `platform_entitlement_cache` and served through `IEntitlementProvider`. The record carries `TenantId`, `PlanCode`, `Features`, `Limits`, `Compliance`, `ExpiresAt`, `GraceUntil` and a monotonic `Generation` — every field `entitlement-v1.schema.json` requires, the compliance caps that gate data residency and recording consent included. One name differs from the wire and one from the column: `PlanCode` is `tier` on the wire and `plan_code` in the column, and `ExpiresAt` is `expires_at` on the wire and persists to the `valid_until` column; `grace_until` and `generation` keep theirs in both. `ExpiresAt` and `GraceUntil` are both **nullable**: a null expiry means no scheduled expiry — trials and perpetual licences, the cohort the Hub creates first — and it persists as `valid_until NULL` rather than as a far-future sentinel somebody eventually has to explain, so Packet 9 alters the column Packet 6 shipped `NOT NULL`. `RefreshAsync` is **generation-guarded inside the write statement** — never read-then-write — and applies a push whose `generation` is **at least** the stored one, reporting `IgnoredAsStale` only for one that is older: a stale push cannot resurrect a revoked plan, and a redelivery at the same generation is idempotent rather than discarded, which is what keeps the provisioning row's default `1` from swallowing the Hub's first real projection ([ADR-0045 Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md)). Delivery is **push-primary, not push-only**: [ADR-0034](decisions/0034-hub-contract-surface-invariant.md)'s normative read order keeps a demand-driven `POST /api/v1/internal/license/verify` as its last step. Wire shape pinned by `entitlement-v1.schema.json` in both repositories. See [ADR-0045 § 1](decisions/0045-entitlement-and-feature-flag-socket.md). | | **Course Access** | *Not* an entitlement — a learner's right to open a course. See *Enrollment & Access*. | | **Feature Key / Limit Key** | A typed value object (`FeatureKey`, `LimitKey`) from the `FeatureKeys` / `LimitKeys` static catalogs. Free-form strings are forbidden. A **feature** key is spelled `{area}.{name}` with no `.enabled` suffix — `classroom.recording` — and its descriptor additionally declares two things that are never inferred from the string: whether the key is **fail-open or fail-closed** when no projection exists at all, and the `KillswitchKeys` entry that gates it, by name and nullable. An existing projection past `grace_until` instead yields every feature false and every limit zero, regardless of key class ([ADR-0045 Amendment 3](decisions/0045-entitlement-and-feature-flag-socket.md#amendment-3--when-a-keys-class-decides-2026-09-11)). A **limit** key carries the **`limits.` prefix the Hub already ships** — `limits.max_users`, `limits.classroom_minutes_per_month` — because the Hub has merged plan validators built on that vocabulary and LearnStack has no implementing line; the earlier `tenancy.max_learners` / `classroom.minutes_per_month` / `media.storage_gb` spellings are **withdrawn** ([ADR-0045 Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md), [ADR-0021 (2026-09-08)](decisions/0021-feature-based-entitlement.md)). A `LimitKey`'s value is a sentinel-carrying `long`: `-1` is unlimited, `0` is denied, `> 0` is the allowance. `GetLimitAsync` returns `long` and never `long?` — "not projected" is not a state a caller can act on — and a key absent from the projection resolves to the catalog default the key declares ([ADR-0045 § 3](decisions/0045-entitlement-and-feature-flag-socket.md)). See [26-hybrid-license-model.md § 0](architecture/26-hybrid-license-model.md). | -| **Killswitch** | A `KillswitchKeys.*` flag whose default is "enabled" and gates an expensive or risky code path. Flipped off during an incident to disable the path platform-wide. The overlay is applied last and wins over both the plan projection and the tenant flag, and it reaches a key only through the `KillswitchKey` that key's descriptor **names** — the correspondence is declared, never derived from the spelling, so a renamed key cannot go silently ungated. It lives in **`platform_killswitches`** — one platform-scoped row per key, no `tenant_id` and no foreign key — and **not** in `tenant_feature_flags`, whose foreign key to `tenants` the deliberately absent sentinel cannot satisfy and which no role or `BYPASSRLS` attribute moves. Read through the L1 cache under the `platform:tenancy:killswitch` family and invalidated on toggle; a read failure resolves to the key's default (`true`) and logs at `Error`, because a cache outage must not disable every gated path platform-wide. **Packet 9 ships the table, the policies, the overlay and the cache family — and no writer**: every toggle runs inside `EnterPlatformAdminScope(reason)`, whose registered gate is `DenyAllPlatformAdminGate`, so nothing can enter that scope until the Platform-scope permission arrives, and [Phase 03](roadmap/phase-03-identity-admin.md) owns the toggle command, its permission and its runbook. Every gated read honours a flipped switch the day one exists; what is absent is the flipping. Per [ADR-0045 § 5 and Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md). | +| **Killswitch** | A `KillswitchKeys.*` flag whose default is "enabled" and gates an expensive or risky code path. Flipped off during an incident to disable the path platform-wide. The overlay is applied last and wins over both the plan projection and the tenant flag, and it reaches a key only through the `KillswitchKey` that key's descriptor **names** — the correspondence is declared, never derived from the spelling, so a renamed key cannot go silently ungated. It lives in **`platform_killswitches`** — one platform-scoped row per key, no `tenant_id` and no foreign key — and **not** in `tenant_feature_flags`, whose foreign key to `tenants` the deliberately absent sentinel cannot satisfy and which no role or `BYPASSRLS` attribute moves. Read through the L1 cache under the `platform:tenancy:killswitch` family and invalidated on toggle; a read failure resolves to the key's default (`true`) and logs at `Error`, because a cache outage must not disable every gated path platform-wide. Packet 9 shipped the table, the policies, the overlay and the cache family, and no writer. The writer ships with P03-9 Step 1: a service entered with an operator admission for the Platform permission `platform.killswitch.write` ([ADR-0101 § 13](decisions/0101-platform-operator-authority.md)), which records a MUST row on the same transaction and drops the overlay cache entry after the commit; see the [killswitch runbook](runbooks/killswitch.md). Per [ADR-0045 § 5 and Amendment 1](decisions/0045-entitlement-and-feature-flag-socket.md). | | **Soft vs Hard Limit** | A `LimitKey` declares `LimitEnforcement = Soft \| Hard`. Hard refuses the operation with `403 ProblemDetails`; Soft surfaces a banner and emits a Hub-side soft-limit alert. The descriptor is declared with each key in Phase 02a Packet 9; the **enforcement** path — the refusal and the `usage.alert.soft_limit_reached` signal — lands in [Phase 02c](roadmap/phase-02c-hub-foundation.md) with `IUsageReporter` and `POST /api/v1/usage/report`, and each individual gate ships with the feature it gates rather than speculatively ([ADR-0045 § 6](decisions/0045-entitlement-and-feature-flag-socket.md)). | ## Search @@ -479,7 +484,7 @@ and recurrence definitions remain empty. | **Integration-event subscription** | One explicitly identified consumer reaction, independent of handler class or assembly. Its stable `{module}.{subscription}.v{N}` ID versions deduplication semantics, not event schema or built-in revision. Renaming needs a migration/replay decision; a handler refactor preserves identity. [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#subscriber-acceptance-and-inbox-ownership) owns the exact grammar. | | **Subscription readiness** | Construction-free Pending, Active or IntentionallyUnsubscribed declaration in `OutboxEventRegistry`, the closed resolver of declared concrete contracts, compatible aliases and retired identities. Any required Pending subscription holds its contract/aliases before acquisition and validation. Active requires a real registered handler; intentional absence is explicit, never inferred from zero discovered handlers. Accepted P02b-2 policy under [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md). | | **Outbox lease** | Paired `locked_by` / `locked_until` fields; the former holds a fresh canonical UUID acquisition token, the latter a database-time expiry. Every transition checks both current token and unexpired lease. Recovery replaces expired ownership before another transition. Stable worker identity confers no ownership. | -| **Dead letter** | Explicit completed terminal state after invalid data or exhausted attempts, distinct from a terminal request or delayed availability. On the producer row, `terminal_reason` requests terminalization and excludes normal publication; only `dead_lettered_at` records completed terminal state. Producer terminal state retains its envelope and commits with MUST audit; subscriber terminal state belongs to its independent delivery ledger and never completes its inbox. P02b-3 Step 4 implements targeted internal subscriber replay; operator routes/permissions and producer reset/replay are separately owned by Phase 03. See [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#producer-dispatch-and-recovery). | +| **Dead letter** | Explicit completed terminal state after invalid data or exhausted attempts, distinct from a terminal request or delayed availability. On the producer row, `terminal_reason` requests terminalization and excludes normal publication; only `dead_lettered_at` records completed terminal state. Producer terminal state retains its envelope and commits with MUST audit; subscriber terminal state belongs to its independent delivery ledger and never completes its inbox. An operator can inspect a dead letter's metadata, replay one dead-lettered subscriber delivery and reset one retry-exhausted producer row, each under a [fence](#operator-recovery) ([ADR-0103](decisions/0103-operator-recovery-of-asynchronous-work.md)). See [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#producer-dispatch-and-recovery). | | **`EventTerminalTransition`** | Restricted immutable witness minted only from the successful fenced terminal UPDATE result in its live transaction. It binds actual row identity, acquisition and terminal values to `WriteEventTerminalAsync`; substituting draft tenant/org/event or transaction requires rollback of state and audit. Producer fifth seam implemented in P02b-2 Step 2, with both independent review rounds complete; P02b-3 Step 4 adds the subscriber tuple witness and terminal writer using a validated attempt trace without causal-envelope/payload access. | | **`DeploymentMode`** | Enum (`Development \| SaaS \| Dedicated \| SelfHostedOnline \| SelfHostedAirGapped`) read at the composition root to select provider implementations. Modules never read this enum. | diff --git a/docs/modules/audit/audit.md b/docs/modules/audit/audit.md index 3171cfdc6..4792f4ebd 100644 --- a/docs/modules/audit/audit.md +++ b/docs/modules/audit/audit.md @@ -8,9 +8,12 @@ adds the confined terminal-audit seam in P02b-2, not an Audit-module operation. `platform.outbox.dead_letter` and P02b-3's `platform.delivery.dead_letter` belong to [Tenancy's off-path matrix](../tenancy/audit.md). P02b-2 Step 2 implements the producer writer, with both review rounds complete; P02b-3 Step 4 implements -the subscriber writer with both review rounds complete. Phase 03 owns privileged -erasure execution and its bounded -caller contract; Phase 11 owns retention purge. +the subscriber writer with both review rounds complete. P03-9 Step 4 adds the +operator's fenced recovery writer, `platform.delivery.replay` and +`platform.delivery.reset`, on the same off-path matrix +([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Phase 03 owns +privileged erasure execution and its bounded caller contract; Phase 11 owns retention +purge. **The module that owns the log is audited like any other.** Reading someone's audit trail is itself a sensitive read; exporting it produces a copy that outlives the diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index e14a433d2..8e363234a 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -74,15 +74,25 @@ serving only anonymous reads, requires both runtime configuration keys and the matching installed authority. Startup qualification rejects missing, unavailable or mismatched registration before accepting HTTP requests. Direct `dotnet run` reads process/.NET configuration, not the root `.env`. Restore the intended -configuration when it differs from the selected database; an issuer rebind remains -P03-9/G13 and is not an automatic repair. +configuration when it differs from the selected database; an issuer change is never an +automatic repair. It is the controlled rebind of +[ADR-0104](../../decisions/0104-controlled-issuer-rebind.md), an offline tool on a +confined sixth database role ([runbook](../../runbooks/identity-issuer-rebind.md)): +it proves each Active person's subject is still reported by the new realm and no +closed person's key reappears, preserves `AuthorityId`, keys and actors, and writes an +intent row and a result row with the change. Authority qualification and the +User-creation admission wait for it behind a shared advisory lock and then read the +value it left. The internal binding service uses explicit startup qualification and fresh, physically read-only existing-binding transactions; it never creates a missing binding. Fixed seed adoption separately requires its confined admission port. Real provider/app-role, schema/body/ACL/caller and physical outcome controls are -implemented. The directory contract appears below; closure, -production first-admin and issuer rebind retain their named later owners. +implemented. The directory contract appears below; closure retains its named later +owner. Production first-admin, Role-template initialization +and recovery are the operator acts of +[ADR-0102](../../decisions/0102-production-tenant-onboarding.md) +([runbook](../../runbooks/tenant-onboarding.md)). ### Retained provider-event storage @@ -339,12 +349,19 @@ P03-1 admits only the fixed development-seed capability. in API composition. The external seed/demo owner supplies bounded canonical manifest facts and actual provider-adoption witnesses to the confined Seeder implementation. Email, a realm role or SystemActor alone supplies no admission. -There is no HTTP entry, operator population or general bootstrap bypass. - -Production first-admin/provisioning admission is **P03-9/G13**, before a -production provisioner uses it. Its authority/recovery cannot inherit the seed -capability. Tenancy's current ProvisionTenant remains the ADR-0042 Tenant/default -Organization pair; no cross-module transaction or further exception is admitted. +The seed capability has no HTTP entry, operator population or general bootstrap +bypass. + +Production first-admin, Role-template initialization and recovery are the operator +acts of [ADR-0102](../../decisions/0102-production-tenant-onboarding.md) (P03-9 Step +2): `OperatorInitializeRoleCommand`, `OperatorCreateFirstAdminCommand` and +`OperatorRecoverAdminCommand`. They are admitted per act by the platform operator +gate, run under the `PlatformOperator` authorization source on the application role +and the ordered locks of ADR-0074, and name the person by provider subject through +the confined resolver definer. They cannot inherit the seed capability: neither source +is sufficient for the other's request. Tenancy's ProvisionTenant remains the ADR-0042 +Tenant/default Organization pair; the operator's provisioning is the same handler +class, and no cross-module transaction or further exception is admitted. 1. The external seed owner completes Tenancy acts and ADR-0072 trusted binding adoption, preserving all four actor/provider IDs, credentials and MFA. @@ -752,6 +769,47 @@ entered on the re-authentication form. with unchanged provenance ([Security § Federation host binding](../../standards/11-security.md#federation-host-binding)). +### Operator federation steps (P03-9 Step 5) + +[ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md) and +[Amendment 11](../../decisions/0099-confined-tenant-federation.md) give the platform +operator a report, a remove and a disable of the identity-provider brokers a tenant's +federation left orphaned, unreadable or nonconforming. The operator's procedure is the +[federation operator runbook](../../runbooks/federation-operator.md); this section is +the module's side of it. + +- **Two ports, one adapter.** `IFederationOperator` (SharedKernel) sits beside + `IFederationProvider` and is held only by `FederationBrokerOperations` (Identity + Infrastructure) and the operator half of the Keycloak adapter, never by the tenant + runner. The operator adapter is a second instance with its own resilience pipeline, + on the same confined client, so a sweep cannot starve a tenant's calls. Its + fail-closed default reports every call unavailable until the federation admin client + is configured. +- **One service, three acts.** `FederationBrokerOperations` implements + `IFederationBrokerOperations` (SharedKernel). It consumes the operator's + `PlatformAdmission` in the platform scope, reads the realm page first and the + connection rows second, and classifies each marked broker as `orphan`, + `unreadable_owned` or `nonconforming`. A broker whose marker does not parse strictly + to a tenant and connection whose derived alias it is, or whose marker disagrees with + its row about the tenant, is counted and never named. +- **Rows read.** `learnstack_platform` holds `SELECT` of `id`, `tenant_id`, `state` and + `deleted_at` on `federation_connections` and nothing more + ([Standard 05](../../standards/05-database.md#federation-operator-projection)); the + Identity migration `20261120160000_grant_platform_federation_projection` carries it. + The one statement that reads the table as the platform role reads by primary key and + sees tombstones, which `FederationConnectionReads.Live` hides from the tenant paths. +- **Two rows around the provider call.** A remove or a disable writes an intent row on + `platform.federation.remove_attempt` or `platform.federation.disable_attempt` at the + platform scope handle's checkpoint + ([ADR-0044 Amendment 18](../../decisions/0044-audit-write-path.md)), commits it, calls + the provider, and writes the completion row on `platform.federation.remove` or + `platform.federation.disable`. Both name the tenant the owner marker names and carry + closed tokens only. The audit matrix is in + [Tenancy's audit.md](../tenancy/audit.md), whose catalogue holds these slugs. +- **No realm user is read or removed.** A remove deletes the broker and the provider + deletes its federated links; the account review is the realm administrator's, by + runbook. + ## Entity-relationship diagram ```mermaid @@ -884,13 +942,15 @@ permission cache/session grant cannot replace a fresh check. ## Risks and open questions -Branch-specific Role configuration reopens ADR-0073. Accepted ADR-0076/0077 own -live delegation, default deny/revocation, reader handoff and trusted evidence. -Those mechanisms and the bounded scope transitions/DTOs are implemented, as are the -verified invitation writers of [ADR-0093](../../decisions/0093-verified-invitation-acceptance-and-handoff.md); -[Phase 03 Status](../../roadmap/phase-03-identity-admin.md) owns qualification. -P03-5 dynamic values, P03-9 production first-admin/recovery and P03-10 -closure/locators remain named later writers, not implicit foundation authority. +Branch-specific Role configuration reopens ADR-0073. Accepted ADR-0076/0077 own live +delegation, default deny/revocation, reader handoff and trusted evidence. Those +mechanisms and the bounded scope transitions/DTOs are implemented, as are the verified +invitation writers of +[ADR-0093](../../decisions/0093-verified-invitation-acceptance-and-handoff.md); +[Phase 03 Status](../../roadmap/phase-03-identity-admin.md) owns qualification. P03-5 +dynamic values and P03-10 closure/locators remain named later writers, not implicit +foundation authority; P03-9's production first-admin and recovery are the operator acts +above. | Subject/control | Current state | Owner / scope | |---|---|---| diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index 3a991796c..5086243d7 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -28,10 +28,14 @@ the request exists, and off-path events register by slug when their writer lands | Resource | Operation | Class | Why | |---|---|---|---| | User/global immutable subject | `identity.user.create` `(off-path)` | **MUST** (`security-event`) | ADR-0072's confined creation/adoption owner and central non-success reconciliation; success shares the User transaction. Exact global witness, source and retention contract stays there. | -| Role including grants | `identity.role.initialize` | **MUST** (`security-event`) | `InitializeSeedRole`; one Role transaction, with contained grants. | +| Role including grants | `identity.role.initialize` | **MUST** (`security-event`) | `InitializeSeedRole` and the operator's `OperatorInitializeRoleCommand` share this slug; one Role transaction, with contained grants. | | Membership including Profile/Assignments | `identity.membership.create_first_seed_admin` | **MUST** (`security-event`) | `CreateFirstSeedAdminMembership`; one Membership transaction. | | Membership including Profile/Assignments | `identity.membership.create_seed` | **MUST** (`security-event`) | `CreateSeedMembership`; one Membership transaction. | +| Membership including Profile/Assignments | `identity.membership.create_first_admin` | **MUST** (`security-event`) | `OperatorCreateFirstAdminCommand`, the operator's production first administrator ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)); one Membership transaction on the operator source, `metadata.operator` and the reason slug on the row, refused once the tenant has had any member. | +| Membership including Profile/Assignments | `identity.membership.recover_admin` | **MUST** (`security-event`) | `OperatorRecoverAdminCommand`, the operator's replacement administrator for a tenant with none active; one Membership transaction on the operator source, refused while any administrator is active. | | MembershipProfile, captured under Membership | `identity.membership_profile.set_seed_profile` | **MUST** (`update`) | `SetSeedMembershipProfile`; same Membership transaction. The slug matches the gated sub-resource while the row's subject remains its owning aggregate. | +| Identity authority | `identity.authority.rebind_attempt` `(off-path)` | **MUST** (`security-event`) | The controlled issuer rebind's intent row ([ADR-0104](../../decisions/0104-controlled-issuer-rebind.md)): committed on the offline tool's own short transaction, by the confined `learnstack_identity_rebind` role, before the main transaction begins, so an aborted attempt is on record. Platform sentinel tenant, outcome `indeterminate`, no actor, `metadata.operator` with the ticket. Written through the witness-bound `WriteIdentityRebindIntentAsync`, never the pipeline. | +| Identity authority | `identity.authority.rebind` `(off-path)` | **MUST** (`security-event`) | The rebind's result row: written on the same transaction as the one-column issuer change, so it commits with the change or not at all, and a forced audit failure rolls the change back. Outcome `success`; the old and new issuer are in `before_state` and `after_state`, and `metadata` holds the operator attribution and the continuity counts, with no subject. Written through the witness-bound `WriteIdentityRebindResultAsync`. | | Authorization decision | `identity.authorization.deny` `(off-path)` | **MUST** (`security-event`) | Central HTTP/application/resource denial owner; one decided invocation event, separate from ordinary plural resource intents. No tenant override or host suppression budget. | | Membership directory | `identity.membership.list` | **MUST** (`read-sensitive`) | Internal `ListMembershipsQuery` under existing Tenant `identity.membership.admin`; ordinary ReadWrite owner commits its row before disclosure. No HTTP activation follows from its catalogue entry. | | Role including grants | `identity.role.change_grants` | **MUST** (`security-event`) | `ChangeRoleGrantsCommand`; one Role root and contained grant diff, expected row version and fresh post-lock authority recheck; success/audit share the transaction. | @@ -271,3 +275,13 @@ baseline provider-credential-rotation row covers `rotate_secret`. no personal data. `GetPublicSignInQuery` is an explicit Off public read: it is anonymous and returns only the host tenant's Active alias and display name ([Standard 18](../../standards/18-audit-coverage.md)). + +The platform operator's report, remove and disable of orphaned or broken brokers +([ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md)) are not +Identity operations and are not in this table. They run at the platform scope, outside +the request pipeline, and write the off-path slugs `platform.federation.report`, +`platform.federation.remove_attempt`, `platform.federation.remove`, +`platform.federation.disable_attempt` and `platform.federation.disable`, which +[Tenancy's audit matrix](../tenancy/audit.md) classifies and Tenancy's catalogue source +registers. Their rows name the tenant the owner marker names and entity +`FederationConnection`. diff --git a/docs/modules/identity/permissions.md b/docs/modules/identity/permissions.md index 93caa4583..92f1b82f0 100644 --- a/docs/modules/identity/permissions.md +++ b/docs/modules/identity/permissions.md @@ -26,6 +26,10 @@ permission admission. An attribute, realm role or SystemActor value grants no ro | `CreateSeedMembership` | Tenant or Organization `identity.membership.admin` | Exact declared learner tuple/target scope; no arbitrary actor/tenant/org/Role | | `SetSeedMembershipProfile` | Tenant or Organization `identity.membership_profile.write` | Declared Membership and bounded contextual fields, through the Membership root | | `InitializeSeedRole` | Tenant `identity.role.admin` | Exact tenant/template/v1 manifest, including Organization-capability templates; one Role root | +| `OperatorInitializeRoleCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | One finite template of the target tenant, before any Membership exists; idempotent on the operator's Role id ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) | +| `OperatorCreateFirstAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | The first tenant-wide administrator of a tenant with no Membership history; the person is named by provider subject and must be an Active, bootstrapped User | +| `OperatorRecoverAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | A replacement administrator while no Active tenant-wide administrator Membership exists; the last-administrator guard is the database's and is unchanged | +| `IdentityIssuerRebind` (an offline tool, not a command or a route) | Platform `platform.identity_authority.admin`, `PlatformOperator` token | The operator's per-act grant for the rebind operation only, checked by the operator gate in the tool; the write itself runs on the confined `learnstack_identity_rebind` role, with no tenant context ([ADR-0104](../../decisions/0104-controlled-issuer-rebind.md)) | Scope selection derives from immutable target Membership/validated declaration, never a claimed scope string. Finite metadata alternatives count the exact five diff --git a/docs/modules/identity/providers.md b/docs/modules/identity/providers.md index 1c5fdd426..c761da53c 100644 --- a/docs/modules/identity/providers.md +++ b/docs/modules/identity/providers.md @@ -57,12 +57,12 @@ specification. | Boundary | Contract | |---|---| -| Ports | SharedKernel `IFederationProvider` and `IFederationEgressFetcher`; held only by `FederationOperationRunner` | +| Ports | SharedKernel `IFederationProvider` and `IFederationEgressFetcher`, held only by `FederationOperationRunner`; and `IFederationOperator`, the platform operator's port ([Operator access](#operator-access)), held only by its owner and the adapter | | Adapter | Internal sealed `KeycloakFederationProvider` in `LearnStack.Infrastructure.Identity.Federation`; direct HTTP, no SDK | | Fetcher | Internal sealed `FederationEgressFetcher` in the same namespace; the only fetcher of a tenant-supplied URL | | Selection | API `FederationComposition` replaces the fail-closed defaults only when `Federation:ClientSecret` is configured; `FederationAdapterFactory` is the only entry. The choice is made when the port is first resolved (it follows `ISecretProvider`), so an empty or invalid `Authentication:Tenant:Issuer` with the secret present refuses at that first resolution, not at host startup | | Credentials | Client `learnstack-federation-admin`; secret through `ISecretProvider` key `Federation:ClientSecret`; a fresh client-credentials token per port call | -| Resilience | `IProviderResilience`, configuration `Resilience:federation`: retry disabled, a 2.5 s timeout, circuit breaker on, a bulkhead of exactly 4 with no queue; these are fixed values, and composition refuses any other value at startup. The enabled breaker's parameters are bounded: failure ratio in (0, 1], minimum throughput 2 to 100, sampling duration 1 to 60 s, break duration 1 to 300 s (defaults 0.5, 10, 30 s, 30 s); a value outside a range refuses at startup | +| Resilience | `IProviderResilience` for the tenant calls and a second instance of the fixed shape, `IProviderResilience`, for the operator's, so a sweep cannot starve a tenant; configuration `Resilience:federation`: retry disabled, a 2.5 s timeout, circuit breaker on, a bulkhead of exactly 4 with no queue; these are fixed values, and composition refuses any other value at startup. The enabled breaker's parameters are bounded: failure ratio in (0, 1], minimum throughput 2 to 100, sampling duration 1 to 60 s, break duration 1 to 300 s (defaults 0.5, 10, 30 s, 30 s); a value outside a range refuses at startup | | Failures | Transport faults, 5xx and 429 are `FederationProviderException` (a `ProviderException`) inside the pipeline and leave as `Unavailable`; no provider text crosses the port | ### Admitted calls @@ -77,6 +77,8 @@ The adapter builds every route in `KeycloakFederationRoutes`, and only these: | `PUT admin/realms/learnstack/identity-provider/instances/{alias}` | Full-state replace of an owned broker. Refused without a call when it would change the stored issuer or SAML entity identifier, or, without a fresh secret, the token endpoint, client identifier or client authentication ([ADR-0099 Amendment 5](../../decisions/0099-confined-tenant-federation.md#amendment-5--step-3-review-egress-adapter-and-linking-decisions-2026-11-14)) | | `DELETE admin/realms/learnstack/identity-provider/instances/{alias}` | Delete of an owned broker; an absent alias is already deleted | | `GET admin/realms/learnstack/identity-provider/instances/{alias}/mappers` | Mapper count for the readback; any mapper is drift | +| `GET admin/realms/learnstack/identity-provider/instances?first={n}&max={m}&briefRepresentation=false` | The operator's bounded page of the realm's listing ([Operator access](#operator-access)); no other query member | +| `GET admin/realms/learnstack/identity-provider/instances/{alias}` (operator) | The operator's read of one derived alias before it knows whose it is; the tenant adapter reads only its own owner's alias | The `{alias}` is only `lsf-` and the connection identifier's 32 lowercase hexadecimal characters, from `FederationBrokerOwner`. No other alias, user, flow, realm, client or @@ -88,6 +90,40 @@ records the decision). The pinned 26.7.5 parser was observed to return `validateSignature=true` for metadata whose `WantAuthnRequestsSigned` is false; the adapter never forwards its output either way. +### Operator access + +[ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md) and +Amendment 11 and 12 give the platform operator four calls on this realm through the +same confined client, `manage-identity-providers`, and no wider role: a **report** (the +listing joined to the registry), an **inspection** of one alias, a **remove** of an +owner-marked broker that the registry no longer holds live or that does not read +(Amendment 12 item 1), and a **disable** of an owner-marked broker at the provider +only. + +- The operator holds `IFederationOperator`, a port beside `IFederationProvider` that + the tenant runner never holds; its adapter is the same internal sealed class with its + own resilience pipeline. +- A broker is the platform's to touch only when its marker parses strictly + (`lsf-` alias, `{tenant:D}:{connection:D}`) **and** the alias is the connection's + derived one. An unmarked instance, a foreign marker and an alias that is not + LearnStack's are counted and never named. +- A remove deletes by alias and confirms the alias is gone. The provider deletes the + federated links of that broker with it and keeps the accounts; the runbook owes an + account review. A live row refuses it for a broker that reads and not for one that + does not, because the tenant's own Delete cannot reach an unreadable broker. +- A disable is the one provider write that is not the fixed profile: the broker can be + unreadable (that is why it is disabled rather than rewritten), so the adapter reads + the raw representation, sets `enabled=false` and puts it back with the secret mask + the provider returned. Nothing else in the representation changes, and the pinned + provider keeps the stored secret when it reads its own mask back. +- A report is one page, no larger than the API's cursor limit, and its cursor is the + provider offset the next page starts at. A listing the provider cannot answer reports + `unavailable`, never an empty realm, and a mapper count that could not be read is + counted as unread, never as zero. +- Federation destinations, secrets, display names, issuers and configuration values + never cross the operator port: facts are an alias, an owner, readable, conforming, + enabled, protocol and a mapper count. + ### Ownership and readback - Every write carries `config.learnstackOwner` = `{tenantId}:{connectionId}`. The diff --git a/docs/modules/tenancy/README.md b/docs/modules/tenancy/README.md index ab515fa4b..684ea4dbe 100644 --- a/docs/modules/tenancy/README.md +++ b/docs/modules/tenancy/README.md @@ -47,9 +47,9 @@ Tenancy owns **who a request belongs to** and nothing about what they do with it - `platform_killswitches` — one platform-wide switch per key. Platform-scoped and tenant-blind: the only table in the schema for which "no tenant context implies zero rows" is deliberately false, because a switch the application role cannot read is one - that fails open. Shipped read-only in Packet 9 — every toggle runs inside - `EnterPlatformAdminScope`, so [Phase 03](../../roadmap/phase-03-identity-admin.md) - owns the writer. + that fails open. Packet 9 shipped it read-only; its one writer is `KillswitchToggle` + (P03-9 Step 1, [ADR-0101 § 13](../../decisions/0101-platform-operator-authority.md), + [runbook](../../runbooks/killswitch.md)). **Two read paths it owns, over tables it does not read directly:** @@ -616,6 +616,15 @@ inserts the default `organizations` row, updates `tenants.default_organization_id`, and returns; the behavior completes the scope, which commits. One transaction, one connection, one commit point. +**The operator's production provisioning** +([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) is +`OperatorProvisionTenantCommand`, handled by this same class. It carries no +`IProvisionsTenant` announcement: the operator act executor installs a resolved ambient +context for the new tenant's id, which the ordinary transaction behavior announces, and +the self-keyed insert policy admits it the same way. The operator's host mapping +(`OperatorMapHostCommand`) shares `MapHostToTenantCommandHandler` likewise. Both are +idempotent on the operator's identifiers and refuse a repeat that changes a value. + **The handler opens nothing and announces nothing.** Both belong to `TransactionBehavior`, and the distinction is not stylistic. A `BeginTransactionAsync` from inside a handler is a *joiner* — [ADR-0040](../../decisions/0040-ambient-unit-of-work.md) diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index b29617d8b..8df020b50 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -68,6 +68,13 @@ under [ADR-0033](../../decisions/0033-audit-durability-model.md). The branding w shares that guarantee; a failed MUST audit rolls its setting write back too. +**Operator acts share the slugs.** The operator's production provisioning and host +mapping ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)) register the +same slugs as the seed commands, in the same classes, written on the act's own +transaction under the target tenant with `actor_user_id` NULL, the closed reason slugs +`tenant_provision` and `host_map`, and `metadata.operator`. Provisioning writes the two +rows below, and a refused act writes the ordinary `failed` row. + **One command, two rows.** An intent is parked per audited `(resource, operation)` and not per request ([ADR-0044 § 3](../../decisions/0044-audit-write-path.md)), so `ProvisionTenantCommand` declares `tenancy.tenant.create` **and** @@ -139,6 +146,14 @@ unmarked row is one a shipped command already raises. |---|---|---|---| | `outbox_messages` | `platform.outbox.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-2 Step 2's consequential BYPASSRLS terminal transition; state and row commit together through the row-bound fifth audit seam, with stored tenant/org/event identity and SystemActor ([ADR-0046](../../decisions/0046-durable-event-delivery-and-recovery.md)) | | delivery ledger | `platform.delivery.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-3 Step 4's subscriber terminal writer binds stored tenant/org/event/subscription, acquisition token, reason and attempts to the actual fenced transition; ledger and MUST audit commit together through the same restricted fifth seam. It receives no causal-envelope or payload SELECT grant | +| outbox, delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `delivery_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the row does not say which list was read; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | +| delivery ledger | `platform.delivery.replay` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered subscriber delivery. Written through the row-bound operator-recovery seam on the outbox-role transaction that makes the change, under the real event tenant, with no actor, the closed reason `delivery_replay`, `metadata.operator`, and `metadata.fence` holding the fence before and after; a forced audit failure rolls the reset back and the request answers `503` with no state change. A stale fence or a refused state writes no row ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | +| `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | +| `federation_connections` and the realm's identity-provider instances | `platform.federation.report` `(off-path)` | **MUST** (`security-event`) | An operator's report of the brokers that are orphaned, unreadable or nonconforming ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `federation_report` is this slug's, with the operator attribution and ticket in `metadata.operator`; the scope reads and changes nothing, so it writes no result row, and it does not say which page was read | +| `federation_connections` | `platform.federation.remove_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's removal of an orphaned or unreadable owned broker, written at the platform scope handle's checkpoint and committed before the provider call ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 11). Outcome `indeterminate`, under the tenant the owner marker names (never the platform sentinel, even when no `tenants` row exists), no actor, the closed reason `federation_remove`, the operator attribution in `metadata.operator`, no ticket because a tenant can read the row, and `before_state` holding the broker's classes and the connection row's state; the entity is the connection | +| `federation_connections` | `platform.federation.remove` `(off-path)` | **MUST** (`security-event`) | The completion row of that removal, written through the witness-bound result method on the work transaction that follows the checkpoint, in the same shape with the audit outcome `success`, which says the act ran to its end, and `after_state` holding the closed `outcome` that says how the provider call ended (`applied`, `already_applied`, `refused`, `not_owned`, `unavailable` or `uncertain`), a `cause` of `live_connection` when a live row refused the delete after the intent, and `accountReviewOwed`, because the provider deletes the federated links with a broker. It is written on a bounded budget detached from the request ([ADR-0099 Amendment 12](../../decisions/0099-confined-tenant-federation.md) item 3). A lost completion leaves the intent row alone, which the next report resolves | +| `federation_connections` | `platform.federation.disable_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's disable of a nonconforming or unreadable owned broker, in the shape of the removal's intent under the closed reason `federation_disable` | +| `federation_connections` | `platform.federation.disable` `(off-path)` | **MUST** (`security-event`) | The completion row of that disable, in the shape of the removal's completion; the provider is changed and the tenant's row is left to its next readback ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10 item 4) | | `background_jobs` | `platform.job.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-4 Step 5 binds stored tenant/org/job/definition/attempt and the actual old acquisition token to the fenced terminal transition. The sixth audit seam writes on that same transaction; audit failure rolls back terminal state. Validation and both review dispositions belong to its delivery record ([ADR-0047](../../decisions/0047-transactional-background-job-runtime.md)) | | `Tenant` | `tenancy.tenant.create` | **MUST** | The root of a customer's data; its existence is a contractual fact | | `Tenant` | `tenancy.tenant.change_status` `(planned)` | **MUST** | Suspension withdraws access; an operator must be able to say who and when | @@ -159,14 +174,14 @@ unmarked row is one a shipped command already raises. | `TenantSetting` | `tenancy.setting.soft_delete` `(planned)` | **MUST** | Removing a setting is a change to it, so the same baseline row covers it — and `ux_tenant_settings_tenant_id_organization_id_key` is partial on `deleted_at IS NULL`, so the key becomes free for a successor | | `Tenant` | `tenancy.locale.write` | SHOULD | Configuration; contained TenantLocale changes are captured with their owning Tenant root | | `TenantFeatureFlag` | `tenancy.feature_flag.write` `(planned)` | **MUST** | "Feature flag toggled" is on the same baseline row, and [Feature Flags § Audit](../../architecture/21-feature-flags.md) classes both flag surfaces as security events | -| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` `(planned)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`, which is what gives the row a real actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships the table, its policies and the read path and **no writer**: nothing can enter that scope while `DenyAllPlatformAdminGate` is the registered gate, so [Phase 03](../../roadmap/phase-03-identity-admin.md) owns the toggle, its permission and its runbook ([ADR-0045 Amendment 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) | -| `platform_entitlement_cache` | `tenancy.entitlement.refresh` `(planned)` `(off-path)` | **MUST** | Changes what the tenant may do; written only by `IEntitlementProvider.RefreshAsync`, a port method driven by the Hub over `/api/internal/*` ([ADR-0045 § 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) and never by a MediatR request, so there is no request type to key a catalogue entry on. **Both markers**, for the reason `tenancy.killswitch.toggle` carries both: Packet 9 ships `NullEntitlementProvider`, which answers from constants and touches no table, and the `HubEntitlementProvider` that performs a real refresh lands in [Phase 02c](../../roadmap/phase-02c-hub-foundation.md) ([ADR-0045 § 6](../../decisions/0045-entitlement-and-feature-flag-socket.md)) — so there is no writer here yet either | +| `platform_killswitches` | `tenancy.killswitch.toggle` `(off-path)` | **MUST** | A platform-wide flip that disables a capability for every tenant at once. It is not a `tenant_feature_flags` row — that table's foreign key to `tenants` is one the platform sentinel cannot satisfy, so killswitches ship as their own platform-scoped table ([ADR-0045 § 5](../../decisions/0045-entitlement-and-feature-flag-socket.md)). Every write goes through `EnterPlatformAdminScope(reason)`; the operator is recorded in `metadata.operator` ([ADR-0101 § 9](../../decisions/0101-platform-operator-authority.md)) because the Packet 9 scope writes a null actor ([Feature Flags § Killswitch Pattern](../../architecture/21-feature-flags.md)); the scope is entered by a service method and not by a MediatR request, so there is no request type to key a catalogue entry on. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) shipped the table, its policies and the read path with no writer; P03-9 Step 1 ships the writer, `KillswitchToggle`, behind the operator gate with the `platform.killswitch.write` grant ([ADR-0101 § 13](../../decisions/0101-platform-operator-authority.md), [runbook](../../runbooks/killswitch.md)). The row is written on the work transaction through the witness-bound result method, so it commits with the flip or not at all | +| `platform_entitlement_cache` | `tenancy.entitlement.refresh` `(planned)` `(off-path)` | **MUST** | Changes what the tenant may do; written only by `IEntitlementProvider.RefreshAsync`, a port method driven by the Hub over `/api/internal/*` ([ADR-0045 § 1](../../decisions/0045-entitlement-and-feature-flag-socket.md)) and never by a MediatR request, so there is no request type to key a catalogue entry on. **Both markers**, as `tenancy.killswitch.toggle` carried both until its writer shipped: Packet 9 ships `NullEntitlementProvider`, which answers from constants and touches no table, and the `HubEntitlementProvider` that performs a real refresh lands in [Phase 02c](../../roadmap/phase-02c-hub-foundation.md) ([ADR-0045 § 6](../../decisions/0045-entitlement-and-feature-flag-socket.md)) — so there is no writer here yet either | | `platform_host_to_tenant` | `tenancy.hostmapping.write` | **MUST** | The resolution index — the row that decides whose data an anonymous request sees | | `platform_host_to_tenant` | `tenancy.hostmapping.delete` `(planned)` | **MUST** | The same row removed. The table carries no `deleted_at`, so the delete is a row gone and a host that resolves to nobody | | `TenantAssertion` | `tenancy.tenant_assertion.reject` `(off-path)` | **MUST** for admitted events (`security-event`) | A validated header/claim mismatch with an independently defended host tenant is recorded under that host tenant, never the asserted tenant or sentinel; row 14 is counted only. [ADR-0065](../../decisions/0065-bounded-tenant-assertion-diagnostics.md) admits 600 authenticated standalone write attempts per host tenant per API instance per first-request-anchored monotonic minute, shared across scoped recorders, actors, sources and dimensions. Failed writes consume permits; later occurrences make no audit-store call and retain their refusal, count and exactly one attributed Warning (4006 replaces normal 4001). An attacker can exhaust the allowance, so later actors lose durable evidence; aggregate log volume remains unbounded. Admitted events retain MUST failure/health behavior, tenant-wide organization scope, exact actor/correlation and trusted organization in metadata. No tenant `AuditConfig` override or independent tenant-registry cap exists. General mutation MUST durability is unchanged. Packet 9 owns the recorder/decorator path; P02b-5 Steps 3–4 implement JWT attribution and HTTP activation under ADR-0064. ADR-0065 acceptance precedes the dependent budget implementation; the [merge closeout](../../roadmap/phase-02b-delivery-log.md#p02b-5-merge-and-closeout-2026-10-20) owns its final delivery status | | `TenantAssertion` | `tenancy.tenant_assertion.anonymous_burst` `(off-path)` | **MUST** (`security-event`) | The anonymous half of the same detector, written once per `(resolved tenant, dimension, window)` when the mismatch counter crosses its threshold. An anonymous mismatch is not itself an audited operation; the burst is — the precedent the baseline's "login failure burst" already sets ([ADR-0036 Amendment 7](../../decisions/0036-tenant-resolution-trusted-inputs.md)). Same writer, and `(off-path)` for the same reason. The window is **in-process** and never `ICacheService` — a cache outage must not decide whether a MUST-class security event is recorded — so the effective threshold is per instance, which errs toward more auditing. `Tenancy:AssertionBurst` sets it; the defaults are ten occurrences in five minutes | | Confirmed claim-context assertion | `tenancy.assertion.reject_claim_context` `(off-path)` | **MUST** (`security-event`) | A header conflicting with actual successful ClaimAndMembership resolution uses the confirmed tenant/actor, fixed dimension/reason and membership-confirmed source. No asserted UUID or host allowance. The production claim-context recorder and central evidence owner implement this path; [Phase 03](../../roadmap/phase-03-identity-admin.md) owns qualification. | -| any | `platform.admin_scope.enter` `(off-path)` | **MUST** (`security-event`) | Cross-tenant access is the one read worth a row; [Audit Coverage](../../standards/18-audit-coverage.md) puts every platform-bypass invocation on `security-event`. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships it: an admitted `PlatformAdminScope.EnterAsync` writes the row through `IAuditStore.WritePlatformScopeAsync` on the scope's own platform-role connection, in a transaction of its own that **commits before** the caller's begins — so work that later fails, throws or is abandoned cannot take the record with it — carrying `TenantId.PlatformSentinel` ([ADR-0044 § 1, § 10](../../decisions/0044-audit-write-path.md)). An entry the catalogue cannot classify, or whose row cannot be written, is **refused** — no transaction is handed out for it. The `Warning` log line stays beside the row, carrying its id, as the real-time signal the row is not. `EnterAsync` is a service method and not a MediatR request, and the catalogue is keyed by request type — so its catalogue entry is registered by slug rather than by request type. Its module segment is `platform` for the same reason: the scope belongs to no module's request path. The permission gate denies before opening a connection; those denied attempts write no entry row. Phase 03 must decide denied-entry evidence before its first privileged consumer | +| any | `platform.admin_scope.enter` `(off-path)` | **MUST** (`security-event`) | Cross-tenant access is the one read worth a row; [Audit Coverage](../../standards/18-audit-coverage.md) puts every platform-bypass invocation on `security-event`. [Packet 9](../../roadmap/phase-02a-kernel-tenancy.md) ships it: an admitted `PlatformAdminScope.EnterAsync` writes the row through `IAuditStore.WritePlatformScopeAsync` on the scope's own platform-role connection, in a transaction of its own that **commits before** the caller's begins — so work that later fails, throws or is abandoned cannot take the record with it — carrying `TenantId.PlatformSentinel` ([ADR-0044 § 1, § 10](../../decisions/0044-audit-write-path.md)). An entry the catalogue cannot classify, or whose row cannot be written, is **refused** — no transaction is handed out for it. The `Warning` log line stays beside the row, carrying its id, as the real-time signal the row is not. `EnterAsync` is a service method and not a MediatR request, and the catalogue is keyed by request type — so its catalogue entry is registered by slug rather than by request type. Its module segment is `platform` for the same reason: the scope belongs to no module's request path. The permission gate denies before opening a connection; those denied attempts write no entry row. [ADR-0101 § 11](../../decisions/0101-platform-operator-authority.md) decides denied-entry evidence: a counter and a Warning log, no durable row | A feature flag that gates a **billed** capability is not a `tenant_feature_flags` row at all. It is plan-level, it is written only by diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index caa988ef9..7ea734c81 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -110,6 +110,33 @@ authority. Their named Phase 02c/P03-9 surfaces retain separate admission decisi [Database Standards § GRANT matrix](../../standards/05-database.md) records that the widening it needs is an ADR's to make, not a migration's. +The Platform catalogue ([ADR-0101](../../decisions/0101-platform-operator-authority.md)) +is separate and never assignable to a Role. Tenancy owns six keys in it today. +`platform.killswitch.write` authorizes the operator surface to toggle +`platform_killswitches`. `platform.tenant.write` authorizes the operator's production +tenant provisioning and host mapping +([ADR-0102](../../decisions/0102-production-tenant-onboarding.md)): +`OperatorProvisionTenantCommand` and `OperatorMapHostCommand` are `FiniteTrusted` +operations whose one source is `PlatformOperator`, run on the application role under the +target tenant's ordinary announcement, and share their audit slugs +(`tenancy.tenant.create`, `tenancy.organization.create`, `tenancy.hostmapping.write`) +with the seed commands they parallel. `platform.delivery.read` and +`platform.delivery.write` authorize the operator's inspection of dead-lettered +asynchronous work and its two fenced recovery transitions +([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)): they run in +the platform scope and on the dispatcher's outbox role, not through the pipeline, and +write the off-path slugs `platform.delivery.inspect`, `platform.delivery.replay` and +`platform.delivery.reset` in [Tenancy's audit matrix](audit.md). +`platform.federation.read` and `platform.federation.admin` authorize the operator's +report of orphaned, unreadable and nonconforming identity-provider brokers and its +remove and disable of one +([ADR-0099 Amendment 10](../../decisions/0099-confined-tenant-federation.md), +[runbook](../../runbooks/federation-operator.md)): they run in the platform scope, not +through the pipeline, and write the off-path slugs `platform.federation.report`, +`platform.federation.remove_attempt`, `platform.federation.remove`, +`platform.federation.disable_attempt` and `platform.federation.disable`. Operators hold +the keys by configuration ([Standard 19](../../standards/19-permissions.md)). + ## Bounded human administration contract Internal human requests carry separate Protected policies and audit bindings. diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md index 2adb91db0..1662a5004 100644 --- a/docs/roadmap/phase-03-delivery-log.md +++ b/docs/roadmap/phase-03-delivery-log.md @@ -479,7 +479,7 @@ not acceptance of implementation choices. Navigate by the generated index below. - [P03-7 hosted repeat failure and closed diagnostic correction (2026-11-12)](#p03-7-hosted-repeat-failure-and-closed-diagnostic-correction-2026-11-12) — 56 lines - [P03-7 faulted test-owner lifetime correction (2026-11-12)](#p03-7-faulted-test-owner-lifetime-correction-2026-11-12) — 73 lines - [P03-7 merge and delivery closeout (2026-11-12)](#p03-7-merge-and-delivery-closeout-2026-11-12) — 89 lines -- [P03-8 — Tenant federation](#p03-8--tenant-federation) — 2,331 lines +- [P03-8 — Tenant federation](#p03-8--tenant-federation) — 2,404 lines - [P03-8 proposed tenant federation package (2026-11-13)](#p03-8-proposed-tenant-federation-package-2026-11-13) — 109 lines - [Maintainer decisions recorded 2026-11-13](#maintainer-decisions-recorded-2026-11-13) — 10 lines - [P03-8 proposal review round one and corrections (2026-11-13)](#p03-8-proposal-review-round-one-and-corrections-2026-11-13) — 40 lines @@ -508,6 +508,29 @@ not acceptance of implementation choices. Navigate by the generated index below. - [ADR-0100 maintainer review disposition and acceptance (2026-11-18)](#adr-0100-maintainer-review-disposition-and-acceptance-2026-11-18) — 71 lines - [P03-8 OpenAPI transition implementation and reviews (2026-11-18)](#p03-8-openapi-transition-implementation-and-reviews-2026-11-18) — 54 lines - [P03-8 PR review disposition (2026-11-18)](#p03-8-pr-review-disposition-2026-11-18) — 101 lines + - [P03-8 merge and delivery closeout (2026-11-19)](#p03-8-merge-and-delivery-closeout-2026-11-19) — 73 lines +- [P03-9 — Platform authority and operational recovery](#p03-9--platform-authority-and-operational-recovery) — 1,291 lines + - [P03-9 proposed platform authority and recovery package (2026-11-19)](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19) — 136 lines + - [P03-9 package review dispositions and acceptance (2026-11-19)](#p03-9-package-review-dispositions-and-acceptance-2026-11-19) — 126 lines + - [P03-9 Step 1 — operator authority and killswitch (2026-11-19)](#p03-9-step-1--operator-authority-and-killswitch-2026-11-19) — 108 lines + - [P03-9 Step 1 — review round 1 and its fixes (2026-11-19)](#p03-9-step-1--review-round-1-and-its-fixes-2026-11-19) — 137 lines + - [P03-9 Step 2 — review round 1 and its fixes (2026-11-19)](#p03-9-step-2--review-round-1-and-its-fixes-2026-11-19) — 46 lines + - [P03-9 Step 2 — review round 2 and its fixes (2026-11-19)](#p03-9-step-2--review-round-2-and-its-fixes-2026-11-19) — 35 lines + - [P03-9 Step 3 — controlled issuer rebind (2026-11-20)](#p03-9-step-3--controlled-issuer-rebind-2026-11-20) — 107 lines + - [P03-9 Step 3 — review round 1 and its fixes (2026-11-20)](#p03-9-step-3--review-round-1-and-its-fixes-2026-11-20) — 23 lines + - [P03-9 Step 3 — review round 2 and its fixes (2026-11-20)](#p03-9-step-3--review-round-2-and-its-fixes-2026-11-20) — 70 lines + - [P03-9 Step 4 — operator recovery of asynchronous work (2026-11-20)](#p03-9-step-4--operator-recovery-of-asynchronous-work-2026-11-20) — 59 lines + - [P03-9 Step 4 — review round 1 and its fixes (2026-11-20)](#p03-9-step-4--review-round-1-and-its-fixes-2026-11-20) — 49 lines + - [P03-9 Step 4 — review round 2 and its fixes (2026-11-20)](#p03-9-step-4--review-round-2-and-its-fixes-2026-11-20) — 39 lines + - [P03-9 Step 5 — federation operator steps (2026-11-20)](#p03-9-step-5--federation-operator-steps-2026-11-20) — 71 lines + - [P03-9 Step 5 — review round 1 and its fixes (2026-11-20)](#p03-9-step-5--review-round-1-and-its-fixes-2026-11-20) — 67 lines + - [P03-9 Step 5 — review round 2 and its fixes (2026-11-20)](#p03-9-step-5--review-round-2-and-its-fixes-2026-11-20) — 63 lines + - [P03-9 Step 5 — verification and closeout (2026-11-21)](#p03-9-step-5--verification-and-closeout-2026-11-21) — 33 lines + - [P03-9 Step 5 — hosted CI correction (2026-11-21)](#p03-9-step-5--hosted-ci-correction-2026-11-21) — 23 lines + - [P03-9 Step 5 — hosted CI correction, second run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-second-run-2026-11-21) — 27 lines + - [P03-9 Step 5 — hosted CI correction, third run (2026-11-21)](#p03-9-step-5--hosted-ci-correction-third-run-2026-11-21) — 24 lines + - [P03-9 Step 5 — hosted CI, the opposite shard layout (2026-11-21)](#p03-9-step-5--hosted-ci-the-opposite-shard-layout-2026-11-21) — 30 lines + - [P03-9 Step 5 — a local guard for unserializable theory data (2026-11-21)](#p03-9-step-5--a-local-guard-for-unserializable-theory-data-2026-11-21) — 16 lines @@ -24092,3 +24115,1367 @@ mapper-readback statement and Amendment 9 for the rest. | `python3 scripts/run-realm-node-tests.py` | 13 files, 498 passing tests | | `python3 scripts/test-openapi-ci.py` | 64 tests OK; the other eleven suites in `scripts/` OK; `test-ci-native-provisioning.py` not run | | `make docs-index`, `make lint-docs` | index regenerated; 3,845 fragment links resolve; roadmap structure conforms; delivery log indexes current | + +### P03-8 merge and delivery closeout (2026-11-19) + +The maintainer merges [PR #45](https://github.com/HodeTech/LearnStack/pull/45) at +02:59:14 Europe/Istanbul on 2026-11-19 (23:59:14 UTC on 2026-11-18). Reviewed head +`5eeba2c3` and merge commit `02654275` share tree `d43ee66d`; the merge parents are +`0c7394c7` and `5eeba2c3`. Development fast-forwards to that merge without switching +branches or changing files. + +P03-8 implementation delivery is complete and merged under Accepted ADR-0099 (Amendments +1–9) and the contract transition ADR-0100: D11 is delivered. Steps 0 to 4, their review +rounds, the CI triage, the contract transition and the +[PR review disposition](#p03-8-pr-review-disposition-2026-11-18) are recorded above. +This closeout changes documentation only and selects no new policy or ADR. + +Delivered behavior: + +- A tenant administrator configures one SAML or OIDC identity provider per tenant in + Studio. LearnStack owns the shared Keycloak broker and fixes every trust, flow, mapper + and egress decision; client secrets are write-only and egress is bounded and + address-class checked. +- Provider writes are intent-first and readback-verified: Begin, the provider call + outside any transaction, then Complete, each with its own MUST audit row. A lost write + settles as uncertain and Resume reconciles it. Drift, an expired test window and an + entitlement lapse are corrected at the next readback. +- The lifecycle is Draft, test window, passed test, Active, Disabled and a Deleted + tombstone. The sign-in option appears only for an Active, entitled connection, and + brokered sessions are host-bound at every credential publication path. +- The first-broker flow only links an existing account and creates none. The Keycloak + account console is retired, so no realm user has Keycloak self-service, and the realm + is pinned to 26.7.5 by digest. +- The OpenAPI gate approves the exact reviewed snapshot pair under ADR-0100 and is + isolated from a pull request's own scripts. + +Final-head evidence: + +- [Run 44408689473, attempt 3](https://github.com/HodeTech/LearnStack/actions/runs/44408689473/attempts/3) + passes 27 jobs with two skipped (the bot reviewers), layout **A**, at reviewed head + `5eeba2c3`; every required check is green. Attempt 1 (layout A) failed `ordinary-6`, + `ordinary-10` and the integration aggregate; attempt 2 (layout B) failed `ordinary-11` + and the aggregate. +- The failed shards' `ci-proof` artifacts show the Keycloak fixture start-up timeout + (`readiness_timeout` at `provider_starting`, TLS readiness not completing within 120 + seconds) with the failed cases lasting a millisecond, so no test body ran. The cause + is not localized, and the later pass does not erase the failed attempts. Only those + failed shards' artifacts were read; no original archive set was retained for this + head. +- Merge-triggered main run `44425299178` was queued at this observation and has a + different source identity. +- The local verification of the final tree is in the disposition record's table. + +Evidence boundaries and handoff: + +- No successful opposite-layout B exists on this final head. Final-head A/B + reconciliation remains an open P03-11 evidence follow-up, and the merge does not waive + Testing 06's complete-pair requirement. +- Manual accessibility for the Studio federation page and the sign-in option was not + performed (ADR-0099 C20). The full local Integration and Architecture suites were not + run; hosted CI ran them. +- The served-contract changes held for a new transition decision (the + `clientAuthentication` read-model field, the operation status descriptions and the + bound mismatches), gate G20, the Phase 11 items for the production realm invariants, + pre-registered accounts and the confirm-link copy, and the managed launcher's closed + inventory stay open as the disposition record lists them. + +Next by packet order is P03-9, platform authority and operational recovery (D12/D13, +C14/C15). G13 and G14 are Open and its decision pass must settle them before the first +Platform writer. It also owns the ADR-0099 federation operator steps: the orphan-broker +sweep, the operator disable of a broker the tenant cannot reach and the +delegated-account review. G20 is decided no later than the first packet that adds an +assignable permission key. P03-10 DSAR and global closure, which integrates +`federation_connections` and its broker, and P03-11 exit enforcement remain unstarted. +Phase 03 stays in progress; this closeout starts no next packet. + +## P03-9 — Platform authority and operational recovery + +### P03-9 proposed platform authority and recovery package (2026-11-19) + +**Status: Proposed.** The maintainer requests P03-9 through `implement-task` on +`development`, with a review of every existing governing document before +implementation, explicit approval of any new ADR before its dependent code, and every +decision that needs the maintainer shown up front. Each implementation step takes a +commit, a fresh independent review round one, verified fixes and a commit, then a +different fresh review round two, verified fixes and a commit. The work continues +between steps without an unnecessary stop. No Fable model is used. + +The baseline is clean `development` at `ed454f3a`. The request cites a +`docs/roadmap/current.md` that does not exist; the scope below comes from the +[Phase 03](phase-03-identity-admin.md) P03-9 row, gates G13 and G14, deliverables +D12/D13 and criteria C14/C15/C19. This proposal changes no register status, claims no +runtime behavior and authorizes no code. + +#### Problem, document review and decision boundary + +P03-9 delivers the first real Platform authority and the operational recovery that +privileged execution has waited on since Phase 02a. The gate still refuses everyone, no +operator is authenticated anywhere, and production has no tenant, first administrator, +issuer-rebind or recovery path outside the development seed. G13 and G14 are Open. + +Four independent read-only reviews compared the P03-9 text with ADR-0004/0015/0033/ +0034/0035/0036/0044/0045/0046/0047/0058/0064/0070/0072/0073/0074/0076/0077/0093/0097/ +0099/0100, Standards 04/05/11/18/19/20/21, Architecture 13/15/23/28/30, the Identity and +Tenancy module specifications, the realm exports, the Phase 02b/02c/11 text and the +code at `HEAD`. The maintainer's session re-verified the headline findings: the gate +and scope signatures, the null actor and correlation in the entry row, the absence of an +HTTP mapping for `PlatformAdminScopeDeniedException`, the singleton registration, the +absence of any production caller of `EnterAsync` and `ReplayAsync`, the missing +`/admin/hangfire` mapping, the platform role's lack of any grant on +`federation_connections`, and that the tenant OpenAPI document includes only `/api/v1` +paths. The load-bearing findings are: + +| Finding at HEAD | Action | +|---|---| +| ADR-0036 routes operators through `/api/internal` under the Hub chain; ADR-0004 says that chain is independent of the operator JWT | ADR-0101 chooses a direct operator scheme; ADR-0004 and ADR-0036 disclosures | +| Standard 04 writes `/api/v1/platform/...`; ADR-0036 leaves the URL space open | ADR-0101 fixes `/api/platform/v1`; Standard 04 edit | +| Standard 11 says the hub realm serves only the Hub portal | Standard 11 edit under ADR-0101 | +| "A real actor" is claimed for the scope row; the row carries null actor and correlation | ADR-0045 disclosure; matrix rewritten with Step 1 | +| Standard 18 says the scope reason is shown to tenant admins; sentinel rows are tenant-invisible | ADR-0101 § 9 and a Standard 18 clarification | +| The gate has no principal and is a singleton; its comments call permissions absent | ADR-0101 § 7 and § 8; comments corrected in Step 1 | +| ADR-0015 still guides a realm-role dashboard gate | ADR-0103 and ADR-0015 Amendment 2 | +| Phase 11 asserts producer replay and job requeue exist | Conditional rewrite at acceptance | +| D13 says the dashboard is admitted; its safe admission conditions do not hold | ADR-0103 § 8; D13 reworded | +| ADR-0099 defines an orphan as a missing row; delete keeps a tombstone | ADR-0099 Amendment 10 covers absent and `Deleted` rows | +| ADR-0100 expects Platform keys to recur the OpenAPI refusal | A Platform key is non-assignable; disclosure at acceptance | +| The `(planned)` matrix row fails coverage once its slug is registered | Row and registration change in one commit | +| `docs/runbooks/` is a Phase 11 deliverable that does not exist; D12/D13 need runbooks | Created in Step 1; Standards 12 and 13 amended | +| CODEOWNERS is cited as enforcing in four documents; the file is absent | Recorded for G20; not changed here | +| The Seeder refuses no deployment mode | ADR-0102 § 11 | + +#### Choices presented together + +- **Operator authentication.** A separate strict scheme at a pinned issuer, by default + the `learnstack-hub` realm, audience `learnstack-platform`, MFA by `acr`, human + operators only, on `/api/platform/v1/*`. No Hub forwarding and no service operator. +- **Grants.** A port with a configuration adapter, evaluated per act; a table adapter on + a named trigger. Keycloak roles carry no authority. +- **Denied evidence.** A counter and a log, with no durable row, because a durable row + needs a bypass connection for a refused caller or a third sentinel class. +- **Onboarding.** Operator-admitted acts on the app role through the ordinary pipeline: + provision a tenant and map its hosts, create Role templates, create the first + administrator, recover. The person is named by provider subject and must have signed + in once. The platform role is not used. +- **Issuer rebind.** An offline operator act through the installer tool: stopped fleet + checked by a session test, a continuity proof over every stored subject key, a guarded + column and a result row. No HTTP rebind and no runtime freeze. +- **Recovery.** Metadata-only inspection, targeted subscriber replay with a stale-state + fence, and a narrow producer reset limited to `retry_exhausted`, all on a confined + outbox-role owner with no new grant. +- **Not admitted, with owners.** Job requeue and reservation release until a provider + can prove quiescence (Phase 08a, Phase 11); recurrence recovery (Phase 11); every + dashboard form. +- **Federation operator steps.** Admitted as ADR-0099 Amendment 10, written at + acceptance: a separate operator port that lists marker-bearing brokers, reports each + class, removes an orphan or unreadable owned broker and disables a nonconforming + readable one at the provider only, with the row left to the tenant readback. The + platform role gains a column-limited `SELECT` on `federation_connections` (id, tenant, + state, deletion time). The delegated-account review is a runbook, because no + LearnStack credential may enumerate or remove realm users and the brokered link events + expire after seven days. The result rows of a disable or removal name the review as + owed. +- **G20.** Not triggered. Every P03-9 key is a non-assignable Platform key, no tenant + field changes, and the tenant document stays byte-identical. G20 stays Open for the + first assignable key. +- **Operator client.** The served operator document is the contract. This repository + ships no operator screen and no command-line client; the Hub operator portal, not + started, is the intended interface. Runbooks give the exact requests. + +#### Experience, performance and security confirmation + +- **Experience.** Every operator write has a report or inspection first. Responses use + closed Problem Details types with the next step named: stale fence (re-inspect), + bootstrap required (the person signs in first), audit unavailable (retry is safe), + forbidden (which permission). Writes accept an idempotency key. Runbooks carry exact + requests and the expected rows. +- **Performance.** Operator routes are low volume and add nothing to tenant requests: + no admission read on the authentication hot path and no freeze flag. Grants are + in-memory. Inspections are cursor-paged on existing indexes with an enforced page + cap, and the federation listing is paged with a deadline. +- **Security.** Two disjoint schemes and prefixes; admission before any privileged + credential; the platform role only for acts that need it; no raw provider connection + in the scope handle; every result row in the state's transaction; a Seeder mode + refusal. The hazards the reviews found map to the proofs in each ADR. + +#### Four implementation steps after approval + +1. **Operator authority and killswitch.** Realm client and audience, the scheme, + witness, Platform catalogue, grant source, gate, scope redesign, result seam, route + census, problem mapping, the killswitch writer, matrix and Standard 19 rows, and the + operator-access and killswitch runbooks. +2. **Production onboarding and issuer rebind.** The operator source and its setter + call, the resolver, the four acts and routes, the rebind verb with its guard + migration and canonical SQL, the Seeder refusal and the onboarding runbook. +3. **Operational recovery.** The confined owner, inspection, replay and reset with + fences, the two witness seams, census edits, the ADR-0015 and ADR-0046 disclosures + and the recovery runbook. +4. **Federation operator steps.** ADR-0099 Amendment 10, the operator port, report, + removal and disable, the column grant, the adapter route census update and + the federation operator runbook. + +Closeout follows: Status, the register, Phase 11 rewrites and the delivery record. Each +step ends with its own commit, review rounds and verified fixes before the next begins. + +#### Carriers owed at acceptance + +Accepting ADR-0101, ADR-0102 and ADR-0103 would close G13 and G14 and name this package +as their record. Dated disclosures follow in ADR-0004, ADR-0015 (Amendment 2), +ADR-0036, ADR-0040, ADR-0044, ADR-0045, ADR-0046, ADR-0047, ADR-0072, ADR-0073, +ADR-0099 (Amendment 10) and ADR-0100; Standards 04, 05, 11, 12, 13, 18, 19, 20 and 21; +Architecture 13, 28 and 30; the glossary; the Identity and Tenancy module +specifications; and the Phase 03 and Phase 11 documents. This proposal edits none of +them. + +### P03-9 package review dispositions and acceptance (2026-11-19) + +**Status: Accepted.** This record closes gates G13 (human operator authority, +production provisioning, first administrator, recovery and issuer rebind) and G14, and +accepts [ADR-0101](../decisions/0101-platform-operator-authority.md), +[ADR-0102](../decisions/0102-production-tenant-onboarding.md), +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md). Where it differs from the +[proposed package](#p03-9-proposed-platform-authority-and-recovery-package-2026-11-19), +this record governs: the proposal's single onboarding-and-rebind ADR is split, and its +four-step plan becomes five. + +#### Maintainer decisions + +The maintainer chose, on the four forks the proposal presented: no dashboard (the +inspection set replaces it, and D13's wording changes); the narrow producer reset is +included; the operator client is the served operator document plus runbooks, with no +screen and no command-line client in this repository; operator grants come from a +configuration adapter behind a port, with the table adapter on a named trigger. The +maintainer then supplied three independent reviews of the Proposed package, asked that +each finding be analysed against the code and the corpus because the reviewers did not +know the process, confirmed that the application is in development and not in use so +no backward compatibility is owed, and asked for acceptance and continued +implementation once the corrections were made. + +#### Verification of the findings + +The maintainer's session checked each claim that would change a decision against `HEAD` +before acting. The following were confirmed: the seed guard demands a single `Seed` +source, an exact trusted `Seed` source and the fixed declaration, and the API registers +deny-all seed continuation and foundation admissions; the first-admin command refuses +any Membership history; authority qualification reads once per process without a lock; +the route convention exempts only `api/internal`, and the tenant document includes only +`/api/v1` paths; ADR-0064 registers exactly one tenant bearer scheme; the platform role +holds no grant on `federation_connections`; the outbox role holds table-wide `SELECT` on +`outbox_messages` and a lifecycle-column `SELECT` on `tenants`; ADR-0093 says reissue +does not reconcile the old effect; the stray fragment in Architecture 30 existed; and +ADR-0040 counts ten logical tenant setters, four context writers and eight definers, not +eight setters. + +#### Dispositions + +| Finding (review labels) | Disposition | +|---|---| +| Rebind guard is not a control: a platform-role grant plus a settable setting (R2 B1, R1) | Fixed. A dedicated rebind role replaces the platform grant (ADR-0104 § 2) | +| Freeze window: qualification reads without a lock (R2 B2) | Fixed. Shared advisory lock on qualification and user creation (ADR-0104 § 5) | +| Seed policies "stay Seed" versus "alongside Seed" (R2 B3, R3 B1) | Fixed. Separate operator commands; the seed guards are untouched (ADR-0102 § 1, § 2) | +| Recovery is not the first-admin act (R3 B2, R2 M13) | Fixed. Two predicates, both under the ordered locks (ADR-0102 § 7, § 8) | +| First-admin could escalate a tenant that has administrators (R3 B7) | Fixed. First-admin refuses any Membership history (ADR-0102 § 7) | +| Target tenant contradicts the no-request-value rule (R3 B3, R2 M3) | Fixed. One confined eleventh setter, disclosed in ADR-0036 and ADR-0040 | +| Ordinary pipeline cannot carry operator attribution (R3 B4) | Fixed. The audit-composition branch is named (ADR-0102 § 9, ADR-0033 and ADR-0044) | +| Offline tool cannot mint the witness (R3 B5) | Fixed. One minter, two sanctioned callers (ADR-0101 § 7, ADR-0104 § 3) | +| Rebind needs `SELECT` and a user-reading credential (R3 B6, R2 M12, M14) | Fixed. Table `SELECT`, a read of four `users` columns, a run-time realm credential, a separate tool project | +| `/api/platform/v1` does not fit the route and OpenAPI mechanics (R3 B8, R2 M10) | Fixed. Prefix list, own document, census and classifier entries (ADR-0101 § 4); the gateway routes none | +| Subscriber replay does not filter terminal reasons (R3 B9, R2 M19) | Fixed. `invalid_envelope` always refused (ADR-0103 § 2) | +| Producer reset claim about every Active subscription is wrong (R3 B10) | Fixed. Only subscriptions with no delivery row are reached (ADR-0103 § 3) | +| Operator denial versus ADR-0077 and Standard 18 (R3 B11, R2 M1, R1) | Kept the decision, added the disclosures (ADR-0077 Amendment 2, Standard 18) | +| Ticket, reason, actor and `toggled_by` mapping (R3 B12, R2 M6) | Fixed. Ticket only in sentinel rows; business actor `SystemActor`; `toggled_by` NULL (ADR-0101 § 9) | +| Issuer may be any OIDC provider (R2 M2) | Fixed. Always a deployment-controlled issuer (ADR-0101 § 1, § 3) | +| Platform key set omits Standard 19's examples (R2 M4) | Examples stay unregistered; Standard 19 cites the catalogue | +| Federation keys have no owning ADR (R2 M5) | Fixed. ADR-0099 Amendment 10 | +| Sentinel class unnamed; "second caller" wrong (R2 M7, M8) | Fixed. The platform-scope class is extended by name; a new method, not a second caller (ADR-0044 Amendment 17) | +| Demo operator grant reachable in production (R2 M9) | Fixed. Refused unless Development (ADR-0101 § 6) | +| Tenant id is server-generated, so a lost reply loses it (R2 M11) | Fixed. The operator supplies a UUIDv7 and a slug; the act is idempotent on the pair | +| Host mapping is not an existing command; DNS unverified (R2 M15) | Fixed. A new operator command; the operator asserts ownership (ADR-0102 § 4) | +| Grant tests cannot see column privileges (R2 M16) | Fixed. Column-privilege tests are required (ADR-0103, ADR-0104) | +| No actor identity for operator acts (R2 M17) | Fixed. `SystemActor` in business columns; operator in audit | +| Inspection reads cross-tenant on a role with table-wide `SELECT` (R2 M18, M21) | Fixed. Inspection moves to the platform scope on named column grants | +| "Reissue" is not a remedy (R2 M20) | Fixed. Stated as a limit (ADR-0103 § 6) | +| Operations and routes missing in ADR-0103 (R2 M22) | Fixed. An operation table with permission, principal and audit | +| Erasure guard is runbook-only (R2 M23) | Fixed. An Active-tenant test until P03-10 | +| New outbox status writer versus CLAUDE.md (R2 M24) | Fixed. ADR-0046 Amendment 5 and the CLAUDE.md rule name the owner | +| Carrier lists incomplete or inconsistent (R2 M25, R3, R1) | Fixed. Each ADR lists its full set; the amendments are applied in this commit | +| ADR-0064 says exactly one scheme (R2 M26) | Fixed. Amendment 9 confines the second scheme | +| Rebind retry, enumeration time and reload mechanism (R1) | Fixed (ADR-0104 § 9; ADR-0101 § 6) | +| Permission table broken (R1, R2) | Fixed. My reflow script had wrapped an indented table; it now skips tables | +| Counters for replay and operator acts (R1) | Fixed. ADR-0101 § 14, ADR-0103 § 10 | +| Self-Hosted issuer must emit `acr` (R1) | Fixed. ADR-0101 § 3 and the runbook | +| Producer reset admits only `retry_exhausted` (R2) | Kept; `unknown_type` rows are not recoverable by reset | +| README placement of Proposed rows (R1) | Moot; all four are Accepted rows in the active table | +| Review severity labels | Not adopted; each finding was judged on its effect | + +Minor wording findings (key names, undefined terms, glossary terms, the 400 versus 403 +for a malformed ticket, "its MUST rows", the "one new realm client" count, the SQL +confinement wording, `OperationPolicyCatalog`, the dashboard-package wording, the rule +name) were corrected in the ADRs. The catalogue's dashboard-absence rule and the code +test that enforces it carry different names; Step 4 reconciles them. + +#### Accepted decisions + +- Operators authenticate at a deployment-controlled issuer through a second strict + scheme on `/api/platform/v1`, with MFA shown by `acr` and `auth_time`. Authority is a + LearnStack-held Platform grant evaluated per act. Admission is a witness, and results + commit with state. +- Production onboarding is five operator commands on the app role, a confined operator + source and an eleventh logical setter. The seed stays development-only. +- The issuer rebind is an offline operator act through a dedicated role, a lock, a + continuity proof, a guarded row and intent and result audit rows. +- Recovery is inspection on column grants, fenced subscriber replay and a narrow + producer reset. Job recovery, recurrence recovery and every dashboard form stay + absent. +- Federation operator steps are ADR-0099 Amendment 10. G20 is not triggered and stays + Open. + +#### Five implementation steps + +1. **Operator authority and killswitch** (ADR-0101). +2. **Production onboarding** (ADR-0102). +3. **Controlled issuer rebind** (ADR-0104). +4. **Operational recovery** (ADR-0103). +5. **Federation operator steps** (ADR-0099 Amendment 10). + +Each step ends with its own commit, a fresh independent review round and its verified +fixes, then a different fresh round and its verified fixes, before the next begins. +Closeout follows with Status, the register and the delivery record. + +#### Carriers applied in this commit + +Dated disclosures in ADR-0003, 0004, 0015, 0033, 0036, 0040, 0044, 0045, 0046, 0047, +0064, 0072, 0073, 0074, 0077, 0099 and 0100. Corrections to Standards 04, 11, 12, 13, 18 +and 19, Architecture 13, 28 and 30, the glossary, the Tenancy audit matrix, Phase 03 +(Status, register, section and deliverables), Phase 11 and the CLAUDE.md outbox rule. +Standard 05 grants and definers, Standard 19 key rows, Standard 21 rules, the permission +and audit matrices and the runbooks land with the steps that use them. No gate other +than G13 and G14 changes status, and no behavior is implemented by this record. + +### P03-9 Step 1 — operator authority and killswitch (2026-11-19) + +Step 1 delivers [ADR-0101](../decisions/0101-platform-operator-authority.md) § 1 to § 14 +for the first Platform operation, the killswitch toggle. The decisions were Accepted in +`a396f50e`; this record is the implementation and its proof. + +Delivered: + +- **Contracts** in `LearnStack.SharedKernel`: the Platform permission catalogue + (`platform.killswitch.write`), the closed operation registry, the operator witness and + the admission, each constructible only through a nested `Minter`, the operator subject + digest, the gate and grant-source ports and the ticket grammar. +- **Gate and grants** in `LearnStack.Infrastructure`: `PlatformOperatorGate`, the + configuration grant adapter on `IOptionsMonitor` (valid reloads apply on the next act, + an invalid reload refuses everyone), start-time validation of every grant, the + demo-operator rule, and the `learnstack.platform_operator` counters. +- **Scope redesign**: `EnterAsync` takes an admission; the handle is a facade with no + connection or transaction member and closes its connection at commit; the entry row + carries `metadata.operator`, the closed reason slug and the correlation id with a NULL + actor; a new witness-bound `IAuditStore.WritePlatformOperatorResultAsync` writes the + MUST result row on the work transaction. `IPlatformAdminGate`, + `DenyAllPlatformAdminGate` and `PlatformAdminScopeDeniedException` are removed. +- **Surface**: the `PlatformOperator` bearer scheme with a closed token profile shared + as `PlatformOperatorTokenProfile`, the named policy, minimal endpoints under + `/api/platform/v1`, the `platform-v1` OpenAPI document, the prefix added to the host + classification and versioned-route exemptions, and absence when no issuer is + configured. +- **Killswitch writer** `KillswitchToggle`: reads the before state under `FOR UPDATE`, + upserts, writes the result row, commits, then drops the overlay entry, including after + an indeterminate commit. `tenancy.killswitch.toggle` is declared off-path and loses + its `(planned)` marker. +- **Realm**: the `learnstack-operator` client with the `learnstack-platform` audience, a + 900-second access-token lifespan, no realm roles in the token, the `browser-loa` flow + with a level-2 one-time password, `acr.loa.map` `mfa` to 2, and a pinned demo-operator + subject. Development configuration accepts `mfa` and grants the demo operator the one + key. +- **Documents**: the operator-access and killswitch runbooks and the runbooks index; the + Keycloak README; Standard 19's Platform catalogue; the catalogue entry for + `PlatformAdminScope_Entry_Requires_Platform_Permission` and two new rules; the Tenancy + permission note; the glossary; the stale "no writer" narratives in Architecture 21 and + 31, Standard 05 and the code comments. + +Findings made while implementing, each fixed: + +- The host's default and fallback authorization policies carry only the + declared-operation requirement and no authenticated-user requirement, so + `[Authorize(AuthenticationSchemes = ...)]` alone authenticated the token and then + admitted an anonymous caller. The endpoints use an explicit named policy that requires + an authenticated principal from this scheme only. The case that found it asserts the + `Bearer` challenge, which only the challenge path sets. +- The pipeline-order proof treated the endpoint mapper's `MapGroup` as an unverifiable + helper; `MapGroup` joins `MapGet` as a framework endpoint leaf and the mapper is + declared. +- The Debug build of the architecture project fails + `Authorization_Evidence_Uses_Trusted_Bounded_Provenance`, an IL-shape rule over a type + this step does not touch; the Release build that CI uses passes it. Recorded, not + changed. +- Six closed censuses counted the new surface and were updated, each by exact type or + name and never by widening a pattern: the authenticated HTTP surface and the + job-manifest registration population exclude `PlatformOperatorEndpoints` (its own + population is closed by + `The_Operator_Surface_Is_Exactly_One_Authorized_Put_Endpoint_Under_Its_Prefix`); the + raw-claim authority census admits `PlatformOperatorTokenProfile.TryRead` alone; + `IAuditStore` gains its eleventh write; the unversioned-prefix list gains + `api/platform`; and Standard 21's published counts move from 377 to 379 test methods + and 164 to 166 rules in that assembly. +- Development configuration now carries an operator issuer and the demo grant, so every + test host would have inherited them. The base test factory blanks the issuer and + points the one grant at a subject nobody holds; the operator tests set their own. + Grants without an issuer validate as inert, because with no issuer there is no scheme + and the grant source answers no for everyone. +- A restored source file kept its old modification time, so an incremental build reused + the mutated binaries and three suites failed on stale code. Restored files are touched + before the rebuild. + +Proof run locally: + +| Suite | Result | +|---|---| +| Unit | 4,181 passed | +| Integration, operator and boundary subset (619 cases: route, host classification, authenticated surface, composition, OpenAPI, deployment modes, job manifest, tenant authentication, platform scope, operator HTTP, job admission, idempotency, rate limit, federation) | 619 passed | +| of which `PlatformOperatorHttpTests` (production Program, controlled RS256 issuer) | 26 passed | +| of which `PlatformAdminScopeTests` (real PostgreSQL as the platform role) | 24 passed | +| `PlatformOperatorRealmTests` (pinned Keycloak 26.7.5, real OTP login) | 3 passed | +| Contract (served tenant document unchanged) | 13 passed | +| Architecture (Release): scope and evidence rules, API conventions, audit conventions, corpus consistency | passed | +| Architecture (Release): `OutboxDispatchConventionTests`, `AuthenticationAuthorityTests`, `AuthenticatedHttpSurfaceTests` | were still running at the commit; the result is recorded in the review-round entry | + +The real-realm cases show that the shipped export issues an operator token with audience +`learnstack-platform`, `azp` `learnstack-operator`, `acr` `mfa`, an `auth_time`, a +lifetime inside 15 minutes and the pinned subject, that the same profile the scheme uses +accepts it, and that a token from the portal client on the same realm and user does not +meet it. + +Mutation checks, each applied, built, run and restored: the gate skipping the grant, the +ticket reaching a tenant-visible row, the cache dropped before the commit, a policy +without an authenticated-user requirement, an ignored `auth_time` age, an unchecked +`azp` and a result row allowed an actor were all killed. One survived: the scope's +refusal of a registered operation that does not use the platform role, because the +registry holds no such operation yet. It is an equivalent mutant today; Step 2 registers +the first and drives the guard. The unit case that implied it covered the +unregistered-operation half and was renamed to say so. + +Not done here and owned elsewhere: manual accessibility needs no screen in this step; +the runbooks were written and their requests are the ones the tests make, but no person +ran them end to end; gateway exposure, production realm MFA enforcement and the grant +table adapter are in Phase 11's list. + +### P03-9 Step 1 — review round 1 and its fixes (2026-11-19) + +Three independent reviewers read commit `bfba1228` with no knowledge of the process: +security and authentication, data and audit durability, and conformance and operability. +None reported a Blocker. Each finding was checked against the code before it was acted +on; the ones below changed the code, and the decisions that were recorded instead are +listed after them. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Authentication | The scheme fetched issuer metadata with the stock transport: redirects, no size cap, any origin named by the discovery document | Its own client: no redirect, five seconds, 256 KB, nothing outside the issuer's origin, no last known good, `TryAllIssuerSigningKeys` off. The tenant scheme's reader is now a shared helper (`BoundedMetadataReader`) with no behavior change | +| Authentication | `TryRead` was a public door to the witness minter, and the minter was an assembly-wide type | The minter is a private nested class of the profile, and a source census pins that only the authentication boundary names the profile, calls `TryRead` or names the minter base | +| Authentication | The profile relied on stock validation for `iss`; `iat` and `auth_time` were converted without a range check; path and `Bearer` matching were case-sensitive while routing is not | The profile restates the exact issuer, range-checks both claims, and both matches ignore case | +| Authentication | Accepted `acr` of `0` or `1`, or an operator issuer equal to the tenant issuer, would have started | Both are refused at start with a message that says why | +| Authentication | Every refusal was labelled `token_invalid` | A closed cause set from the profile and from the exception type, on the counter and in the Warning log; the response is unchanged | +| Classifier | The operator metadata alone made an endpoint infrastructure, which the tenant admission middlewares leave alone | Honoured only on a route under `api/platform/v1/`, behind exactly the operator policy and never anonymous | +| Scope | An admission could be kept and replayed, and a handle could commit a state change with no result row, run `COMMIT` or `SET` through the facade, or commit after a failed statement | The gate stamps the admission; the scope refuses one older than 30 seconds and spends it on entry. The facade takes one `SELECT`, `INSERT`, `UPDATE`, `DELETE` or `WITH` statement, refuses a commit with no result row, and is abandon-only after a failed statement. The result counter moves to the committed result | +| Audit store | The result row was bound to its admission by a substring search of `metadata` | `metadata.operator.issuer` and `subjectDigest` are parsed and compared, a ticket is accepted only on a sentinel row and only the admitted one, and the correlation id must match | +| Killswitch writer | Two first toggles of one key both read the registry default, because `FOR UPDATE` locks nothing when no row exists | The row is created at its default with `ON CONFLICT DO NOTHING`, then locked, read and updated. A cache removal failure is logged, and the commit no longer takes the caller's cancellation token | +| Operator endpoint | A missing `enabled` was answered before admission; a refused audit write left no signal | Admission first. The refusal logs at Error, counts `audit_failures` and carries `Retry-After`. The correlation id falls back to the request id, so a result row always has a handle | +| Operability | Counters used dotted names and had no row in Standard 10 | `learnstack_platform_operator_*_total`, five rows in Standard 10, and a new counter for failed metadata fetches | +| Realm | Password reset was on in the operator realm, a second path to a password that does not pass the second factor | `resetPasswordAllowed` is `false`; the README and runbook say so and give the order for a new operator: enrol the authenticator, confirm it, then grant | +| Tests | A result-row test wrote under a shared fixture tenant; assertions on `reason`, before and after state, `toggled_at`, the sentinel ticket, `issuer` and `executor` were missing; one expectation was inverted | Throwaway tenant id; the missing assertions; the inversion corrected | +| Docs | Runbooks omitted the full token profile, a decode recipe, executable commands, the audit query and the digest recipe; stale statements said the table had no writer | Runbooks rewritten; the statements corrected in CLAUDE.md, the Tenancy matrix, Standards 05, 18, 19 and 21, Architecture 21, the feature-key skill, the glossary and the compose and Keycloak READMEs | + +New cases: the admission age and single use (including 64 racing consumers), a catalogue +that lost only the operation slug, a grant withdrawn on reload and an invalid reload +failing closed, the profile cause matrix and the failure labels, the settings guards, +the classifier guard, redirect, oversized and foreign-origin metadata (the last with a +second live origin that would validate a token if it were followed), wrong `iss`, `typ`, +algorithm and signature isolated one at a time, case-insensitive matching, +`Retry-After`, a commit with no result row, a failed statement, the statement guard +(twelve refused forms, four accepted), the connection returned at commit with a pool of +one, the counter on commit only, two racing first toggles, the scripted writer order, an +indeterminate commit, a cache that cannot remove, and the store's refusal of fourteen +bound attributes after an accepted control. + +#### Recorded, not changed + +- **A start-time check that an operator issuer comes with the platform credential.** + Added and withdrawn: the closed credential-reader census + (`OutboxDispatchConventionTests`) permits no further reader of a connection string, + and the existing first-use error already names the key. The runbook lists the + credential as required for any act. +- **Requiring a platform host for `/api/platform`.** The surface is host-independent on + purpose (the target tenant is data of the act); the gateway that fronts it is Phase + 11's. +- **Keycloak `minimum.acr.value`.** Not adopted: the scheme refuses any `acr` outside + the accepted list whatever the flow produced, so a client that asked for a lower level + obtains a token that is refused, and an unverified realm attribute would add a second + control that nothing proves. +- **An end-to-end real-Keycloak token through the actual scheme.** The real-realm cases + prove the profile on a real token and the controlled-issuer cases prove the scheme on + real RS256; the two are not joined. Recorded as a gap, to be closed in Phase 11's + gateway proof. +- **A per-operation target kind** on `PlatformOperation`, so the store can also refuse a + tenant-targeted result for a platform-wide operation. Step 2 registers the first + tenant-targeted operation and adds it there. +- **The stock handler reports a disallowed algorithm as a signature failure,** so the + `token_algorithm` label is reachable only through a path the handler does not take; + the mapping stays for a future handler version and is covered by a unit case. +- **The marker clause.** The Standard 21 note that no handler carries both + `[AllowsUnresolvedTenantContext]` and a platform-scope entry is enforced as the holder + census (`Only_The_Operator_Services_Hold_The_Platform_Scope`), by path, because the + scope is a service and not a handler; the wording of the note says so. + +#### Mutation checks + +Eighteen mutations of the fix-pass guards, each applied, built, run and restored with +the restored file touched so the next build cannot reuse the mutated binary. Seventeen +were killed: the admission age unchecked, an admission reusable, a commit with no result +row, a failed statement leaving the scope usable, the statement guard off, the +connection kept past commit, the result counted when written, an unbound correlation id, +an unlocked first toggle (killed by the writer-order case; the race case is a regression +guard and is not deterministic against a plain read), a cancellable commit, an +unrestated issuer, a classifier trusting the metadata alone, a single-factor `acr` +allowed, a foreign origin followed, no `Retry-After`, and every cause reported as +generic. + +One mutant survived its first test and was killed after the case was strengthened: a +ticket accepted on a tenant row. The case's admission carried no ticket, so a second +condition refused the row for another reason; the admission now carries the ticket, so +only the sentinel rule can refuse it. + +One survives as an equivalent mutant: the scope's own refusal of a background-job frame. +The privileged data source refuses the same frame when the connection is opened, so the +property that matters, refusal before the credential is resolved, holds without it. The +scope's call stays as the named first refusal. + +#### Proof run locally + +On the final code of the step, after round 2: + +| Suite | Result | +|---|---| +| Unit | 4,327 passed | +| Integration, the whole suite (every rebind class: storage as the role and as every other role, the locks, the run end to end, the audit store, the tool as a child process, the realm reader against a loopback realm and the pinned Keycloak 26.7.5, the operator validator, the input rules) | 4,661 passed | +| Architecture (Release), every class except the five IL-census classes | 495 passed | +| Architecture (Release), the five IL-census classes | 178 passed, three of them after the lifecycle owner lists were completed (see round 2) | +| Docs: `make lint-docs` | passed | + +What the real-database cases show: each act answers `200` and again `200` on a repeat; +a changed value under the same identifiers is refused; a reply lost after the commit +(the outermost behavior fails once the commit is done) and an act interrupted between +its writes both leave the state the retry then completes once; a grant is judged per act +and a refused act writes nothing; an unknown tenant is `404`; a taken slug, host or +identifier is `409`; a tenant with Membership history refuses the first administrator +and the Role templates; recovery refuses while an administrator is active, succeeds once +none is, and leaves the database's last-administrator guard as it found it; an +Organization-scope or another tenant's administrator Role does not qualify; every row +carries `actor_user_id` NULL, the closed reason slug and the operator's issuer, `acr`, +executor and subject digest, and never the person's subject, the operator's raw subject +or the ticket; the correlation id the answer returns finds the rows. + +#### Mutation checks + +Thirty-two mutations of the new guards, each applied, built, run and restored with the +restored file touched. Twenty-two were killed at once: the guard accepting a read-only or +rollback-only unit, a global identity transaction, another tenant's plan or announcement, +or a lost lock not rolling the act back; the executor ignoring the operation binding, +admitting the sentinel or a stale or reused admission, or leaving its context installed; +the source answering in another context or for another operation; the first +administrator ignoring Membership history; recovery ignoring an active administrator; +Role templates ignoring history; the resolver returning a non-Active user, accepting +another authority, another session or a short key; route ids not checked; and a +provisioning replay accepting any pair. Ten survived. Five exposed gaps in the tests and +were killed after they were strengthened: the guard allowing a user, an organization or a +host scope that was already in the context when the act began, the source ignoring the +policy's sources, and recovery accepting any Role. Five are equivalent mutants: the +guard's checks of the source kind, the policy's sources and the descriptor's liveness, +which the coordinator and the invocation already enforce (the invocation can be built +only by the coordinator, so no test can present a mismatch); the executor's refusal of a +platform-role operation, which the act catalog refuses first; and the source's +frame-open check, which the disposal of the source with the scope makes redundant. + +### P03-9 Step 2 — review round 1 and its fixes (2026-11-19) + +Three independent reviewers, each read-only, read the range from the accepted decisions +to the implementation: authority and security, correctness and concurrency, and tests, +censuses and documentation. None reported a Blocker. Each finding was checked against +the code before it was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Provisioning | A replay compared only the slug and organization id and answered with the request's organization slug, which was never stored | The replay reads the stored organization and compares the whole request; the answer is what was stored and a changed value is refused | +| Identity acts | A retry was refused when the person's state or the template had changed after the first run | The Membership and Role replays are judged before the present state, and a template edited by the new administrator no longer unmakes the original act | +| Host mapping | The retry did not drop the cached resolution again; both flags defaulted to live although the factory defaults them off and no act unmaps a host | The retry invalidates again; both flags are required | +| Routes | The platform sentinel as a tenant answered 500; a blank or over-long subject was a `409` on the wrong field; ids were checked only at the tenant | The sentinel and every identifier are checked at the route (400); the subject is checked at the route | +| Resolver | It was called before the act was known to be live | The guard's `RequireLiveAct` is asked first | +| Storage refusals | Every refusal answered `identity_foundation_refused` | They answer in the sibling handlers' vocabulary: `concurrency_conflict`, `dependency_unavailable`, or the foundation refusal | +| Signals | § 11 promised per-act counters and none existed; the code comment and Standard 18 claimed a counter and a log for a refusal inside the pipeline | The act counter and event 7109 exist; the documents say what they emit | +| HTTP/2 | A body without a content length or transfer encoding was read as absent | Only HTTP/1.x reads absence from the headers | +| Migration | The resolver migration was reversible although every recent Identity head refuses reversal | Forward-only; the rollback census names the new head | +| Documents | The ADR errata had been mangled by the 88-column reflow and sat after the span they correct | Rewritten in the form [ADR-0041](../decisions/0041-correcting-false-statements-in-accepted-adrs.md) prescribes, before the span, with the evidence and the Current authority line | +| Documents | The runbook promised a retry refusal the code did not give; Standard 05 said "no grant" and "reads no other relation" | Corrected | + +New cases: a reply lost after the commit, an act interrupted between its writes, +sentinel and malformed requests, exact template and scope names, both host flags +required, a host held by another tenant, a foreign organization, Organization-scope +templates, another tenant's Role, a retry after the Role was edited, an ineligible +person, the resolver's remaining refusals, the act counter, and the no-denial-row +coordinator case with a seed control. + +#### Recorded, not changed + +- **The user-eligibility recovery predicate.** A 17th definer; the maintainer decides. +- **The classification of the ADR-0102 § 1 correction.** Inline errata, Decision + unchanged and an Amendment; a superseding ADR was weighed and not chosen. + +#### Mutation checks + +Eleven further mutations after the fixes, each applied, built, run and restored: the +coordinator's observed-denial skip, a host replay not counted or keeping the stale cache, +a provisioning replay ignoring the display name or the organization slug, the sentinel +and any subject accepted at the route, a Role and a Membership replay not counted, and a +Membership replay judged after the Role's state were all killed. The coordinator's first +denial skip, in `RecordDenial`, survived and is an equivalent mutant: the observed-denial +path is reached first and carries its own skip. + +### P03-9 Step 2 — review round 2 and its fixes (2026-11-19) + +Three further independent reviewers, with lenses different from round 1: composition, +regression risk and the whole attack surface; SQL, row security, locks, the migration +and performance; and operability, the API contract, maintainability and the coherence of +the document set. None reported a Blocker. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Contract | A `503` answered as a result carried no `Retry-After` although the operator document declares it on every `503`; the runbook described a lock timeout as a `409` | The helper that answers a result sets it; the runbook separates the lock the act could not take from the statement that timed out | +| Contract | The operator document listed a 409 reason that does not exist, a killswitch-only 404 and 400, no 413 or 429, and no required fields for the five bodies | The request records state their required fields, the ticket grammar and the subject length; the status texts are truthful; the test asserts the required members | +| Routes | `Enum.TryParse` accepted numerals, padded names and comma lists that OR into another member | Exact names only | +| Resolver | A provider fault or an unqualified authority escaped as an unclassified exception; the definer named a variable `found` and measured a key by `length` | Classified like the sibling stores; renamed; `octet_length` | +| Census | Standard 05 claimed the resolver's callers were pinned and nothing pinned them | `Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject` | +| Maintainability | The killswitch route repeated the refusal switch and the audit-503 block; `RequestTypes` had no caller; a summary and a 255 literal were stale or duplicated | One shared helper each; the member is removed; one constant | +| Documents | The Identity and Tenancy module specifications still said no production first-admin exists; the ADR repeated the setter claim in Context, Consequences, Implementation Notes and Carriers with no erratum; the runbook had no "Not recoverable here" section; the sibling runbooks applied killswitch-only signals to every act; the seeder's rule was missing from the seed skill and README | All corrected; Amendment 1 gains the shared-cores, unrecorded-ticket and request-shape items | + +#### Recorded, not changed + +- **A lock timeout on a unique-index wait in the Tenancy writes surfaces as a 500**, as + when two operators map one host to two tenants at once. The writes classify only a + unique violation, the translating save is shared with the seed, and the same request + repeated gets the right answer. Amendment 1 item 11 says so. +- **The ticket is not recorded.** The gate validates it, the five acts store it nowhere, + and the runbook says so. +- **A host mapping needs only that the tenant exists and is not deleted**, where the + Identity acts also need Trial or Active. Whether a suspended tenant may be mapped is + the maintainer's decision. +- **A repeated act commits MUST rows with no captured change**, counted as `replayed`; a + metadata marker on the row is not built. +- **A `replayed` flag in the response** would tell an operator resuming a setup without + reading the metric; the response shape is the contract and is left as it is. + +### P03-9 Step 3 — controlled issuer rebind (2026-11-20) + +Step 3 delivers [ADR-0104](../decisions/0104-controlled-issuer-rebind.md): an offline +tool that moves the identity authority to a new issuer origin under the same realm +path, on a sixth confined database role, after a freeze and a continuity proof. The +decision was Accepted in `a396f50e`; this record is the implementation and its proof. + +Delivered: + +- **The sixth role.** `learnstack_identity_rebind` in the roles script, compose, the + environment example and every fixture that runs the script, `NOINHERIT NOBYPASSRLS`, + a member of nothing, with its credential in no host configuration. The compose + README says how to add it to a warm volume. +- **The storage.** One forward-only Identity migration: `SELECT` and `UPDATE (issuer)` + on `identity_authority`, four `users` columns, a third `identity_authority` policy for + the update and the role added to the read policy and to `users_isolation`'s `USING`, + and the trigger that refuses any change of `id` or `authority_id` for every role. The + `audit_log` grant and the policy arm are installed by a central audit installer, + because no module names the table. The definer census stays at sixteen; functions and + triggers are thirty. +- **The freeze.** A fixed advisory key. Authority qualification takes the shared form + after `SET TRANSACTION READ ONLY`; the User-creation admission takes it first, under + its two-second `lock_timeout`, and then reads the stored authority and issuer and + refuses a creation from a process that qualified with other facts. +- **The seam.** `platform.identity_authority.admin`, the `identity.authority.rebind` + operation with its attempt slug, two witness-bound audit methods on `IAuditStore` with + throwing defaults and their off-path declarations. +- **One validator.** The operator validator moved from the API project into + Infrastructure: settings, the bounded metadata client, the profile and a new + `PlatformOperatorTokenValidator` for the offline caller. The scheme and the tool take + the validation parameters and the metadata manager from one factory. +- **The run.** `IdentityIssuerRebind`, with the continuity proof as a pure function, and + the tool project that supplies the operator token, the grant, the new-realm reader and + the exit codes. It prints one line of classes and counts. +- **Documents.** The runbook, ADR-0104 Amendment 1, ADR-0073 Amendment 9, Standard 05's + new section and its role, identity-authority and ledger text, Standards 10, 11, 18, 19 + and 21, the Identity module specifications, the glossary and the local-dev skill. + +Findings made while implementing, each fixed or recorded: + +- **ADR-0104 § 5's "reads the new value" is not what a lock does.** The creation + admission never read the issuer, so a lock would only have delayed a creation from a + process that qualified before the rebind. The comparison after the lock is what + refuses it; Amendment 1 item 5 records it. +- **No module may name `audit_log`.** The first migration put the grant and the policy + arm in the Identity module's DDL and the architecture rule refused it, so the SQL + moved to a central installer beside the creation witness's, and the rebind run names + the table only through the installer's constant. +- **The IL-shape rules are Release rules.** Run in Debug, a rule over the evidence + coordinator's IL failed on an unrelated method. The architecture suite is run in + Release, as the earlier steps' records say. +- **A pooled idle connection is still a session.** The freeze check refuses until the + pools of the stopped hosts have drained, and the runbook says so. +- **The role's posture is checked before use.** An escalated attribute, a membership, an + extra table grant or a column grant beyond the declared ones refuses the run before + the lock, with a test for each. +- **Step 2 left two Docker classes out of the CI shard plan.** + `PlatformOperatorOnboardingTests` and `OperatorSubjectResolverTests` carry xUnit + fixtures and were missing from `sharedFixtureClasses`, which the plan test would have + failed on. Both are added with the Step 3 classes. +- **A Step 2 analyzer warning** (`CA2263` in a unit test) would have failed the + warnings-as-errors build and is fixed. + +#### Proof run locally + +| Suite | Result | +|---|---| +| Unit | (result below) | +| Integration, `IdentityAuthorityRebindStorageTests` (real PostgreSQL as the role and as every other role) | 7 passed | +| Integration, `IdentityAuthorityRebindLockTests` | 6 passed | +| Integration, `IdentityAuthorityRebindTests` | (result below) | +| Integration, `IdentityRebindAuditStoreTests`, `IdentityAuthorityRebindToolTests` (child process), `KeycloakRealmContinuitySourceTests`, `PlatformOperatorTokenValidatorTests` | (result below) | +| Integration, `KeycloakEnumerationTests` (pinned Keycloak 26.7.5) | 1 passed | +| Architecture (Release), every class except the five IL-census classes | (result below) | +| Architecture (Release), the five IL-census classes | (result below) | +| Integration, the whole suite | (result below) | + +What the real-database cases show: the role holds exactly its column privileges and +nothing else and each refusal is raised by the database as that role; the key trigger +refuses a change of `id` and `authority_id` even with the grant present; a start that +overlaps a rebind waits for it and then fails or succeeds on the value it left; a +creation is refused within its two seconds while a rebind runs and after one it did not +qualify against; a rebind that changes only the issuer leaves every user row identical +and writes an intent row and a result row, both under the platform sentinel with no +actor and the ticket in `metadata.operator`; a run whose target is already stored writes +nothing; every refusal class leaves the issuer where it was and an intent row where the +run reached the decision; a forced audit failure rolls the change back; a session +terminated before the commit is reconciled as not applied; a commit whose answer was +dropped by a relay is reconciled as applied by reading the issuer. The child process +refuses a missing or malformed input, a bad token, a missing grant and a wrong role with +one fixed line that names no credential, subject, issuer or address. + +#### Mutation checks + +More than forty mutations of the guards, each applied, built, run against its owning +test class and restored: the continuity comparison and its Closed, Closing and ordinal +rules, the lock and the rollback on audit failure, the posture attributes, the freeze +check, the policy arms, the operator validator's four validations, the realm reader's +completeness, origin and paging, and the key trigger. Six survived at first. Four were +real gaps and are killed by new cases: the audit store's tenant rule, which the ticket +check masked; the realm reader's origin rule, which was exercised only against a closed +port; the page loop past a first page boundary; and the sign-in creation path's mapping +of a changed authority. Two are equivalent and recorded: the audit store's +operation-identity check, which its off-path catalogue lookup makes redundant, and +`ValidateIssuerSigningKey`, which governs the key's own validity and not signature +verification. + +### P03-9 Step 3 — review round 1 and its fixes (2026-11-20) + +Three independent reviewers, each read-only, read the range from the accepted decisions +to the implementation: authority, security and the attack surface; correctness, +concurrency and failure windows; and tests, censuses and documentation. None reported a +Blocker. Each finding was checked against the code before it was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Regression | The creation admission's issuer comparison broke two existing integration tests that used an authority other than the installed one, and the lock-signal assertion did not know the new authority kind | Both tests use the installed facts; the signal census knows the kind | +| Audit | The role's `audit_log` access was open to any tenant it announced through the tenant setting, because the ordinary arm named no role | The ordinary arm excludes the role; a test announces a tenant as the role and is refused | +| Role posture | The check compared table grants only, so an extra or a missing column privilege passed | It compares the three tables column by column in both directions and sweeps every other relation for any privilege | +| Commit | A reconciliation of an unknown `COMMIT` could read the issuer before the original transaction had ended and report a false "unchanged" | It takes the shared lock first, so it reads only after the original transaction ends | +| Freeze | The check ran once, before a proof that can last minutes | It runs again immediately before the change | +| Outcome | A failure to dispose could replace the outcome of an applied rebind | Disposal never replaces the outcome | +| Inputs | The target issuer and the deployment mode were read more loosely than the API reads them | The mode is a declared name, the issuer follows the realm grammar, and outside Development it is HTTPS | +| Realm reader | One pass, no repeat check, no token renewal, the credential sent to any address the discovery document named, and no size bound | Two passes that must agree, repeats refused, one renewal per request, same-origin only and only after the discovery issuer equals the target, and a 200,000-user bound | +| Tool | An interrupt was not handled, the stdin wait had no bound, an outcome could go to standard error and a refusal carried no correlation | Interrupts end the run through the token, the wait is thirty seconds, everything goes to standard output, every refusal after the input carries its correlation | +| Census | The validator's and the profile's callers were unpinned and the executor set was open | Two rules pin the callers and the executor set is closed | +| Documents | The runbook, Amendment 1 and Standards 05, 10, 11, 19 and 21 said things the code did not do | Corrected | + +### P03-9 Step 3 — review round 2 and its fixes (2026-11-20) + +Three further independent reviewers, with lenses different from round 1: composition, +regression and the runtime; SQL, row security, locks, the migration and performance; and +operability, maintainability and the coherence of the document set. None reported a +Blocker. Each finding was checked against the code before it was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Freeze | The last-moment session count ran in the same transaction as the first, and the server serves `pg_stat_activity` from one snapshot per transaction, so the second count always repeated the first and a host that never takes the rebind lock could start in between | Each count first calls `pg_stat_clear_snapshot()`; a case opens an outbox session while the realm is read and expects `refused_live_sessions` before the change | +| Idle fence | Round 1's `KeepAlive` sends a message on the idle connection, and every message restarts the server's idle-in-transaction clock, so a hung tool's lock was never freed at fifteen minutes | The application keepalive is off whatever the connection string says; the operating system's TCP probes stay; a case sets `KeepAlive=1` in the string and watches the idle session's `state_change` stay still | +| Role posture | A `PUBLIC`-readable relation an extension owns (`pg_stat_statements`) locked the tool out in a way the runbook's remedy could not fix; the maintenance privilege, sequences and owned objects were not checked; a null answer threw | Extension-owned relations are not counted; the maintenance privilege, sequences and ownership of a relation, function or schema are; a null is a failed check; cases for each | +| Session settings | The three timeouts depend on the connection's startup options, which a pooler drops, and nothing checked they took effect | They are read back from `pg_settings` and refuse the run as `session_settings` | +| Diagnosis | `refused_input` covered nine causes, `refused_new_realm_unavailable` six and `refused_database_unavailable` swallowed stored-state faults as outages | A closed `detail` names the setting, the step of the realm read, the kind of database failure, or the posture check; it names no value | +| Exit codes | A failure to read back an unknown commit could escape as `refused_unexpected` and exit 2, which says the state is unchanged; an unexpected failure printed no correlation | Any reconciliation failure is `unknown`; an unexpected failure prints its correlation | +| Signals | A hang-up (an SSH drop) was unhandled, a signal in the last instant could fault the process, and nothing tested the handlers | Hang-up is handled, a late signal cannot throw, the stdin wait ends on a signal, and child-process cases send TERM and HUP while the realm read hangs and expect `refused_cancelled`, the intent row and no change | +| Deployment mode | The tool compared the mode exactly while the API ignores case and padding, so a lawful `saas` was an opaque `refused_input` | One `DeploymentModeParser` in the kernel is read by both | +| Counters | The runbook and Standard 10 said every run is counted, and the refusals before the database were not | They are recorded under the label the line prints | +| Logs | The runbook and the test comments said the tool logs; it writes none | Said plainly in the runbook, ADR-0104 Amendment 1 item 9 and the operator-access runbook | +| Runbook | It named no build step, said a rollback was unrecoverable while its own proof allows one before the new realm takes people, deleted the client and retired the password before a sign-in was confirmed, listed one setting where four name the realm, gave no way to enable the role, quoted a password unsafely, and left exit 3 and the continuity counts without a next step | Build, enable and retire steps, a rollback section with its precondition, the full settings table, a quoted example with TLS, the exit-3 read-back and the two shapes of continuity failure | +| Documents | Eleven prose lines over 88 columns, the rebind's token and role text twice in Standard 11, a missing Identity permissions row, a wrong place for the issuers in the audit specification, and a profile reader that became public without saying what confines it | Wrapped, pointed, added and stated in ADR-0104 Amendment 1 item 11 | +| Dependencies | The two new package pins are coupled to JwtBearer with nothing saying so | A comment in the props file says so | +| Logger category | The API named the retriever's category with a hand-typed string | The factory takes an `ILoggerFactory` and owns the category | +| Magic numbers | The idle fence had to exceed the run deadline and lived as literals in two files | Named constants in the library, with a test that the fence outlasts the deadline | +| Census | The heavy IL census, never run on Step 3's final code, found three cases of one cause: the lifecycle census enumerates every owner of a database commit and rollback, and the rebind's two transactions and its already-applied rollback were not listed | The three owners are listed with the reason; the census passes | + +#### Recorded, not changed + +- **No release artifact carries the tool.** The runbook builds it from the deployed + commit. A packaging decision belongs to whoever owns releases; none is made here. +- **A denied operator attempt at the offline tool leaves the printed line and, with an + OTLP endpoint, the counter, and no durable server-side trace.** Standard 10 and + ADR-0101 § 11 ask a counter and a log; the tool writes none. A stderr log would carry + the operator's identity into terminals and logs the tool promises not to write. The + maintainer decides whether the line is enough. +- **The tool does not require TLS to PostgreSQL.** The runbook asks for it. Nothing else + in the repository enforces database TLS either. +- **The platform and outbox roles can write rebind-shaped audit rows**, as they can + write every other platform-sentinel row. A trigger that confines the two operations to + the rebind role is not built; ADR-0104 Amendment 1 item 10 says so. +- **`PlatformOperatorTokenProfile.TryRead` is public**, confined by two census rules and + not by the compiler; the alternative is `InternalsVisibleTo` for the API project. +- **`RunCoreAsync` is long**, and `DisposeQuietlyAsync` has two siblings elsewhere. They + read as phases and are left alone rather than refactored in a review fix. +- **Shard weights for about a hundred new Docker cases** are the default until a CI run + measures them. The balance, not correctness, is affected. +- **A 55P03 from the final `UPDATE`'s row wait** reports `refused_rebind_in_progress`; + no state changes either way. +- **ADR-0003 Amendment 14 says the canonical policy template is unchanged**, which + holds: the restated `audit_log_isolation` arm is the central installer's, owned by + Standard 05. + +#### Mutation checks + +Sixteen mutations of the round 2 guards, each applied, built, run and restored, and all +killed: the activity snapshot not refreshed before the count (which also showed the +reviewer's claim true: without the call the late count repeats the first), the client +keepalive left to the connection string, extension relations counted, the maintenance +privilege, sequences, function ownership and schema ownership ignored, a +`PUBLIC`-readable relation outside an extension tolerated, the session settings not +compared, an authentication failure classified as a connection failure, the deployment +mode compared with case, the hang-up not handled, the realm token step not named, tool +refusals not counted, the detail not printed, and the refused input's field not named. +Two branches have no case that reaches them and are recorded: the refusal for session +settings the server did not apply (it needs a pooler in the path), and the stdin wait +ending on a signal. Both are small, and the first is checked in the positive on every +run. + +### P03-9 Step 4 — operator recovery of asynchronous work (2026-11-20) + +Step 4 delivers [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md): +a metadata-only inspection of dead-lettered work and two fenced transitions, and no +dashboard and no job recovery. The decision was Accepted in `a396f50e`; this record is +the implementation and its proof, and ADR-0103 Amendment 1 records where the code +corrected the Decision. + +Delivered: + +- **The seam.** `platform.delivery.read` and `platform.delivery.write`, the three + operations `platform.delivery.inspect`, `platform.delivery.replay` and + `platform.delivery.reset` with their off-path declarations, and an executor kind on + every `PlatformOperation` (scope, pipeline, recovery owner, rebind tool) that replaces + the earlier pair of booleans. +- **The inspection.** `IDeliveryInspection` and `DeliveryInspection`: cursor-paged + metadata of dead-lettered and terminal-requested outbox rows and deliveries and of + quarantined jobs with their reservation occupancy, one entered platform scope per + page, on column grants. One forward-only Platform migration revokes the platform + role's table-wide `SELECT` on `outbox_messages` and grants twelve, fifteen, + twenty-seven and seven named columns of the four tables, and adds two partial indexes. +- **The two transitions.** `DeliveryDispatchStore.ReplayAsync` and the new + `OutboxDispatchStore.ResetAsync`, each a partial-class file: lock, fence, state and + tenant checks, one fenced `UPDATE ... RETURNING old.*, new.*` and a MUST row on the + same outbox-role transaction through the sibling witness `OperatorRecoveryTransition` + and the fourteenth `IAuditStore` write. Each store has a third connection slot for + the operator lane (capacity 52 to 54, 158 to 160), and `OperatorRecovery` is the DI + owner behind `IOperatorRecovery`. +- **The routes.** Three `GET` inspections and two `POST` acts under + `/api/platform/v1/asynchronous-work`, gate first, served in `platform-v1`. +- **Signals and documents.** `learnstack_platform_operator_recoveries_total`, the + runbook `operator-recovery.md`, ADR-0103 Amendment 1, Standards 05, 10, 18, 19, 20 and + 21, Architecture 15, 23 and 31, the module documents and the glossary. + +Where the code corrected the Decision (ADR-0103 Amendment 1, with inline errata beside +the statements in the Decision): + +- The platform role already held table-wide `SELECT` on `outbox_messages`, so the + migration revokes it before it grants twelve columns. +- The witness is a sibling class with two kinds, not a new kind of the terminal witness + whose census pins two factories. +- The status map is closed, so a stale fence and a refused state are reasons on the + fields `fence` and `state` of `business_rule_violation`, and an unknown commit + outcome is a reason on the field `outcome` of `dependency_unavailable`. +- The inspection's entry row carries the operation `platform.admin_scope.enter` and the + reason `delivery_inspect`; it does not say which list was read. + +Proof, against real PostgreSQL as each role: the current fence applies and every stale +variant refuses, one microsecond included; a stale fence is reported before a refused +state; each refused state, a tenant that is not serving and a type the registry has +retired or no longer knows; a forced audit failure rolls the change back; a wrong, +stale or spent admission; the operator lane in each store; a lost commit +acknowledgement and its repeat; the siblings and the inbox byte-identical after a +replay; the witness refusing each substituted field of its row and a foreign +transaction, and a reused witness; the real owner counting each outcome under its own +operation; the inspection's pages, cursors, occupancy counts and exact column +grants; the eleven routes, their statuses and the served contract; and each delivery +permission held alone. + +### P03-9 Step 4 — review round 1 and its fixes (2026-11-20) + +Three independent reviewers, each read-only, read the range from the implementation's +base to its commit: authority, security and the attack surface; correctness, +concurrency and failure windows; and tests, censuses and documentation. Each finding +was checked against the code before it was acted on; the three reports agreed on the +two that mattered most. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Tests | About forty integration test sites and three unit sites still pinned the old 52-connection floor, so every runtime fixture threw on construction | The sites derive the floor from the production manifest through one constant; the unit sites pin 54 and 53; the fixture comment says 160 | +| Contract | The unknown-commit `503` carried `status: 500` in its body, because the status map is closed and the reason was a new top-level code | It is `dependency_unavailable` with the reason on the field `outcome`; a test asserts the body's status for every `503` | +| Authority | Nothing pinned which permission each operation binds, and every HTTP case ran as an operator holding all three keys | A unit theory pins the pair both ways, and an HTTP theory holds each key alone against all five routes | +| Tests | The real owner ran in no test, its counters were unobserved, and no test showed the witness refusing a substituted field | Owner tests over the real stores read the counters by operation; a ten-field substitution matrix and a reused witness run for each store | +| Tests | The occupancy assertion was vacuous, the cursor test could not tell a bound scope from an invalid key, deliveries and terminal-requested rows were not paged, the outbox column inventory was open and the outbox operator lane was unproven | Each has its own test, seeded so that the guard decides the outcome | +| Contract | A `limit` of zero was clamped, a state on the jobs list was ignored, a refused page parameter named nothing, an inspection's database fault was a `500`, and a `503` logged no cause | Zero is refused naming `limit`, the jobs list refuses a state, each refusal names its parameter, the fault is a `503` and the cause is logged and never returned | +| Failure windows | A fault after the `COMMIT` was sent, the connection's cleanup included, was reported as nothing changed | Any such fault is reported as an unknown outcome; a missing lifecycle projection is a configuration error and no longer a transient `503` | +| Disclosure | `last_error` is bounded by length only, so stored text could reach the page | The page shows a descriptor-shaped value and `unrecognized` otherwise | +| Documents | Four documents said the entry row names `platform.delivery.inspect`; the access runbook omitted two credentials; the recovery runbook was wrong about reasons, queuing, refusals and the erasure owner; Standard 05 restated the ADR and claimed proofs that did not exist | Corrected; ADR-0103 carries inline errata beside the false text and Amendment 1 items 6, 7, 9 and 10; Standard 21 records the new consumer | +| OpenAPI | A read listed `404`, `413` and `415`, the page parameters were free strings and two texts called every act idempotent | Reads list none of the three, the parameters carry their enum, bounds and shape, and the texts say what a repeat answers | +| Censuses | The reset factory and the outbox reset overload had no mutation twin; two HTTP assertions were loose | Twins added; the assertions name their status | + +Mutation checks of the guards this step added: twenty-six single-line mutations of the +fence comparison, the state and tenant checks, the result row, the operator lane, the +witness binding, the permission pair, the page rules, the descriptor shape, the +occupancy counts, the cursor scope and the owner's counters. Three survived at first +because the fenced `UPDATE` repeats each predicate, so the early comparison only +decides whether a stale fence is reported before a refused state; one test per store +now pins that order, and all twenty-six are killed. + +#### Not changed + +- **`Cache-Control: no-store` on the operator `GET`s.** Steps 1 to 3 answer the same + way, and a shared cache does not store a response to a request that carries + `Authorization`. A response policy for the whole operator surface is the maintainer's + decision, not this step's. +- **Verb sub-paths `/replay` and `/reset`.** Standard 04 does not forbid them and the + decision names no path. +- **The fence as one opaque token.** The microsecond instant is kept exact, because the + comparison is the safety property; a client that truncates it is refused, never + wrongly admitted. The runbook says to send it back as returned. +- **A disposal fault after a successful `COMMIT`.** The code reports it as an unknown + outcome; no test can inject it, because Npgsql's disposal does not throw on a dead + socket. +- **A ticket on a replay or a reset.** It is checked and not stored, because the audit + row is readable by the tenant; the runbook says to record the correlation id. + +### P03-9 Step 4 — review round 2 and its fixes (2026-11-20) + +Three fresh read-only reviewers read the range with different lenses from round 1: +composition and regression; SQL, row-level security, the migration and performance; +and operability, the operator's experience and the truth of the documents. None +reported a Blocker or a Major. Each finding was checked against the code before it +was fixed. + +#### Fixed + +| Area | Finding | Fix | +|---|---|---| +| Operability | The unavailable-owner log line reused event id 7109, which the onboarding runbooks, three ADRs and a test pin as a defect alert | The line is 7110; a test captures the log of the `503` path and asserts the id, the level and the cause | +| Failure class | Every database fault, a refused credential and a missing grant included, was reported as a retryable `503` | Only a transient fault, a timeout or the server's statement timeout is unavailable; a refused credential or a missing grant surfaces as the `500` it is, with a unit theory over the SQLSTATEs and a real-database test of both | +| Operator experience | A refused state said only that it was refused, and the unknown-outcome recipe asked the operator to observe an advanced count that a landed act never leaves | A refusal names its rule as the `cause` parameter of its reason; the runbook's unknown-outcome recipe is list again, then the tenant's audit row by the correlation id | +| Contract | A misspelt query parameter was ignored and answered a different list, a `limit` past the range of an int was refused, the jobs list advertised a `state` it refuses, and the page size was declared again at the edge | An unknown parameter is refused without being echoed, any size above the maximum is clamped, the jobs list does not offer a `state`, and the kernel's constants are used | +| Documents | Phase 11 and Architecture 23 still said the platform role reads `outbox_messages` whole; the Outbox canonical block lacked its new index; two statements said the two stores share one cleanup seal; the runbooks omitted the log ids, the cause classes of a `503` that does not clear, the response table's other statuses, the audit read recipe, the `#` encoding and the producer-reset wording | Corrected; the runbook now has a section for an unknown outcome and one for a `503` that does not clear; ADR-0103 Amendment 1 items 6, 7, 9 and 10 say what the code does | +| Tests | The keyset's tie-break columns, the indexes' keys and predicates, the plan of each dead-lettered page, a recovery admission on the platform scope and on the platform result writer, and the previous Platform head's `Down` were unpinned; two stale 52-connection literals remained | Each has a test, and the literals are corrected | + +Mutation checks of the guards this round added: the transient classification, the +refusal tokens, the unknown-parameter and limit rules, the event id, the keyset +tie-break and the executor kind of the result writer. + +#### Not changed + +- **A non-concurrent `CREATE INDEX` in the migration.** The two indexes are built in + the migration's transaction, as the earlier ledger indexes were, and the tables are + small until the retention purge of Phase 11 exists. A concurrent build, or a lock + timeout, is a deployment decision for that phase and the maintainer. +- **A single-row read or a tenant and event filter on the lists.** The recipe for an + unknown outcome does not need one, and each page is one audited scope by design; + the runbook names it as not here. +- **The failure descriptor in the audit row.** A reset clears `last_error`, so the + descriptor that caused the dead letter is not in the fence's before state. Whether + the row should carry it is a maintainer decision. +- **The platform role's loss of `SELECT` on the correlation and actor columns of + `outbox_messages`.** It constrains P03-10 and Phase 11, which need a named grant or + another principal for a predicate that reads them; Phase 11's text now says so. + +### P03-9 Step 5 — federation operator steps (2026-11-20) + +Step 5 delivers [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md): +a report, a remove and a disable of the identity-provider brokers a tenant's federation +left orphaned, unreadable or nonconforming, and no way to list or remove a realm user. +Amendment 11 records where the code corrected Amendment 10, and +[ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md) records the audit seam it +needed. The maintainer chose the audit shape (a checkpoint on the platform scope handle, +a fifteenth `IAuditStore` write) and accepted the bounded raw round trip of the disable +before any code was written. + +Delivered: + +- **The seam.** `platform.federation.read` and `platform.federation.admin`; the three + operations `platform.federation.report`, `platform.federation.remove` and + `platform.federation.disable`, the last two with attempt slugs + (`platform.federation.remove_attempt`, `platform.federation.disable_attempt`) declared + off-path MUST/SecurityEvent in the Tenancy catalogue. +- **The audit checkpoint.** `IPlatformAdminScopeHandle.WriteIntentAsync` writes the + intent row on the attempt slug with the outcome `indeterminate`, commits it, and + continues in a fresh transaction on the same connection, once, and a result row is + refused before it. `IAuditStore.WritePlatformOperatorIntentAsync` is the fifteenth + write, witness-bound like the result method, refusing a ticket on a tenant-readable + row and the identity module's own rows. +- **The ports.** `IFederationOperator` beside the tenant provider port, with a + fail-closed default and a second adapter instance with its own resilience pipeline; + `IFederationBrokerOperations` with its closed result types, owned by + `FederationBrokerOperations` in Identity Infrastructure. The adapter's route census + grows from four builders to six (a bounded page of the listing and a read by derived + alias), and the owner marker is parsed strictly: an `lsf-` alias and a + `{tenant:D}:{connection:D}` marker that round-trips. +- **The rows read.** An Identity-chain forward-only migration, + `20261120160000_grant_platform_federation_projection`, grants `learnstack_platform` + `SELECT` of four columns of `federation_connections`; the raw-reader census admits the + operator's one statement, pinned whole. +- **The routes.** `GET /api/platform/v1/federation/brokers`, and `POST` of + `.../{alias}/remove` and `.../{alias}/disable`, gate first, served in `platform-v1`; + the counter `learnstack_platform_operator_federation_total`. +- **Documents.** The runbook `federation-operator.md`, ADR-0044 Amendment 18, ADR-0099 + Amendment 11 with an erratum beside the item that cited a pattern Amendment 2 does not + hold, Standards 04, 05, 10, 11, 18, 19, 20 and 21, Architecture 31, the Identity and + Tenancy module documents, the runbooks index, operator access and the glossary. + +Where the code corrected Amendment 10 (ADR-0099 Amendment 11): + +- The intent-first pattern is the Decision's § Intent-first operations, not + Amendment 2, which is the Keycloak pin. +- A remove refuses while a live row names the broker, an unreadable owned broker + included: such a broker is disabled by the operator and deleted by the tenant. +- The disable of an unreadable broker is the one provider write that sends back what the + provider returned, with only `enabled` changed, because the fixed profile cannot be + rebuilt from a representation that does not read. +- A mapper is drift only a mapper read shows, so the mappers of a healthy broker are + counted one after another within the page's ten seconds and an unread count is + reported unknown, never zero. +- The report reads the realm first and the rows second, because a tenant writes its row + before it creates the broker. + +Proof, against real PostgreSQL as each role and the pinned Keycloak 26.7.5: the +listing's pages, the three classes and the foreign, unmarked and mismatched instances +that are counted and never named; a remove of an unreadable orphan that deletes the +federated links and leaves the account and a control broker byte-identical; a disable +that changes `enabled` alone; the intent row committed before the provider call and +surviving a failure after it; no tenant row for an absent broker, an unowned alias, a +live row or an unavailable provider; the result row refused before the intent, the +intent refused twice and for an operation with no attempt slug; the exact column grant +and the refused columns; each route's statuses, bodies and permission held alone; and +the route, port-holder and raw-reader censuses with their planted violations. A +mutation sweep over the new guards killed every mutant but one equivalent: a marker +length check that the marker's round trip makes redundant. + +### P03-9 Step 5 — review round 1 and its fixes (2026-11-20) + +Three read-only reviews ran over the Step 5 commit, one per lens: goal conformance, +authority and security; correctness, the audit checkpoint and robustness; tests, +censuses, documentation and standards fidelity. Each finding was verified against the +code before it was acted on. The first full run of the heavy architecture suite had +already failed three lifecycle-census tests, and the full integration run one +isolation test, for two causes recorded below. + +Fixed, with the proof that now catches each: + +- **A completion lost after a change read as "nothing changed".** The completion row + is written on a bounded three-second token detached from the request. A caller that + leaves while the provider works is recorded `uncertain`, and a completion that cannot + be written after a change that landed or may have answers the unknown outcome with + the intent row standing. Owner tests fail the completion after an applied remove, an + uncertain remove and an applied disable, fail it when nothing changed (still the audit + failure), and abort the caller inside the provider call. +- **An unread mapper count made a drifted broker vanish.** The report carries + `mappersUnread`, the healthy-looking live brokers it could not clear. Owner tests + return a count, `null` and a deadline from the scripted provider. +- **A database fault was a raw 500.** The owner translates a transient fault to the + unavailable owner with its cause for the log, the route answers `503`, and any + failure to commit the intent row now stops the act. The fault classifier became + public for it. Owner and route tests cover each act. +- **An unreadable owned broker with a live row could be removed by nobody.** The + tenant's Delete reports it foreign and fails, and the operator remove refused the + live row. The maintainer chose to admit the operator remove for exactly that class; + ADR-0099 Amendment 12 records it with an erratum beside Amendment 11 item 5. Owner + tests refuse a readable pair, remove an unreadable one with its row untouched, and + refuse a delete whose row turned live after the intent. +- **Record against behaviour.** The ticket is recorded on the entry row, never on a + tenant row; the grant sat in the wrong column of the Standard 05 matrix; the runbook's + metric labels, step order, class count and `accountReviewOwed` were wrong; the served + contract named too few reasons and fields; Standard 21 still counted three raw + readers and two scope holders; the glossary, the provider specification and the + audit documents lagged. Each is corrected, and Amendment 12 records the decisions + that were implicit (the audit outcome of a completion row is `success`, and an + applied disable owes the review too). +- **Test gaps.** Marker and row disagreeing on remove and disable, every non-applied + disable outcome, an uninspectable alias, the route's field-level reasons, the + counter's labels, a report's audit failure, the real-provider paging being disjoint + and complete, and a real brokered sign-in after a disable that proves the provider + kept the stored secret. The port-holder census now also finds a holder of the + concrete owner, with planted controls, and the listing's one exact query is pinned. + +Two causes outside the findings: the new checkpoint is a `CommitAsync` owner the +delivery-lifecycle census had to name, and the new audit-writing service tests moved to +an isolated database because `audit_log` is append-only and the shared schema's +isolation census counts the rows each seeded tenant sees. + +Decided and not changed: + +- **The audit outcome of a completion row.** It stays `success`; the provider outcome + is `after_state.outcome` (Amendment 12 item 5). A query for non-success rows misses a + refused or uncertain provider call, which is the open question for the maintainer. +- **An applied disable owes the review** (Amendment 12 item 6), as Amendment 10 item 6 + says. +- **The marker's tenant is not checked against `tenants`.** Amendment 11 item 3 decides + it, and planting a marker needs realm-console rights, which exceed a tenant + administrator's. +- **No batched mapper read.** The operator pipeline's per-call timeout bounds one call, + so one token over a batch would not be sound; the page's ten seconds and + `mappersUnread` bound the cost, and the runbook says so. +- **The disable reads the row once.** Amendment 11 item 8 accepts the read-and-write + interleave; the effect fails closed. + +### P03-9 Step 5 — review round 2 and its fixes (2026-11-20) + +Three further read-only reviews ran over the round 1 fix commit with different lenses: +an adversarial analysis of the fixes and of the authority change they carry; contract +and documentation truth after the round 1 edits; and test adequacy of the fixes with +fresh eyes on the whole step. Each finding was verified against the code first. + +Fixed, with the proof that now catches each: + +- **The removal rule rested on a false premise.** Amendment 12 item 1 let the operator + remove an unreadable owned broker with a live row because it "already fails closed". + It does not: "unreadable" is the shape check of one read, a broker edited in the + provider's console can be unreadable and still serve sign-ins, and the tenant's + brokered publication does not depend on a provider read. The remove of a broker a + live row names now needs it to be unreadable **and disabled**, which the adapter + proves again at the delete and refuses to send otherwise. ADR-0099 Amendment 13 + records it with inline errata beside the false premise and the wrong pointer. The + maintainer's choice to make the class removable stands; the rule that narrows it is + reported to the maintainer. Owner tests refuse each combination that reads or is + enabled and remove an unreadable, disabled one with the live row untouched; adapter + tests refuse a readable, an enabled and an unreadable-enabled broker without sending + a delete; the real provider refuses an enabled unreadable broker, accepts it once + disabled, and a mutation sweep kills the dropped conditions. +- **A failure after the change could still say "nothing changed".** The owner tracks + whether a change may have landed. Any non-fatal failure after that point (the + provider call, the completion row, its commit, the handle's disposal, an unexpected + provider failure, a cancellation) is the unknown outcome with the failure kept as its + cause for warning 7110, and a completion that cannot be written is no longer swallowed + silently. The completion budget is injectable, so the owner tests cut a hung write in + two hundred milliseconds and otherwise run on a generous one. Tests fail the commit + with a connection fault, a closed transaction and a timeout, hang the write, fail the + disposal, throw from the provider after the send, abort the caller during a disable, + and have the provider find the broker already gone. +- **A wider intent-commit catch.** It excludes the fatal exceptions, and a test closes + the connection between the intent row and its commit. +- **Public surface.** Only the transient-fault classifier of the recovery fault helper + is public. +- **Record against behaviour.** The runbook's live-row exception, the review a disable + owes, the read of one alias that does not exist, the entry-row audit failure, the + paging that shifts when a remove shortens the provider's list, the refusal table of + operator access, the Standard 05 sentence that said the table is granted to the + application role only, the glossary, and the served contract (a description of the + report and its unread count, the removal rule, the federation runbook, a pinned + document test) are corrected. Three lines over eighty-eight columns are reflowed. +- **Test gaps.** The composition tests resolve the operator's port closed without the + secret and as its own adapter with its own pipeline with it; the tokenizer behind the + pinned listing query also refuses a query built through a builder or a property; the + `not_found` body, the already-applied-after-intent case, the unread count of the + first report test and the listing that runs out of time are asserted. + +Decided and not changed: + +- **A completion lost after a certainly applied change answers `503` + `outcome_unknown`,** not a `200` with a marker: the record is the one thing known to + be missing, and the runbook says a repeat answers `already_applied` with no review + owed, so the operator keeps their own record. +- **An unknown enum member in the route throws.** It is a defect to see (a `500`, which + the contract says may follow a landed act), and every member is covered today. +- **The budget's disposal is not bounded** after a failed commit; Npgsql's own command + timeout applies, and no test showed a hang. +- **Offset paging.** The cursor stays an offset; the runbook says to read a page again + after acting on it. + +### P03-9 Step 5 — verification and closeout (2026-11-21) + +The final head of Step 5 passed every suite: 4,387 unit tests; 500 fast and 180 heavy +architecture tests, the heavy set including the lifecycle-census tests round 1 had +extended; and 4,884 integration tests against real PostgreSQL and the pinned Keycloak +26.7.5. Document lint, the fragment audit and the delivery-log index are clean, and a +mutation sweep over the guards of both review rounds killed every mutant but one +equivalent (a marker length check that the marker's round trip makes redundant). + +Two full integration runs of this head failed for the host and not for the code, and +are recorded so a later reader does not read them as a defect. The first lost the +container runtime's API mid-run (every failure a cancelled Docker request within a +millisecond); the second could not start its Keycloak fixtures in the fixed two-minute +window while the workstation was swapping nine of ten gigabytes. The run that counts +is the third, serialized with `xUnit.ParallelizeTestCollections=false` so that one +provider container exists at a time, and it took two hours and five minutes where the +parallel runs took about an hour and a half. + +The gate rows G13 and G14 of the decision register now say the implementation is +delivered, and the Status block says Step 5 is delivered and twice reviewed. What +remains of the packet is its merge closeout. + +Open for the maintainer, as recorded in Amendments 12 and 13: + +- **The audit outcome of a completion row is `success` for every closed provider + outcome.** A query for non-success rows misses a refused or uncertain provider call; + the provider outcome is `after_state.outcome`. +- **The marker's tenant is not checked against `tenants`.** Planting a marker needs + realm-console rights, which exceed a tenant administrator's. +- **The removal of an unreadable owned broker with a live row needs it disabled first.** + This narrows the choice the maintainer made in review round 1, because the premise + that an unreadable broker already fails closed was wrong. + +### P03-9 Step 5 — hosted CI correction (2026-11-21) + +The first hosted run of the pull request failed every backend job at the build, and the +verification record above did not catch it because the local runs never built with +`CI=true`. That setting turns analyzer warnings into errors +(`backend/Directory.Build.props`), so a plain local build shows them as warnings and the +suites ran against a tree the hosted gate refuses. The frontend, document, OpenAPI, +demo and secret-scan jobs passed. + +Two analyzer errors, both in Step 4 code and both hidden one behind the other, because +the first stopped the project every later project depends on: + +- **CA1068** in `DeliveryInspection.PageAsync`: the cancellation token preceded five + delegate parameters. It is now the last parameter. +- **CA1822** in the delivery-inspection integration test: the `Admission` helper read no + instance data. It is now static. + +Neither changes behaviour. The corrected tree builds clean with +`CI=true dotnet build LearnStack.slnx -c Release --no-incremental`, and the 136 +integration tests that exercise delivery inspection and the operator HTTP surface pass. +The record above stands for what it measured; this entry owns what it did not. The +build with warnings as errors is now part of the gate before any push of this packet. + +### P03-9 Step 5 — hosted CI correction, second run (2026-11-21) + +With the build repaired, the second hosted run passed the build and 17 of the 19 backend +jobs, and failed two for different reasons. + +- **`backend-base`: `completed_case_unexpected`.** Two Step 1 theories took a parameter + xUnit cannot serialize, an `Exception?` and a `PlatformOperation`. Discovery lists such + a theory as one case, execution reports one result per data row under that same id, + and the hosted protocol refuses the second completion of an id. The last completed case + in the log, the first row of the exception theory, is where it stopped, after 395 of + 5,037 planned cases, so nothing after it had run. Both theories now take a serializable + key, a label and an audit slug, and build the object inside the test; discovery lists 16 + and 5 distinct cases for them. No local run could see this, because a local run reports + per row and the check lives in the hosted protocol only. +- **`backend-ordinary-9`: a Keycloak readiness timeout.** The one failed case, + `TenantRealmStockBaselineTests.Historical_stock_ordinary_reconciliation_…`, recorded + `readiness_timeout` at `provider_starting`, 120,001 ms and a TLS readiness outcome. It + is the hosted start-up flake already seen on this packet's earlier heads, in a test of an + older packet that passes locally; no code changed for it. + +Before pushing, the names a project discovers were compared with the names it executes for +all three assemblies of the base partition (4,387 unit, 656 integration without Docker, 13 +contract). They match, apart from the TRX escaping of surrogate pairs. A parameterised +theory that discovers as one case is the failure to look for, and the sweep over 1,398 +theories found only those two. The gate before any push of this packet is now the build +with warnings as errors and this comparison. + +### P03-9 Step 5 — hosted CI correction, third run (2026-11-21) + +The third hosted run passed the build, `backend-base` and every shard but one. The one +failure, `backend-ordinary-11`, was the hang-up case of +`IdentityAuthorityRebindToolTests.A_Signal_During_The_Realm_Read_…`, a Step 3 test; its +terminate case passed. The hosted record keeps no message for it, so the case was run in +an Ubuntu 24.04 container, the hosted distribution, against a real PostgreSQL. It passed +alone and ten times in a row, and failed once in ten under CPU load with the tool's own +line: `refused_live_sessions sessions=1` where the test expected `refused_cancelled`. + +The cause is the test, not the tool. The tool writes its intent row, then counts the +sessions of every runtime role, then reads the realm. The test took the appearance of the +intent row as the instant to signal, and polled for it as `learnstack_platform`, a role +the count includes. When a poll connection was still open as the tool counted, the tool +saw a live session and refused the run, which is what it exists to do. The signal never +had a chance to cancel a run that was already refused. The race needs load to show, which +is why every local run passed. + +The test now waits for the realm's hung discovery request to arrive. That request is made +only after the row is written and the sessions are counted, so it is the instant the signal +is meant for, and the test holds no database session while the tool counts. Under the same +load the hang-up case then passed 40 times in 40. The helper that polled for the row had no +other caller and is removed. The tool did not change. + +### P03-9 Step 5 — hosted CI, the opposite shard layout (2026-11-21) + +Head `82d18d8d` passed all 27 jobs in layout A (run attempt 1). Rerunning every job, as +[ADR-0063](../decisions/0063-complete-bounded-ci-test-shards.md) requires for the second +qualification, ran layout B (attempt 2) and failed two producers, for different reasons. + +- **`backend-ordinary-11`: `filter_bound`, no test ran.** The filter that lists the + shard's selectors came to 33,367 bytes against the 32,768-byte ceiling. It was computed + with the repository's own `assign` and `filter_for` over the run's discovery manifest and + the committed plan: layout B gives the twelve ordinary shards 21,794 to 33,367 bytes, with + `ordinary-7` at 31,989; layout A gives 27,144 to 28,123. Assignment is deterministic from + the manifest and the plan, so every layout-B attempt on this source refuses the same way + and a rerun cannot pass. The population is 2,052 distinct ordinary selectors; twelve + shards at the ceiling hold about 2,300 even when perfectly balanced, so the ceiling + binds layout A as well within a modest amount of further growth. +- **`backend-ordinary-7`: a Keycloak readiness timeout.** `readiness_timeout` at + `provider_starting`, 120,002 ms and a TLS readiness outcome at the first fixture, + failing the realm tests that share it. This is the hosted start-up flake already + recorded on this packet's earlier heads; no code is implicated. + +Nothing was changed for the first. ADR-0063 bounds filter arguments to 32 KiB, the +ordinary shards to eight through twelve (twelve are in use), and requires a reviewed plan +revision, an assignment diff and fresh qualification for any change of count, bound, +algorithm or salt. Whether to revise the plan, change the bound or reopen the decision is +the maintainer's. The candidates are a new B salt (cheap, and a lucky rebalance that the +next growth undoes), a byte-aware assignment (an algorithm version), a higher bound (which +the hosted boundary must then qualify) or a thirteenth shard (the envelope's end, which +reopens the decision). Until one is chosen, layout A is qualified on this source and layout +B is not. + +### P03-9 Step 5 — a local guard for unserializable theory data (2026-11-21) + +The maintainer asked for a guard that shows locally what only the hosted discovery +protocol showed: a theory whose data xUnit cannot serialize. The rule already exists. The +`xunit.analyzers` package that comes with xUnit 2.9.2 ships `xUnit1044` (the type argument +is not serializable) and `xUnit1045` (it might not be), both off by default. A scratch +theory with the two original shapes, a `PlatformOperation` record and an `Exception?` in +`TheoryData`, fails the build with them at error severity: `xUnit1044` for the first, +`xUnit1045` for the second. With both set to error in `backend/tests/.editorconfig`, the +whole solution builds with no warning and no error, so no existing theory breaks the rule. + +This replaces the reflection rule the question proposed. An analyzer knows what xUnit can +serialize, shows the fault in the editor and needs no catalogue entry, and the architecture +catalogue and its counts are unchanged. Standards 06 states the rule beside the +discovery protocol it protects. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 74b49ce04..eb95ac64c 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -1,6 +1,6 @@ # Phase 03: Identity Domain, Authorization, and Admin Foundation -> **Status (2026-11-18).** P03-0 through P03-7 implementation delivery is complete; +> **Status (2026-11-19).** P03-0 through P03-8 implementation delivery is complete; > Phase 03 remains in progress. Packet closeouts below own the delivered scope. > P03-7 is merged in [PR #44](https://github.com/HodeTech/LearnStack/pull/44) under > Accepted [ADR-0098](../decisions/0098-session-targeted-back-channel-logout.md). @@ -18,7 +18,13 @@ > acceptance covers earlier UI, with later fixes also lacking fresh human evidence. > P03-6/P03-7 add no new manual UI gate. Earlier intermittent CI causes remain > unlocalized except where the dated records establish a specific correction. -> P03-8's design is [accepted in ADR-0099](../decisions/0099-confined-tenant-federation.md) and G12 is closed as Accepted. Step 1 (authority and storage) is committed with its first and second review rounds' corrections; Step 0 moved the Keycloak pin to 26.7.5 ([ADR-0099 Amendment 2](../decisions/0099-confined-tenant-federation.md#amendment-2--keycloak-pin-decision-2026-11-13)); Steps 2 and 3 are committed under their own approvals; Step 4 (native and Studio) is committed with [Amendment 6](../decisions/0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14), its first review round is corrected with [Amendment 7](../decisions/0099-confined-tenant-federation.md#amendment-7--step-4-review-purposes-test-freshness-and-detail-loads-2026-11-15) and its second with [Amendment 8](../decisions/0099-confined-tenant-federation.md#amendment-8--step-4-review-round-2-test-session-replacement-and-scope-confinement-2026-11-15). PR #45 is open, its OpenAPI contract transition is [accepted in ADR-0100](../decisions/0100-p038-federation-contract-transition.md) and the hosted pinned approval passed at `cd71cb6d`, and its review findings are corrected with [Amendment 9](../decisions/0099-confined-tenant-federation.md#amendment-9--pr-review-behavior-corrected-to-this-record-and-decisions-recorded-2026-11-18). P03-9–11 remain unstarted. +> P03-8 is merged in [PR #45](https://github.com/HodeTech/LearnStack/pull/45) under Accepted +> [ADR-0099](../decisions/0099-confined-tenant-federation.md) (Amendments 1–9) and +> [ADR-0100](../decisions/0100-p038-federation-contract-transition.md). Its +> [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) records +> final-head `5eeba2c3` layout A (27/27, attempt 3). Opposite-layout B/pair +> qualification stays open before P03-11 exit; manual accessibility was not performed. +> G12 is closed as Accepted; G20 stays Open. P03-10 and P03-11 remain unstarted. > > | Packet | Title | State | > |---|---|---| @@ -30,8 +36,8 @@ > | P03-5 | Custom fields and privacy classification | Complete and merged — [closeout](phase-03-delivery-log.md#p03-5-merge-and-delivery-closeout-2026-11-11); final-head A/B and all original archives verified; manual-evidence boundary retained | > | P03-6 | Provider event ingress and audit mirror | Complete and merged — [closeout](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | > | P03-7 | Back-channel session revocation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12); final-head opposite-layout/pair qualification remains open | -> | P03-8 | Tenant federation | In progress — PR #45 open; its contract transition is [accepted in ADR-0100](../decisions/0100-p038-federation-contract-transition.md), [record](phase-03-delivery-log.md#adr-0100-maintainer-review-disposition-and-acceptance-2026-11-18), and the hosted pinned approval passed at `cd71cb6d`; PR review findings corrected, [record](phase-03-delivery-log.md#p03-8-pr-review-disposition-2026-11-18); Step 4 (native and Studio) implemented, [record](phase-03-delivery-log.md#p03-8-step-4--native-and-studio-2026-11-14); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-4-review-round-1-corrections-2026-11-15); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-4-review-round-2-corrections-2026-11-15); Step 3 (provider and realm) implemented in `d166e12d`, [record](phase-03-delivery-log.md#p03-8-step-3--provider-and-realm-2026-11-14), [commit correction](phase-03-delivery-log.md#p03-8-step-3-commit-and-log-correction-2026-11-14); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-3-review-round-1-corrections-2026-11-14); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-3-review-round-2-corrections-2026-11-14); Step 2 (application and API) implemented, [record](phase-03-delivery-log.md#p03-8-step-2--application-and-api-2026-11-13); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-2-review-round-1-corrections-2026-11-14); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-2-review-round-2-corrections-2026-11-14); Step 1 (authority and storage) implemented, [record](phase-03-delivery-log.md#p03-8-step-1--authority-and-storage-2026-11-13); review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-1-review-round-1-corrections-2026-11-13); review round 2 corrected, [record](phase-03-delivery-log.md#p03-8-step-1-review-round-2-corrections-2026-11-13); Step 0 (Keycloak pin to 26.7.5) implemented, [record](phase-03-delivery-log.md#p03-8-step-0--keycloak-pin-move-2026-11-13); Step 0 review round 1 corrected, [record](phase-03-delivery-log.md#p03-8-step-0-review-round-1-corrections-2026-11-13); its round 2 is recorded in the PR review disposition. Design: [ADR-0099](../decisions/0099-confined-tenant-federation.md) | -> | P03-9 | Platform authority and operational recovery | Not started | +> | P03-8 | Tenant federation | Complete and merged — [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19); final-head opposite-layout/pair qualification and manual accessibility evidence remain open; the contract-transition items, G20 and the Phase 11 realm items are owned in the closeout | +> | P03-9 | Platform authority and operational recovery | Decisions Accepted — [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); implementation in progress: Step 1 (operator authority and killswitch), Step 2 (production onboarding), Step 3 (controlled issuer rebind), Step 4 (operator recovery of asynchronous work) and Step 5 (federation operator steps) delivered and twice reviewed; the merge closeout remains | > | P03-10 | DSAR and global account closure | Not started | > | P03-11 | Exit enforcement | Not started | @@ -104,7 +110,7 @@ activation is not the only decision boundary. | P03-6 | Authenticated durable provider ingress and attributed, deduplicated Audit mirror | P03-1–2 | G10; G13 before any privileged/global intake the chosen mechanism requires | | P03-7 | Registered, authenticated back-channel logout with bounded provider/session indexes | P03-3 | G11; provider event mirroring is a distinct contract, not a prerequisite by filename | | P03-8 | Usable tenant SAML/OIDC configuration with safe linking and recovery | P03-3 | G12; G1/G4/G5 still bound issued identity and authority | -| P03-9 | Admitted Platform gate, production first-admin/issuer-rebind authority, killswitch, fenced recovery and dashboard | P03-2 | G13, G14; privileged execution remains closed until this contract ships; also owns the [ADR-0099](../decisions/0099-confined-tenant-federation.md) federation operator steps: the orphan-broker sweep, the operator disable of a broker the tenant cannot reach, and the delegated-account review | +| P03-9 | Admitted Platform gate, production first-admin/issuer-rebind authority, killswitch, fenced recovery and inspection (no dashboard) | P03-2 | G13, G14; privileged execution remains closed until this contract ships; also owns the [ADR-0099](../decisions/0099-confined-tenant-federation.md) federation operator steps: the orphan-broker sweep, the operator disable of a broker the tenant cannot reach, and the delegated-account review | | P03-10 | Subject-scoped DSAR, usable export, tenant erasure and separately authorized global closure/redaction | P03-3, P03-5, P03-9 | G15, G16; G10 only if this workflow consumes provider ingress; integrate all applicable delivered stores, including `federation_connections` and its broker ([ADR-0099](../decisions/0099-confined-tenant-federation.md)) | | P03-11 | Complete source-bound evidence, gateway scaffold correction and analyzer escalation | All implementation packets | G17, G18; no pending mandatory deliverable or unqualified production subject | @@ -143,15 +149,15 @@ named part, and the register links each explicit acceptance and vehicle. | G9 | How do field definitions and values preserve schema/classification history? | Decide revision pins/active uniqueness, scalar-field compatibility with the existing admitted object profile, nested data, required/default/retire/reclassify/key-reuse behavior, consent and supported localized forms; no raw JSONB bypass | P03-5 before its schema | Customization/privacy contract; ADR-0043 disclosure or successor if needed; module specs | Accepted — 2026-11-10, [ADR-0095](../decisions/0095-revision-pinned-membership-custom-fields.md) and [corrected package](phase-03-delivery-log.md#p03-5-conditional-acceptance-and-step-1-start-2026-11-10); implementation/qualification remain separate | | G10 | What authenticated durable provider ingress is selected, and how are global events attributed? | Name producer, acknowledgement, stable provider-event dedup, ordering, tenantless/multi-membership routing, privacy and retention; enqueue through outbox, never direct business publication; no invented tenant or privileged app consumer | P03-6, or an earlier mechanism needing ingress | Provider-event ADR; ADR-0046/0057 boundaries, exact grants and Audit subscription | Accepted — 2026-11-11, [ADR-0097 and corrections](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11); [delivery and evidence record](phase-03-delivery-log.md#p03-6-merge-and-delivery-closeout-2026-11-12) | | G11 | Which back-channel token profile, route and session targets are supported? | Separate OIDC purpose validation, signature/issuer/audience/time/events/no-nonce, replay retention, provider/session indexing and reachability; preserve late-work/accounting fences and unrelated/new session owners | P03-7 | ADR-0070 bounded extension; native route/provider configuration package | Accepted — 2026-11-12, [ADR-0098 and reviewed package](phase-03-delivery-log.md#p03-7-maintainer-review-corrections-and-acceptance-2026-11-12); implementation delivery is merged, with final-source evidence and the remaining pair qualification in the [closeout](phase-03-delivery-log.md#p03-7-merge-and-delivery-closeout-2026-11-12) | -| G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | Accepted — [ADR-0099](../decisions/0099-confined-tenant-federation.md), 2026-11-13, with the [package](phase-03-delivery-log.md#p03-8-proposed-tenant-federation-package-2026-11-13) records; implementation and qualification remain open | -| G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Open for human/operator authority; machine-ingress slice only Accepted — 2026-11-11 under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) and its [acceptance](phase-03-delivery-log.md#p03-6-maintainer-review-corrections-and-acceptance-2026-11-11) | -| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Open | +| G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | Accepted — [ADR-0099](../decisions/0099-confined-tenant-federation.md), 2026-11-13, with the [package](phase-03-delivery-log.md#p03-8-proposed-tenant-federation-package-2026-11-13) records; implementation delivery is merged, with evidence and follow-ups in the [closeout](phase-03-delivery-log.md#p03-8-merge-and-delivery-closeout-2026-11-19) | +| G13 | How does the operator population authenticate a specific Platform act and retain human attribution? | Resolve ADR-0036's internal-chain rule and undecided platform URL space, tenant/Hub realm separation, no-Hub baseline, service versus human actors, MFA/reason, denied-entry evidence, production first-admin/provisioning and exceptional recovery, controlled issuer rebind and retained-connection lifetime; a new Hub crossing needs a coordinated ADR | P03-9 or first earlier privileged consumer | Operator authority ADR; bounded disclosures/supersession in affected Accepted records; Platform gate contract | Accepted — 2026-11-19, [ADR-0101](../decisions/0101-platform-operator-authority.md), [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); the machine-ingress slice was Accepted earlier under [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md); implementation delivered by P03-9 Steps 1 to 3 and 5 (packet state in the Status block) | +| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Accepted — 2026-11-19, [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) with the [record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19); no dashboard is admitted; implementation delivered by P03-9 Step 4 (packet state in the Status block) | | G15 | Who may request which person's data in which tenant/org scope and for which recipient/purpose? | Separate self/admin/delegate authority, subject predicates and org boundaries; category is not disclosure authority; resolve third-party data, holds, eligibility and post-erasure status access | P03-10 request writer | Data Protection/Identity request contract and module matrices | Open | | G16 | How do exports, closure and privileged redaction finish durably? | Decide artifact delivery/reauthorization/expiry, job/storage prerequisites, participant inventory/write fence, last-membership case and provider finalization; exact erasure grants/order/immutable references, user-reference locators and result-audit/inbox reconciliation | P03-1 only for shared closure-fence invariants; P03-10 workflow | Data Protection and ADR-0044/0046 privileged contract; migrations, module participation and phase package | Accepted shared fence; P03-10 workflow Open | | G17 | Which real production subjects and product journeys prove complete phase exit? | All deliverables/criteria, inherited catalogue clauses, no skips/empty censuses, real provider/native/app-role paths, manual accessibility and complete source-bound CI; analyzer escalation stays at exit | P03-11; packets retain their own proof | Phase package, evidence index, catalogue and existing test owners | Open | | G18 | Which gateway scaffold corrections ship without activating the gateway? | Apply Architecture 30 Rules 1–3: explicit version paths/priorities and separated credentials; retain disabled OIDC; reviewed per-public-read allowlist, lint and activation stay Phase 11 | P03-11 config writer | Phase package and Architecture 30; ADR-0035 trigger unchanged | Open | | G19 | How is personal-data classification and diagnostic redaction established before the first identity writer? | Census current PII-bearing subjects and missing-annotation control; distinguish snapshot markers from logs/errors; fixed descriptors and value canaries, including arbitrary nested values; custom-field history remains G9 | P03-1 first personal-data writer; P03-5 extends it | Data Protection, ADR-0044/0057 boundaries and module PII/audit specs | Accepted; current/global/contextual model classification and actual Identity diagnostic sink controls implemented and reviewed; custom-field history remains G9 | -| G20 | How does the closed administration grant contract grow after P03-8, when the pinned OpenAPI gate refuses every further assignable permission key? | [ADR-0100](../decisions/0100-p038-federation-contract-transition.md) measures the candidates: a transition record per release, a standing registry-growth rule enforced by the gate, or an open-key grant contract. Appending new union branches removes the positional companion findings under any of them and needs a registry-release contract the OpenAPI document builder does not have today. It also decides whether review of the carrier, decision and gate files becomes mechanical, for example with an owners rule | The first packet after P03-8 that adds an assignable permission key or alters the grant unions' bytes; P03-9 or P03-10 earliest | Maintainer decision: an ADR and, where it changes the gate, its controls | Open | +| G20 | How does the closed administration grant contract grow after P03-8, when the pinned OpenAPI gate refuses every further assignable permission key? | [ADR-0100](../decisions/0100-p038-federation-contract-transition.md) measures the candidates: a transition record per release, a standing registry-growth rule enforced by the gate, or an open-key grant contract. Appending new union branches removes the positional companion findings under any of them and needs a registry-release contract the OpenAPI document builder does not have today. It also decides whether review of the carrier, decision and gate files becomes mechanical, for example with an owners rule | The first packet after P03-8 that adds an assignable permission key or alters the grant unions' bytes; P03-10 earliest, because P03-9 adds only non-assignable Platform keys | Maintainer decision: an ADR and, where it changes the gate, its controls | Open | ### Entry and activation boundaries @@ -497,17 +503,18 @@ and provider token refresh alone cannot establish application permission freshne [Security Standards § Tenant Context](../standards/11-security.md). `Tenant_Scope_Widening_Is_Never_Set_From_Request_Input` becomes non-vacuous here. -- **The Platform-scope permission, and the writer it unlocks.** `EnterPlatformAdminScope` - is gated by `IPlatformAdminGate`, registered since - [Phase 02a Packet 9](phase-02a-kernel-tenancy.md) as `DenyAllPlatformAdminGate`, which - refuses everyone — so every operation that needs the scope is unreachable, every - killswitch toggle included. This phase replaces it with a gate that reads a - Platform-scope permission, and ships with it the killswitch toggle command, its - permission key and its incident runbook: the writer Packet 9 withheld on purpose +- **The Platform-scope permission, and the writer it unlocks.** The platform scope was + gated by a gate registered since [Phase 02a Packet 9](phase-02a-kernel-tenancy.md) + that refused everyone, so every operation that needs the scope, every killswitch + toggle included, was unreachable. This phase replaces it with the operator authority + of [ADR-0101](../decisions/0101-platform-operator-authority.md): an admission minted + for an authenticated operator who holds a Platform grant, and with it the killswitch + writer, its permission key and its incident runbook: the writer Packet 9 withheld on + purpose ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). - [Permissions](../standards/19-permissions.md) reserves no killswitch or entitlement key - yet, so reserving them is part of the work. The toggle's row is already classified — - `tenancy.killswitch.toggle`, `(off-path)` `(planned)`, MUST, in the + [Permissions](../standards/19-permissions.md) registers `platform.killswitch.write`; + an entitlement key joins with the operation that uses it. The toggle's row is + classified — `tenancy.killswitch.toggle`, `(off-path)`, MUST, in the [Tenancy matrix](../modules/tenancy/audit.md). - **Audited job quarantine inspection and reconciliation.** ADR-0047 assigns this @@ -552,34 +559,32 @@ browser-supplied tenant/org authority is not admitted by adding an admin screen. ### Operator recovery and dashboard admission -P03-9/G13 also owns the production first-admin and controlled issuer-rebind -authority defined by ADR-0072/0073. Before production onboarding, -qualify an admitted operator creating the finite Role templates in separate -transactions, then the first tenant-wide admin Membership with MUST audit. -Specify authorized retry after partial setup, wrong-tenant/operator denial, -unknown-COMMIT reconciliation and recovery without the development seed -capability. Tenancy provisioning remains its Tenant/default Organization pair. -An issuer rebind needs proven provider continuity and frozen admission, preserving -AuthorityId, actor IDs and tombstones; no production rename path exists before -this contract is accepted and delivered. Seed-backed P03-3 journeys may be -qualified earlier; they are not production onboarding proof. - -Phase 02b supplies internal targeted subscriber replay and no operator route. -This phase owns the operator outbox/dead-letter/subscriber-replay and job-recovery -surface. Before its first writer, settle the URL space under ADR-0036, exact -Platform-scope permission, reason, fenced transition and MUST audit/runbook; -producer reset is not an implied power of targeted subscriber replay. - -This phase also owns the application `/admin/hangfire*` mapping and its -Platform-scope permission. Append the dated ADR-0015 disclosure before replacing -its historical realm-role gate. Keycloak roles are not LearnStack authority. -Keep the route absent until the application gate and denied-route controls ship. +P03-9 delivers G13 and G14 under [ADR-0101](../decisions/0101-platform-operator-authority.md), +[ADR-0102](../decisions/0102-production-tenant-onboarding.md), +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md); the +[acceptance record](phase-03-delivery-log.md#p03-9-package-review-dispositions-and-acceptance-2026-11-19) lists their dispositions. + +Production onboarding is operator-admitted commands on the app role: provision a Tenant +with its default Organization and hosts, create the finite Role templates in separate +transactions, create the first tenant-wide administrator Membership with MUST audit, and +recover a tenant that has none, with authorized retry after partial setup, wrong-tenant +denial and unknown-COMMIT reconciliation. The development seed capability is +insufficient. The controlled issuer rebind is an offline operator act that preserves +AuthorityId, actor IDs and tombstones; no other rename path exists. Seed-backed P03-3 +journeys may be qualified earlier; they are not production onboarding proof. + +Phase 02b supplied internal targeted subscriber replay and no operator route. ADR-0103 +admits metadata inspection, fenced targeted subscriber replay and a narrow producer +reset that is not an implied power of subscriber replay. Job requeue, reservation +release and recurrence recovery are not admitted, and no dashboard is mapped: +`/admin/hangfire*` stays absent in every deployment mode, and ADR-0015 Amendment 2 +withdraws its realm-role gate guidance. Keycloak roles are not LearnStack authority. Phase 11 owns APISIX defense in depth and gateway activation. -The first Platform-admin consumer must decide denied-entry evidence and enforce -connection lifetime: a connection retained after scope completion must not permit -an autocommit bypass. The current deny-all gate exposes no privileged consumer; -an admitted scope's entry row is not evidence of a denied attempt. +ADR-0101 decides denied-entry evidence, a counter and a log with no durable row, and the +handle contract that stops a connection retained after scope completion from running an +autocommit bypass. An admitted scope's entry row is not evidence of a denied attempt. ### Gateway Configuration Corrections @@ -801,8 +806,8 @@ identifies observable proof; a later packet completes dependent end-to-end paths | D09 | Authenticated durable provider-event ingress, identifier-only outbox facts and deduplicated Audit mirror | P03-6 | C11, C19 | | D10 | Authenticated OIDC back-channel logout, provider/session indexes and fenced local revocation | P03-7 | C12 | | D11 | Confined tenant federation configuration, safe linking, test/activate/rollback and recovery | P03-8 | C13, C20 | -| D12 | Platform-scope identity/permission gate, production first-admin/issuer rebind, attributed bypass, killswitch writer and runbook | P03-9 | C14, C19 | -| D13 | Fenced operator recovery and application Hangfire dashboard admission, exact permissions/grants/audit/runbooks | P03-9 | C15, C19 | +| D12 | Platform-scope identity/permission gate, production first-admin/issuer rebind, attributed bypass, killswitch writer, federation operator steps and runbooks | P03-9 | C14, C19 | +| D13 | Fenced operator inspection, subscriber replay and narrow producer reset, with the Hangfire dashboard decided absent, exact permissions/grants/audit/runbooks | P03-9 | C15, C19 | | D14 | Self/admin tenant-scoped DSAR requests, usable export/erasure, separate person-authorized global closure and privileged redaction | P03-10 | C17, C18, C20 | | D15 | Trusted audit request/actor enrichment, sensitive-read/denied coverage and user-reference locators | P03-2; P03-10 locator/redaction completion | C19 | | D16 | Corrected inactive gateway scaffold, LS0001/LS0002 Error, complete catalogue and source-bound exit evidence | P03-11 | C21 | diff --git a/docs/roadmap/phase-11-production-hardening.md b/docs/roadmap/phase-11-production-hardening.md index ab3853d00..29f2177cb 100644 --- a/docs/roadmap/phase-11-production-hardening.md +++ b/docs/roadmap/phase-11-production-hardening.md @@ -321,6 +321,17 @@ bounds request *cost* once a request is inside. Neither substitutes for the othe - Confirm-link page copy. The realm ships no localization text or theme, so the page that confirms a link is Keycloak's own and does not state the delegation risk; this phase owns the production realm theme that does. +- Platform operator surface + ([ADR-0101](../decisions/0101-platform-operator-authority.md) to + [ADR-0104](../decisions/0104-controlled-issuer-rebind.md)). This phase decides gateway + exposure of `/api/platform/v1`, which the scaffold does not route; enforces MFA for + the operator client in the production realm, because LearnStack checks the claim but + the realm must issue it; builds the database adapter for operator grants on its + trigger, audited runtime grant changes; pins the operator OpenAPI document under a + gate of its own; decides durable denial evidence if security monitoring requires it; + alerts on the operator counters; and owns the read-only dashboard decision, job + reconciliation and recurrence recovery that + [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) leaves absent. - Secret management: Vault rotation cadence (90 days for provider keys, yearly for Hub HMAC shared secret + mTLS client certs), no secrets in repo, no secrets in env files committed. The Vault adapter itself lands in this phase — see @@ -460,7 +471,8 @@ not a request to add an unused module, adapter or port. `/healthz` proves liveness. Decide whether an unavailable IdP changes whole-instance readiness or authenticated-traffic admission, preserving the credential-free public contract. Keep IdP state, subject capacity and audit-store failure distinguishable. - Platform operations owns runbooks under `docs/runbooks/` for DNS/TLS/metadata failure, + Platform operations owns runbooks under `docs/runbooks/` (begun in Phase 03 for the + platform operator decisions) for DNS/TLS/metadata failure, signing-key rollout and withdrawal, authentication-volume spikes and capacity refusal. Each runbook names the signal, diagnostic access, safe recovery and an exercised recovery control before production activation. @@ -677,8 +689,12 @@ new erasure permission. - Soft delete and purge jobs. - Processed outbox, delivery, inbox and job-history purge decisions against the inventory. Among its first-party asynchronous tables, only - `outbox_messages` currently grants Platform SELECT/DELETE; - inbox, delivery and LearnStack job tables grant Platform no access. Immutable + `outbox_messages` grants Platform `DELETE`; Platform reads twelve metadata columns of + it, fifteen of `event_deliveries`, twenty-seven of `background_jobs` and every + column of `background_job_reservations` + ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)), and the + inbox grants it no access. A purge predicate that needs another column needs a + named grant or another principal. Immutable completion/execution facts and no-delete guards remain effective even with `BYPASSRLS`. Before the first purge writer, a bounded decision names the exact principal, minimum grants and required migration, eligible facts, dependency @@ -836,12 +852,15 @@ new erasure permission. and job alerts keep their own thresholds, and the three are asserted separately, with a runbook entry for each. - Each failure domain's recovery is asserted on its own path, because the two sides fail - independently and the job side is a third: a producer-side replay resets the row and - the next poll dispatches it, the consumer's guard absorbing the duplicate; a - subscriber-side replay resets one `(event, consumer)` pair, reaches that subscription - and no other, and a late success racing it is absorbed by `IInboxGuard`; and a - terminal job is recovered by requeue and runs once. Each case names the single effect - it expects, and each runs while a second pod holds the lease. + independently and the job side is a third: a producer-side reset + ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), + `retry_exhausted` rows only) clears the row and the next poll dispatches it, the + consumer's guard absorbing the duplicate; a subscriber-side replay resets one + `(event, consumer)` pair, reaches that subscription and no other, and a late success + racing it is absorbed by `IInboxGuard`; and a terminal job has no operator requeue, + because ADR-0103 admits none until a provider can prove quiescence, so its recovery is + the domain's own, for example invitation reissue. Each case names the single effect it + expects, and each runs while a second pod holds the lease. - Each asynchronous-store purge writer satisfies its bounded decision and exact migration/grant contract, using a named principal admitted by the required audited gate. Existing Platform outbox DELETE is not inbox, delivery or job diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md new file mode 100644 index 000000000..fe0343dec --- /dev/null +++ b/docs/runbooks/README.md @@ -0,0 +1,16 @@ +# Runbooks + +Operational procedures, one per failure or privileged act. Each names the signal, the +diagnostic access, the safe recovery and what is not recoverable. They live under +`runbooks/` per [Documentation Standards](../standards/13-documentation.md). Phase 03 +begins this directory with the platform operator runbooks; +[Phase 11](../roadmap/phase-11-production-hardening.md) completes the set. + +| Runbook | Use it when | +|---|---| +| [Platform operator access](operator-access.md) | An operator needs a token, a grant, or an answer to a 401, 403 or 503 | +| [Killswitch](killswitch.md) | A capability must be switched off for every tenant during an incident | +| [Tenant onboarding](tenant-onboarding.md) | A production tenant must be provisioned, mapped to a host and given its first administrator, or an administrator must be recovered | +| [Identity issuer rebind](identity-issuer-rebind.md) | The tenant identity provider keeps its realm and users but changes address, and the stored issuer must follow without re-keying anyone | +| [Operator recovery](operator-recovery.md) | An event or delivery is dead-lettered, a job is quarantined, and an operator must inspect it or reset one delivery or outbox row under a fence | +| [Federation operator](federation-operator.md) | A tenant's identity-provider broker is orphaned, unreadable or nonconforming, and an operator must report it, remove it or disable it, and an account review is owed | diff --git a/docs/runbooks/federation-operator.md b/docs/runbooks/federation-operator.md new file mode 100644 index 000000000..5a1ae4f25 --- /dev/null +++ b/docs/runbooks/federation-operator.md @@ -0,0 +1,300 @@ +# Federation operator: orphaned and broken brokers + +How an operator finds the identity-provider brokers a tenant's federation left +orphaned, unreadable or nonconforming, and removes or disables one. Decided in +[ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md), implemented +as Amendment 11 and corrected by Amendments 12 and 13. There is **no dashboard** and +**no way to list or remove a realm user**: this is an API and this document. + +## What exists + +| Route | Does | Permission | +|---|---|---| +| `GET /api/platform/v1/federation/brokers` | Reports one page of brokers that need an operator (a **report**) | `platform.federation.read` | +| `POST /api/platform/v1/federation/brokers/{alias}/remove` | Deletes an orphaned or unreadable owned broker at the provider (a **remove**) | `platform.federation.admin` | +| `POST /api/platform/v1/federation/brokers/{alias}/disable` | Sets `enabled=false` on a nonconforming or unreadable owned broker, at the provider only (a **disable**) | `platform.federation.admin` | + +Authentication, the token profile and how a grant is given are in [Platform operator +access](operator-access.md). The served operator document, `platform-v1`, is the +contract for these routes, and it is the only client there is. + +All three run on `ConnectionStrings:PlatformAdmin` and on the federation admin client +(`Federation:ClientSecret`; see the [adapter +specification](../modules/identity/providers.md#tenant-federation-adapter)). With no +client secret configured every call answers `503` at once and nothing is sent to the +provider. The report needs the Identity migration +`20261120160000_grant_platform_federation_projection` applied; without it the first +report fails with a permission error in the API's log. + +## Which brokers the platform may touch + +A broker is the platform's only when **both** hold: + +- its alias is `lsf-` and 32 lowercase hexadecimal characters, the form LearnStack + derives from a connection identifier, and +- its owner marker parses strictly to a tenant and a connection whose derived alias is + that alias. + +Everything else in the realm (an unmarked instance, a marker naming another connection, +an alias that is not LearnStack's) is **counted and never named**: the report's +`ignored` says how many, and no act accepts such an alias. + +A broker the platform may touch is reported in one or two classes (`orphan` combines +with either of the others): + +| Class | Meaning | +|---|---| +| `orphan` | No live connection row names it: the row is absent (`rowState` `absent`) or a tombstone (`deleted`) | +| `unreadable_owned` | The marker proves it LearnStack's and its representation no longer reads as an admitted OIDC or SAML broker | +| `nonconforming` | It reads, and differs from the fixed profile or carries a mapper ([Fixed broker profile](../modules/identity/providers.md#fixed-broker-profile)) | + +A broker that conforms and has a live row is not reported. + +## What is not here + +- **Listing or removing realm users.** No LearnStack credential may enumerate or remove + them ([ADR-0099 Decision Q1](../decisions/0099-confined-tenant-federation.md)). The + account review below is yours, with your own realm authority. +- **Removing a broker that reads, or one that is still enabled, while a live row names + it.** A remove is refused (`errors.connection`). Disable it here if it must stop now, + and let the tenant's own *Delete* retire the connection with its broker. The one + exception is a broker that does *not* read and is disabled: the tenant's own Delete + treats it as foreign and cannot, so nothing else can, and it is removed here. +- **Repairing a broker.** There is no rewrite from the fixed profile on this surface. + The tenant's next readback records a drifted broker's state on its own row and leaves + the broker as found; an unreadable one is disabled and then removed here. +- **A broker whose tenant is archived or deleted with a live row.** That is + [P03-10](../roadmap/phase-03-identity-admin.md)'s. +- **A provider-side fence.** A tenant's create that lands after a sweep produces a new + orphan, which the next report finds. + +## When to look + +- A tenant reports a sign-in option that does nothing, or a provider that was removed + in the tenant's own screen and still offers a button. +- A broker in the provider's console carries a LearnStack alias (`lsf-` and 32 hex + characters) that no connection in the tenant's own screen explains. +- After a failed tenant create or delete whose intent row has no completion row + (see [Check it worked](#check-it-worked)). +- As a periodic sweep: the report is read-only and cheap, so run it page by page. + +## Report + +Each page is one entered platform scope, so each page writes one +`platform.admin_scope.enter` audit row with the reason `federation_report`, your +attribution and your ticket. It does not say which page you read. Pass the ticket as +`?ticket=`: 1 to 64 letters, digits or `.` `_` `:` `/` `#` `-`, and percent-encode `#` +as `%23`. + +```sh +curl -s -H "Authorization: Bearer $TOKEN" \ + "$API/api/platform/v1/federation/brokers?limit=50&ticket=CHG-123" +``` + +- `limit` is 1 to 100 (default 20; a larger value is clamped, and zero or less is + refused with `errors.limit`). Only `limit`, `cursor` and `ticket` are accepted; any + other parameter is refused with `errors.query` and nothing is read. +- A page is one slice of the provider's own listing, `scanned` instances long, and the + answer holds `items` (the brokers on that slice that need attention), `scanned`, + `ignored`, `mappersUnread` and a `pageInfo` whose `nextCursor` you send back as + `cursor`. **An empty `items` with a `nextCursor` is not the end**: the slice held + nothing to report. Read until `hasNext` is false. A cursor belongs to this route. +- Each item carries `alias`, `tenantId`, `connectionId`, `classes`, `rowState`, + `protocol`, `enabled` and `mappers`. `mappers` is the count read on a live broker that + reads and conforms, where only a mapper can make it drift; `null` means it was not + asked (an orphan, an unreadable or a drifted broker already has its class). +- **`mappersUnread` is not clean.** An extra mapper is drift only a mapper read shows, + so the page reads the mappers of its healthy-looking live brokers one call at a time + within ten seconds. `mappersUnread` counts those it could not read (the provider + failed, its circuit was open or the time ran out): they are unknown, not cleared, and + no item names them. When it is not zero, read the page again, with a smaller `limit` + if it keeps running out of time. +- The realm is read **first** and the connection rows second, because a tenant writes + its row before it creates its broker. A tenant that creates a broker while your page + is being read cannot be taken for an orphan. A broker whose class is `orphan` on one + page can still gain a row before you act; the remove re-reads the row. +- A report the provider cannot answer is `503`, never an empty realm. + +## Choose: remove or disable + +| The broker is | Do | +|---|---| +| `orphan`, readable or not | **Remove** it | +| `unreadable_owned`, no live row | **Remove** it | +| `unreadable_owned` with a live row, still `enabled` | **Disable** it first. "Unreadable" is a shape check of one read, and an unreadable broker can still be serving sign-ins, so a remove is refused (`errors.connection`). The disable is reversible in the provider's console | +| `unreadable_owned` with a live row, `enabled` false | **Remove** it: the tenant's own Delete treats a broker that does not read as foreign and cannot reach it, so nothing else can. The provider proves again at the delete that it still does not read and is still disabled, or sends nothing (`errors.provider`). The tenant's row stays as it was and its next readback finds the broker absent, after which the tenant's own Delete completes | +| `nonconforming` with a live row | **Disable** it if it is a risk now; the tenant's next readback records the drift on its row and leaves the broker as found. The tenant's own Delete can remove it, because it reads; a remove here is refused | +| healthy with a live row | Neither: a disable is refused with `not_applicable` | + +A **remove** also deletes the broker's federated links, which is why [an account +review](#account-review-after-a-remove-or-a-disable) is owed. A **disable** changes +only `enabled` at the provider and keeps the links, but people who sign in only +through that broker cannot while it is disabled, so its review is smaller and is owed +too. Neither writes the tenant's connection row. + +## Act + +A ticket is optional and is checked, and **recorded only on the platform scope's entry +row** (a row of the platform sentinel, like the report's): the intent and completion +rows are readable by the tenant, so they never carry one. The body is `{}` or +`{"ticket":"CHG-123"}`. + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/federation/brokers/$ALIAS/remove" -d '{"ticket":"CHG-123"}' +``` + +Use `.../disable` the same way. + +Each act proves the owner marker at the provider and reads the connection row (a live +row refuses the remove of a broker that reads or is still enabled at once, and writes +no tenant row). It then writes an **intent** +row; a remove reads the row again, as the last check before the delete. It changes the +provider, reads it back, and writes a **completion** row on a bounded budget of its own, +so a client that leaves while the provider works does not lose the record. + +| Answer | Meaning | +|---|---| +| `200`, `outcome: applied` | The provider's change was made and confirmed. `accountReviewOwed` is `true`: a remove deleted the broker's federated links, and a disable closed it as a sign-in option, so people who signed in only through it need another way in | +| `200`, `outcome: already_applied` | The broker was already absent (remove) or already disabled (disable). Nothing was sent, and when it was so at the first read **no tenant row was written**; if it changed between that read and the provider call, the intent and completion rows exist and the completion says `already_applied` | +| `404` | A disable named an alias no instance has | +| `409`, `errors.owner` = `lockey_not_owned` | The instance's marker does not name a tenant and a connection of LearnStack's, or its row names another tenant. Nothing was touched | +| `409`, `errors.connection` = `lockey_live_connection` | A live connection row names the broker and it reads or is still enabled, so a remove is refused. Disable it first; a broker that does not read is then removable, and one that reads is retired by the tenant's own Delete | +| `409`, `errors.class` = `lockey_not_applicable` | A disable found a healthy owned broker with a live row | +| `409`, `errors.provider` = `lockey_provider_refused` | The provider definitively refused the change, or a remove that was let through for an unreadable, disabled broker found it reading or enabled again at the delete. Nothing changed | +| `400` | The alias is not a derived one, or the body or the ticket is malformed. A refusal at the gate carries no per-field errors | +| `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act): the credential, the grant (`platform.federation.admin` for an act), the body size or type, or the request budget | +| `503`, `audit_unavailable` | The scope's entry row (no intent row exists), or the intent row, could not be written or committed, or the completion of a change that did not happen could not be: nothing changed, though the intent row may stand alone. Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | The provider or the database could not be reached before any change was sent. Nothing changed. Retry after the delay | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | A change was sent and its answer was lost, the request was aborted while it ran, an unexpected failure followed it, or the completion that records it could not be written. It **may have landed**: see [An unknown outcome](#an-unknown-outcome). Warning 7110 in the API's log carries the failure | +| `500` | An unexpected failure or a deployment defect (a refused credential, a missing grant): the API's log names it | + +A client that never received an answer (a timeout, a gateway error) is in the same +position as an unknown outcome. + +## An unknown outcome + +There is no provider-side fence, so reconcile by reading, in this order: + +1. Read the report again from the same cursor (there is no read of one alias), or + look at the instance in the provider's console. A remove that landed leaves no + instance with that alias, so a report no longer lists it; a disable that landed + shows `enabled` false. +2. If it did not land, repeating the act is safe: it re-proves the marker and the row. +3. To tell your act from another operator's, read the tenant's audit rows by the + `correlationId` of the failed response, as in [Check it worked](#check-it-worked). + +A repeat of an act that had landed answers `already_applied` with `accountReviewOwed` +false, and writes no row; that alone cannot say whose act it was, and it does not say a +review is owed. **After an unknown remove that shows the broker gone, treat the account +review as owed**, and after an unknown disable that shows `enabled` false, treat the +smaller review (people who signed in only through it) as owed. The record is the +`remove_attempt` or `disable_attempt` row, with no completion row or with an +`uncertain` one. + +## Account review after a remove or a disable + +The provider deletes **the broker's federated links** with the broker and keeps the +accounts. A person who signed in only through that provider still has an account, and +has lost the way into it. A disable keeps the links, and the same people cannot use +them while the broker is disabled: review them the same way, and re-enable the broker +in the provider's console if the disable was a mistake. LearnStack cannot list or +repair these accounts, and Keycloak keeps link events for seven days only, so the +review is a realm administrator's, in the provider's own console under their own +authority: + +1. If the removal is not urgent, **note the linked users before you remove**: the + console lists a user's identity-provider links. For an unreadable, enabled broker + this is the time between the disable and the remove. +2. After the remove, review the accounts that depended on it: whether each has another + credential or sign-in route, and whether its sessions must be ended. +3. Tell the tenant's owner. No owner notification channel exists before + [Phase 08a](../roadmap/phase-08a-assessment-notifications.md), so this is by hand. + +An `accountReviewOwed` of `true` in the answer, and the same member in the completion +row's `after_state`, are the reminder for an applied or an uncertain act. A repeat of a +landed act answers `already_applied` with `false`, so keep your own record. Nothing in +LearnStack closes the review. + +## Check it worked + +1. Read the report again: the broker is gone (a remove) or shows `enabled` false (a + disable). +2. Read the audit trail. The rows are in the **tenant's** trail: they name the tenant + the owner marker names, even when no tenant row exists, with no actor, your + attribution in `metadata.operator` and **no ticket**. There is no audit API: read + them as the application role announcing the tenant, by the response's + `correlationId`, with the query and the digest recipe of [Tenant + onboarding](tenant-onboarding.md#reading-the-record). + - `platform.federation.remove_attempt` or `platform.federation.disable_attempt`, + outcome `indeterminate`, the **intent**, committed before the provider was + touched. Its `before_state` holds the broker's `classes` and the connection + row's `rowState`. + - `platform.federation.remove` or `platform.federation.disable`, outcome `success`, + the **completion**, whose `after_state` holds the closed `outcome` (`applied`, + `already_applied`, `refused`, `not_owned`, `unavailable` or `uncertain`) and + `accountReviewOwed`. +3. An **intent row with no completion row** is a completion that was lost: the provider + may have been changed. The next report resolves it, as step 1 does. + +A refusal before the intent (an absent broker, an unowned alias, a live row seen at +the first read, an unavailable provider) writes **no tenant row**: the scope's entry +row, `platform.admin_scope.enter` with the reason `federation_remove` or +`federation_disable`, records that an act was attempted and nothing is known to name a +tenant. A live row found only at the re-read after the intent writes both tenant rows, +and the completion says `refused` with the cause `live_connection`. + +## A 503 that does not clear + +Find the line in the API's host log by the response's `correlationId` (warning 7110; +it carries the operation and whether the outcome is unknown): + +- **The provider.** The federation admin client's token or an admin call failed. The + adapter never logs provider text, so the line names no cause: read the provider's own + server log, and the counter below (`outcome` `unavailable`). The adapter's circuit may + be open after repeated failures; it closes by itself. A `Federation:ClientSecret` that + is not configured, or one the realm refuses, never clears until it is fixed. +- **The database.** A transient fault of `ConnectionStrings:PlatformAdmin` (it cannot + connect, a timeout) is a `503`, and the line's exception holds the cause. A refused + credential or a missing grant is not transient: it is a `500` and the log names it. + +## Signals + +`learnstack_platform_operator_federation_total{operation,outcome}` counts every call +that reached the owner: a refused parameter, alias or body (a `400`) and a refused +credential are not counted, and an audit failure is counted by the audit-failure +counter. `operation` is `platform.federation.report`, `platform.federation.remove` or +`platform.federation.disable`; `outcome` is `ok`, `invalid_cursor`, +`applied`, `already_applied`, `not_found`, `not_owned`, `live_connection`, +`not_applicable`, `refused`, `unavailable` or `uncertain`. A rising `uncertain` means +completions are being lost or the provider is failing mid-change; a rising +`not_owned` is an operator naming aliases that are not LearnStack's. The admission, +refusal and audit-failure counters are in [Platform operator +access](operator-access.md#signals). Each report page logs the scope-entry line 7001, as +a killswitch act does. + +## Limits + +- **Pages are slices of the realm.** A realm with many instances takes many pages; + there is no filter by tenant, class or alias. The cursor is an offset into the + provider's list, and a remove shortens that list: **read a page again from the same + cursor after you act on it**, or sweep first and act afterwards, or an instance that + moved up is skipped. A page whose instances are unusually + large (over 1 MiB together) is refused as unavailable: lower `limit`. +- **The mapper reads are sequential.** Each costs a token and a call, so a page of many + healthy brokers can run out of its ten seconds; `mappersUnread` says so. +- **Disable is a read and a write.** The tenant's own write can interleave with it, and + the tenant's next readback detects the drift + ([ADR-0099 Amendment 11](../decisions/0099-confined-tenant-federation.md)). +- **A disable sends back what the provider returned.** An unreadable broker cannot be + rebuilt from the fixed profile, so the operator disable is the one provider write that + does not build its body from the allow-list. It changes `enabled` and nothing else, + and keeps the stored secret. + +## Not recoverable here + +- A broker with no marker, or a marker that is not LearnStack's: the realm + administrator's, in the provider's console. +- A federated link that a remove deleted. +- A realm user, a session, a credential or an owner notice. +- A dashboard. diff --git a/docs/runbooks/identity-issuer-rebind.md b/docs/runbooks/identity-issuer-rebind.md new file mode 100644 index 000000000..585635a46 --- /dev/null +++ b/docs/runbooks/identity-issuer-rebind.md @@ -0,0 +1,376 @@ +# Identity issuer rebind + +Moving the identity authority from one issuer origin to another, under the same realm +name, without re-keying a single person. Decided in +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md); the storage contract of the +confined role is in +[Database Standards](../standards/05-database.md#controlled-issuer-rebind-storage). +This is a planned, rare act with a downtime window. A development environment never +needs it. + +## When to use it, and when not to + +Use it when the deployment's tenant identity provider keeps its realm and its users but +changes address: a new host name, a new load balancer origin, a migration to another +cluster that preserved every user's `sub` (a realm export and import does). The path +before `/realms/learnstack` may change, for example from `/auth/realms/learnstack` to +`/realms/learnstack`; the realm name may not. + +It does **not** change the stable authority identifier, and it refuses a new realm that +would lose or resurrect a person. It cannot rename the realm, re-key users, merge two +providers or move a tenant between authorities. A new realm whose users have new `sub` +values is a different authority and is not reachable here: escalate before doing +anything. + +## What it needs + +| Needed | Why | +|---|---| +| An operator with a current token and the grant `platform.identity_authority.admin` | The same operator token and grant model as the other [operator acts](operator-access.md). The grant is read from the tool's own configuration when it runs, never from a claim. See [Two people](#two-people) | +| The sixth database role's connection string | `ConnectionStrings__IdentityRebind` for `learnstack_identity_rebind`, to PostgreSQL **directly**, never through a connection pooler: the tool's session settings and its lock belong to one physical session. It exists only in the tool's environment for the minutes it runs: never in an API, seeder or web configuration, and never in a file under version control | +| A read-only credential for the **new** realm | A confidential client with the single role `realm-management/view-users`, created for this run and deleted after it. It is not a LearnStack credential and is not in the realm export | +| The stable `Identity__AuthorityId` and the new `Authentication__Tenant__Issuer` | The same two values the deployment is about to run with. The authority must equal the stored one; the issuer is the target. Outside Development the target must be HTTPS | +| `Deployment__Mode` and the `PlatformOperator__*` settings | The same as the API's, so the tool validates the token against the same issuer, clients and assurance. The mode is read as the API reads it: a declared name, with case and padding ignored; an ordinal or a list is refused | +| The new realm's administration API on the issuer's **own origin** | The tool asks `/admin/realms//users`. A load balancer that blocks `/admin` on the public host makes the proof impossible from there; run the tool from a host that can reach it. The tool uses no proxy and the operating system's trust store only, so a private authority belongs in that store | + +### Two people + +The tool checks the operator's token, the grant and the attribution it writes into the +audit rows. The grant and the database password sit in the same process environment, so +the tool cannot tell who wrote them. Separate the roles by practice: whoever deploys the +change writes the tool's environment, including `PlatformOperator__Grants__*`, and +supplies the database password for the window only; the operator who signs in supplies +the token and runs it. The database does not force that separation: whoever holds the +role's password could change the issuer without the tool. The password is therefore +enabled for the window and retired after it (see [After it](#after-it)). + +## Before you start + +### Build the tool + +There is no release artifact that carries the tool. Build it from the same commit as the +deployed migrations, on a host with the .NET 10 SDK, and run the output on a host with +the .NET 10 runtime: + +```sh +dotnet publish backend/src/LearnStack.Tools.IdentityAuthorityRebind -c Release -o ./rebind-tool +``` + +### Enable the role for the window + +The role's login is closed outside a window. A role administrator opens it with a +password made for this window and hands that over through the secret channel: + +```sql +ALTER ROLE learnstack_identity_rebind LOGIN PASSWORD ''; +``` + +The roles script sets `LOGIN` and the password from `LEARNSTACK_IDENTITY_REBIND_PW` +every time it runs, so rerunning it opens the role; retire it again afterwards. On a +database that predates the role, run the roles script before the migration that grants +it: the migration stops with a message that names the missing role, and the roles script +is the role's only definition. + +### Freeze + +The tool takes a database lock that every API start and every new user binding queues +behind, and it refuses to run while any session of the application, outbox, ingress or +platform role is open on the database. A start that overlaps the rebind waits for the +lock for up to thirty seconds and then fails with the fixed qualification error, and a +user creation waits two seconds and is refused. The tool cannot see a process that holds +no database connection, so the stop step below is the control for that case. + +1. Announce the window and **stop every API and seeder process** of the deployment, + including the Hangfire server, the outbox dispatcher and the provider-event poller. +2. Check that nothing still holds a session. A stopped process leaves none. A connection + pooler (PgBouncer) or a process that was missed does: the tool refuses with + `refused_live_sessions` and a count, and that count is all it reports. To see which + role, read `pg_stat_activity` yourself. +3. Keep the **old** configuration out of every restart script, and out of anything that + restarts a crashed service. A process started with the old issuer fails its start on + the mismatch, which is the safe outcome. A process that starts while the tool runs + queues behind its lock and holds a session, which makes the tool refuse at its last + check, again the safe outcome; a process that was already running and idle is the one + the tool cannot see. +4. Do not create or delete users in the **new** realm while the tool runs. It reads the + realm twice and refuses a realm whose users changed between the reads. + +## Get the access token + +Follow [Getting a token](operator-access.md#getting-a-token) for the operator issuer. +The token lasts at most 15 minutes and its `auth_time` must be recent, so sign in just +before the run. Give it to the tool in `LEARNSTACK_OPERATOR_TOKEN`, or pipe it on +standard input within thirty seconds so it does not sit in the environment. **Never pass +it as an argument**: the tool refuses any argument. + +## Create the read-only realm credential + +In the **new** realm's administration console create a client with *Client +authentication* on, only *Service accounts roles* enabled, and give its service account +the single client role `realm-management` / `view-users`. Copy its id and secret into +`LEARNSTACK_REBIND_REALM_CLIENT_ID` and `LEARNSTACK_REBIND_REALM_CLIENT_SECRET`. Delete +the client when the run is over, whatever the outcome. + +## Run it + +From a host that can reach the database, the operator issuer and the new realm, with the +settings of the stopped deployment in the environment. Run it in `tmux` or `screen`: a +dropped connection ends the run, as an interrupt does. Under `nohup` the hang-up is +ignored and the run goes on. + +```sh +export Deployment__Mode= +export ConnectionStrings__IdentityRebind="Host=$DB_HOST;Database=$DB_NAME;Username=learnstack_identity_rebind;Password='$REBIND_PASSWORD';SSL Mode=VerifyFull" # leakwatch:ignore:database-connection-string +export Identity__AuthorityId= +export Authentication__Tenant__Issuer= +export PlatformOperator__Issuer=... PlatformOperator__AuthorizedParties__0=... PlatformOperator__AcceptedAcr__0=... +export PlatformOperator__Grants__0__Subject= +export PlatformOperator__Grants__0__Permissions__0=platform.identity_authority.admin +export LEARNSTACK_REBIND_REALM_CLIENT_ID=... LEARNSTACK_REBIND_REALM_CLIENT_SECRET=... +export LEARNSTACK_REBIND_TICKET=CHG-123 # optional but recommended +printf %s "$TOKEN" | dotnet ./rebind-tool/LearnStack.Tools.IdentityAuthorityRebind.dll +``` + +The password is single-quoted inside the string, and a quote inside it is doubled, so a +`;` or `=` in it cannot split the string. The tool does not require TLS to the database; +outside a loopback host, ask for it (`SSL Mode=VerifyFull`) because the role's password +crosses that link. The two issuer settings are different things: the operator issuer +signs the person in, the tenant issuer is the realm being moved. + +The ticket is 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -`; a ticket outside that +grammar is refused. It is recorded on the two audit rows, which no tenant can read. + +It prints exactly one line to standard output, nothing to standard error, and exits: + +| Exit | Meaning | +|---|---| +| `0` | The issuer was changed (`outcome=applied`), or already equalled the target (`outcome=already_applied`, nothing written) | +| `2` | Refused. **The state is unchanged**; fix the cause and run it again | +| `3` | `outcome=unknown`: the commit's answer was lost and the stored issuer could not be read back. See [After exit 3](#after-exit-3) | + +The line is `rebind: outcome=`, then `correlation=`, which finds the audit +rows of a run that reached the database (a refusal before that writes none), then +`detail=` where the class has more than one cause, then `sessions=` when the +freeze check ran, then the counts of the proof where it ran: `active`, `closing`, +`closed`, `reported`, `unkeyable`, `missing_active`, `reappearing_closed` and +`unbootstrapped`. A refusal that happens before a run has a handle (`refused_input`, and +a cancelled start that was waiting for the token) carries no correlation. The line never +contains a subject, a key, an issuer, an address or a credential; keep it in the change +ticket, because it is the only record of a refusal that happens before the database is +reached. + +An interrupt (Ctrl-C), a termination signal or a hang-up ends the run as the ten-minute +deadline does: the run rolls back, an unknown commit is still reconciled, and the line +says `refused_cancelled` or its true outcome. A second interrupt does not shorten the +reconciliation, which can take up to about a minute because it waits for the original +transaction to end. + +### After exit 3 + +The commit may or may not have landed. Read the stored issuer with the same role, from a +host that can reach the database: + +```sh +psql "host=$DB_HOST dbname=$DB_NAME user=learnstack_identity_rebind sslmode=verify-full" \ + -c 'SELECT issuer FROM identity_authority' +``` + +- It equals the **target**: the change landed. Run the tool again; it answers + `already_applied` and writes nothing. Then continue with [After it](#after-it). +- It equals the **old** value: the change did not land. Run the tool again. +- It is **anything else**: stop and escalate. + +## What the tool does, in order + +1. Validates the token with the operator validator and admits the act against the + grant. A refusal here (`refused_operator_...`) writes nothing, not even a row. +2. Opens one direct, never-pooled connection as the rebind role and checks that the role + is exactly what it was granted, table by table and column by column, and that the + server applied the session timeouts it asked for. It then takes the exclusive rebind + lock as the first statement of its transaction. If another rebind holds it, the + tool waits up to 30 seconds and refuses with `refused_rebind_in_progress`. +3. Reads the stored authority. If the stored issuer already equals the target it ends + with `already_applied` and **writes nothing**. +4. Otherwise commits an **intent** audit row on its own short transaction. From here on + an aborted attempt is on record. +5. Refuses while a session of a runtime role is open (`refused_live_sessions`). +6. Reads the new realm's discovery document, key set and users, and requires the realm's + own `issuer` to equal the target, at least one signing key and a complete + enumeration. The credential is sent only to the realm's own token endpoint, and only + once the discovery document names the target. +7. Proves continuity (below), asks the freeze question again with a fresh view of the + database's sessions, changes the one column, writes the **result** row on the same + transaction and commits. + +Limits that bound the run: statements time out at 120 seconds, a transaction that idles +for 15 minutes is ended by the server, the whole run has a ten-minute deadline, and a +realm of more than 200,000 users is refused because its proof cannot finish in that +deadline. A realm of a size near that limit can end as `refused_cancelled` for the same +reason: each page is one request, twice over, and a slow realm uses the deadline up. + +## The continuity proof + +- Every **Active** user's exact stored subject must be among the new realm's `sub` + values. A missing one is `missing_active`. +- No reported `sub` may produce the key of a **Closed** user, whose subject is gone and + only its key kept, so a closed person cannot reappear. That is `reappearing_closed`. +- A user in the new realm that matches no stored key is allowed: that person has not + signed in yet. +- A user that is **Closing** and still holds its subject is judged by neither rule, + because closure owns that transition. +- A `sub` that could not be a LearnStack subject (blank, over 255 characters or text + that cannot be stored) is counted as `unkeyable` and cannot equal a stored one. + +The realm is read in full twice and the two reads must report the same users, with no +user repeated and the same count before and after. A realm that changes while it is read +is refused as incomplete. + +`refused_continuity_broken` means the new realm is not the same population. Do not +force it. Read the counts: + +- **`missing_active` is close to `active`** (or `reported` shares almost nothing with + it): the realm's users have new ids, as an import that generated them does. This is a + different authority and not reachable here. Escalate. +- **A few `missing_active`:** accounts were deleted or not copied. Restore them in the + new realm with their original `sub`, or close those people in LearnStack first through + the normal lifecycle, then run it again. +- **Any `reappearing_closed`:** a person LearnStack closed has an account in the new + realm. Delete that account, then run it again. Never reactivate it here. + +To compare by hand, the stored subject is `users.provider_subject`, which the rebind +role can read, and the new realm's is the user's `id` in the administration console. + +## When it refuses + +`detail` is a closed name that says which check failed and never a value. + +| Outcome | What it means and what to do | +|---|---| +| `refused_input detail=` | A required value is missing, malformed, or an argument was given, and the setting is named: `arguments`, `connection_string` (missing, malformed or not the rebind role's), `operator_token` (missing, empty or over its length bound), `realm_client`, `authority_id`, `issuer` (not the realm grammar, or not HTTPS outside Development) or `deployment_mode` | +| `refused_operator_token_` | The token failed validation: `token_missing`, `token_invalid`, `token_expired`, `token_audience`, `token_issuer`, `token_signature`, `token_algorithm`, `token_type`, `token_lifetime`, `metadata_unavailable`, `metadata_stale` or a `profile_*` cause. [The profile](operator-access.md#the-token-profile) says what each requires. Get a fresh token | +| `refused_operator_missing_permission` | The token is good and the operator holds no `platform.identity_authority.admin` grant | +| `refused_operator_invalid_ticket` | The ticket is outside its grammar | +| `refused_operator_issuer_not_configured` / `..._configuration_invalid` | The `PlatformOperator__*` settings are absent or unsafe | +| `refused_operator_invalid_witness` / `..._unknown_operation` / `..._not_admitted` | A defect in the tool's build, not an operator mistake. Escalate | +| `refused_not_admitted` | The admission was stale, spent or not for this operation. Run the tool again | +| `refused_role_invalid detail=` | `role_session`: the string is malformed or not the rebind role's. `role_attributes`: the role gained an attribute that escalates. `role_membership`: it belongs to a role or has a member. `role_grants`: it can create objects, owns something, or holds a privilege on a relation beyond its declared grants (a `PUBLIC`-readable relation you added to `public` counts; an extension's own relations do not) or lacks one. `session_settings`: the server did not apply the timeouts the tool asked for, as a pooler in the path can; connect directly. For the first four, re-run the roles script and migrate, then open the role again | +| `refused_rebind_in_progress` | Another rebind holds the lock, or a previous run is still open. Wait and retry | +| `refused_database_unavailable detail=` | `database_connection`: the host or port could not be reached, or the TLS handshake failed. `database_authentication`: the server refused the credential or `pg_hba` does not admit this host (try the same string with `psql`). `database_permission`: a statement was refused for a missing privilege. `database_timeout`: the server or the network took too long. `authority_state`: the stored authority is missing, is not one row or changed under the run; this is not an outage, so escalate. Nothing changed | +| `refused_authority_mismatch` | The stored authority is not `Identity__AuthorityId`. A different authority would re-key every person: stop and escalate | +| `refused_live_sessions` | A session of a runtime role is open (the count is printed). Stop what holds it and retry | +| `refused_new_realm_unavailable detail=` | The read of the new realm stopped at `realm_discovery` (the discovery document, the issuer's path or an address that is not on the issuer's origin), `realm_key_set`, `realm_token` (the client credential was refused, or the token endpoint did not answer), `realm_user_count` (the administration API refused it: the client lacks `view-users`, `/admin` is blocked on this origin, or the realm is above 200,000 users) or `realm_user_list` (the user list was refused or malformed). It names no address and no body | +| `refused_new_realm_incomplete` / `refused_new_realm_issuer_mismatch` | The new realm published no signing key, changed while it was read or reported inconsistent counts, or names another issuer than the target | +| `refused_continuity_broken` | See [the proof](#the-continuity-proof) | +| `refused_audit_failed` | The audit row could not be written, so the change was rolled back or never begun | +| `refused_commit_failed` | The commit failed and the stored issuer was read back unchanged, after the original transaction had ended. Retry | +| `refused_cancelled` | The ten-minute deadline, an interrupt, a termination signal or a hang-up ended the run | +| `refused_unexpected` | A defect. The state is unchanged, because a commit whose outcome cannot be confirmed is reported as `unknown`. Quote the correlation, which finds the intent row if one was written, and escalate | + +Every refusal leaves the stored issuer where it was and the next run repeats the whole +proof. The intent row stays, so the trail shows each attempt. + +## After it + +The change is done when the tool prints `applied`. **Deploying the new issuer +configuration is the unfreeze.** Do the cleanup only after a sign-in works, because a +rollback needs the old realm, the realm credential and the role's password +([Rolling back](#rolling-back)). + +1. Set every setting that names the issuer or the realm to the new value, then start + the processes. A process that still holds the old issuer fails its start with the + fixed qualification error: that is the guard, not a bug. + + | Setting | Where | + |---|---| + | `Authentication__Tenant__Issuer` | Every API and seeder configuration. The federation adapter reads the same key | + | `LEARNSTACK_BFF_ISSUER` | The web application, when native sign-in is enabled | + | `IdentityEvents__RealmId` and `IdentityEvents__ClientSecret` | The API, when the provider-event mirror is configured: the realm's immutable id and the event reader's secret, [as the Keycloak setup describes](../../infra/keycloak/README.md) | + | The realm's own clients and their secrets | In the new realm. A Keycloak export masks confidential client secrets, so set them again there | + +2. Confirm one sign-in per tenant host and look at the audit rows (below). +3. Only then clean up. Delete the read-only realm client and remove + `ConnectionStrings__IdentityRebind` from the tool's host. Close the role's login and + discard its password: + + ```sql + ALTER ROLE learnstack_identity_rebind NOLOGIN PASSWORD NULL; + ``` + + The roles script restores `LOGIN` and the password every time it runs, so close the + role again after any rerun of it. +4. Keep the old realm until you have no use for a rollback. + +The audit rows are readable only by the platform role, because they sit under the +platform sentinel tenant and no tenant policy admits them: + +```sql +-- as learnstack_platform, not the rebind role +SELECT timestamp, operation, outcome, reason, entity_id, before_state, after_state, + metadata->'operator' AS operator, metadata->'continuity' AS continuity +FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; +``` + +The two rows are `identity.authority.rebind_attempt` (`indeterminate`) and +`identity.authority.rebind` (`success`), with no actor. The old and new issuer are in +`before_state` and `after_state`, and the ticket is in `metadata.operator`. A run that +was refused or interrupted leaves its attempt row and no result row. To list those: + +```sql +SELECT a.correlation_id, a.timestamp FROM audit_log a +WHERE a.operation = 'identity.authority.rebind_attempt' + AND NOT EXISTS (SELECT 1 FROM audit_log r + WHERE r.correlation_id = a.correlation_id + AND r.operation = 'identity.authority.rebind') +ORDER BY a.timestamp DESC; +``` + +## Rolling back + +An applied rebind to a wrong issuer is undone by running the tool again with the old +issuer as the target. The same freeze, proof and rows apply, so it needs everything the +first run did: every runtime process stopped, a fresh operator token, a fresh read-only +client in the **old** realm, the old realm reachable, and the role opened again. + +It works only while the old realm still reports every Active user. Once anyone has been +created in the new realm after the change, that person's `sub` is stored and is not in +the old realm, so the proof answers `refused_continuity_broken` with `missing_active`. +Roll back before the new realm takes new people, or fix forward. + +## Signals + +`learnstack_identity_rebind_runs_total{outcome}` counts each run that read its input: +every printed class, `applied` and `already_applied` and `unknown` included, and the +operator-gate and input refusals under the label the line prints. The tool is a +short-lived process: it exports the counters only when `OTEL_EXPORTER_OTLP_ENDPOINT` is +set in its environment. It writes no log. A refusal at the gate leaves no audit row by +design, so its record is the printed line, which belongs in the change ticket, and the +counter when it is exported. `learnstack_identity_rebind_continuity_total{class}` counts +the proof by class. + +Any outcome other than `applied` and `already_applied` outside a planned window means +someone ran the tool; alert on it where the counters are exported. The audit query +above lists every attempt that did not finish. + +`learnstack_identity_lock_refusals_total{lock_kind="authority"}` counts a user creation +that could not take the shared rebind lock in time (`reason` `timeout`, `cancelled` or +`fault`) and, with `reason="mismatch"`, one that waited out a rebind and found the +issuer changed. A burst of `timeout` is what a window looks like from the API side. + +## Not recoverable here + +- **A change of the stable authority identifier.** It re-keys every person and can + resurrect a closed tombstone. There is no tool for it; escalate. +- **A realm rename.** +- **A running process that held no database connection** when the tool ran. It keeps the + old issuer until it restarts, and then fails its start on the mismatch. The stop step + is the control for it, not the database. +- **A rollback after the new realm took new people.** See [Rolling back](#rolling-back). +- **A realm of more than 200,000 users.** The proof cannot finish in the deadline; + escalate. + +## What this does not do + +It does not stop or start any process, deploy configuration, create or delete the +realm client, verify DNS or certificates, or move any tenant data. Moving a tenant +between identity authorities is out of scope for the whole platform until a decision +says otherwise. diff --git a/docs/runbooks/killswitch.md b/docs/runbooks/killswitch.md new file mode 100644 index 000000000..ce8091e4b --- /dev/null +++ b/docs/runbooks/killswitch.md @@ -0,0 +1,116 @@ +# Killswitch + +Switching a capability off for every tenant during an incident, and switching it back. +Decided in [ADR-0101 § 13](../decisions/0101-platform-operator-authority.md); the +registry and the overlay are described in +[Feature Flags](../architecture/21-feature-flags.md). + +## When to use it + +Only during an incident, to stop an expensive or risky path for all tenants at once. It +is not a way to take a feature away from one tenant; tenant flags and the plan do that. + +| Key | Capability | +|---|---| +| `killswitch.classroom.recording` | Recording a live class | +| `killswitch.notifications.email` | Outbound email | +| `killswitch.analytics.ingest` | Analytics ingest | + +No production code reads any of these yet. Flipping one is recorded and visible to the +overlay, but changes no behavior until the capability that guards a path reads it. The +owner of that capability states it in its own runbook. + +## What it needs + +An operator holding the Platform permission `platform.killswitch.write`, a current token +(see [operator access](operator-access.md)), and the key from the table. + +## Switching a key off + +`PUT /api/platform/v1/killswitches/{key}` with body +`{"enabled": false, "ticket": "INC-123"}`, as shown in the +[operator access](operator-access.md#making-a-call) example. The answer is +`{ "key", "before", "after", "correlationId" }`. `before` is `true` when no row existed, +because absent and enabled mean the same. + +Concurrent flips of one key take turns on the row, so each answer's `before` is the +previous flip's `after`, and a first flip of a key creates the row at the default before +it reads it. + +Two audit rows are written under the platform sentinel, which no tenant can read: the +entry into the platform scope, and the result row `tenancy.killswitch.toggle` with the +before and after state and the operator's digest. The ticket is on those rows. Find the +rows by the correlation id. The switch's own row keeps no ticket, because the +application role can read that table. + +## Reading the record + +The sentinel rows are visible only to the `learnstack_platform` role (the table owner is +filtered too, because row level security is forced), so a database administrator +connects with the `ConnectionStrings:PlatformAdmin` credential to read them. By the +correlation id the answer returned: + +```sql +SELECT timestamp, operation, reason, + metadata->'operator'->>'subjectDigest' AS operator_digest, + metadata->'operator'->>'ticket' AS ticket, + before_state, after_state +FROM audit_log +WHERE tenant_id = '00000000-0000-7000-8000-000000000002' + AND correlation_id = '' +ORDER BY timestamp; +``` + +The operator is recorded as a digest, never as the raw `sub`. To find every row one +operator wrote, compute their digest from the issuer and the `sub` (`ISSUER` must equal +`PlatformOperator:Issuer` byte for byte, a trailing slash included) and filter on +`metadata->'operator'->>'subjectDigest'`: + +```sh +printf 'learnstack.operator.subject.v1\n%s\n%s' "$ISSUER" "$SUB" \ + | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=' +``` + +The current state of a switch is its own row, if it has one: + +```sql +SELECT key, is_enabled, toggled_at +FROM platform_killswitches WHERE key = ''; +``` + +## When it takes effect + +Immediately on the instance that handled the request, which drops its cached copy after +the commit. Every other instance refreshes within 60 seconds. Plan for that minute. If +the instance could not drop its copy it logs a Warning with event 7104, and then it too +serves the old state for up to 60 seconds. + +**The read fails open.** If the overlay cannot read the table or the cache, it answers +the key's default, which is enabled. A switch flipped off during a database or cache +incident can therefore read as on again once its cached copy expires. Watch the log for +event 7107 (Error, "The killswitch overlay could not be read"), and repeat the flip if +it appears. Event 7108 means a caller asked for a key that is not declared. + +## Switching it back + +Send the same request with `"enabled": true`. There is no other restore, and no delete. +Confirm by the response (`after` is `true`) and by the result row. + +## If the answer is not 200 + +| Answer | What happened | What to do | +|---|---|---| +| 400, 401, 403 | The body, the ticket, the token or the grant | See [operator access](operator-access.md#reading-a-refusal) | +| 404 | The key is not one of the three in the table, or no operator issuer is configured | Check the spelling and the issuer setting | +| 503 | The audit row could not be written, so the table was not changed | Repeat the request after `Retry-After` | +| 500 | Something failed unexpectedly: the platform credential is missing, or the final commit's outcome is unknown and the flip may have landed. The instance still dropped its cached copy | Read the switch's row (above) before repeating | + +For a killswitch act, an admission with neither a matching `results_total` increment nor +an `audit_failures_total` increment is an act whose outcome is unknown; read the row for +it too. The onboarding acts are counted by `acts_total` and are not judged this way. + +## Not recoverable here + +A flip is not undone by the audit log: the log records it, and only another flip +reverses it. Both flips of a pair are in the audit log with their true before and after +states. diff --git a/docs/runbooks/operator-access.md b/docs/runbooks/operator-access.md new file mode 100644 index 000000000..cb740c7bd --- /dev/null +++ b/docs/runbooks/operator-access.md @@ -0,0 +1,221 @@ +# Platform operator access + +How a LearnStack or deployment operator authenticates to the platform surface, how a +grant is given and withdrawn, and how to read a refusal. Decided in +[ADR-0101](../decisions/0101-platform-operator-authority.md). + +## Who this is for + +Operators only: LearnStack staff, or the customer's staff in a Self-Hosted deployment. +An operator is not a tenant user and holds no tenant role. Nothing here is reachable +with a tenant token. + +## What must be configured + +The surface does not exist until an issuer is configured; with none, every +`/api/platform` path answers 404. + +| Setting | Meaning | +|---|---| +| `PlatformOperator:Issuer` | The deployment-controlled OIDC issuer, for example the `learnstack-hub` realm. HTTPS only; loopback HTTP in Development. Never the tenant issuer | +| `PlatformOperator:AcceptedAcr` | The `acr` values that show the second factor. The shipped realm emits `mfa`. `0` and `1` are single-factor levels and are refused at start | +| `PlatformOperator:AuthorizedParties` | The allowed `azp` clients. The shipped realm's is `learnstack-operator` | +| `PlatformOperator:MaxAuthenticationAge` | How old `auth_time` may be, as a time span such as `00:15:00`; at most one hour, default 15 minutes | +| `PlatformOperator:Grants` | Each operator's `Subject` (the issuer's `sub`) and the Platform permission keys held | +| `ConnectionStrings:PlatformAdmin` | The `learnstack_platform` credential the killswitch act, the [recovery](operator-recovery.md) inspections and the [federation](federation-operator.md) report, remove and disable run under. Required for them: without it the first one fails with an error that names this key. The [onboarding](tenant-onboarding.md) acts run on the application role and do not use it | +| `ConnectionStrings:OutboxDispatcher` | The dispatcher's outbox-role credential, which the two recovery acts (replay and reset) use through the dispatcher's own stores. Without it they cannot run, as the dispatcher cannot | + +List settings are indexed in environment variables, and the double underscore is the +separator: + +```sh +PlatformOperator__Issuer=https://identity.example.com/realms/learnstack-hub +PlatformOperator__AcceptedAcr__0=mfa +PlatformOperator__AuthorizedParties__0=learnstack-operator +PlatformOperator__MaxAuthenticationAge=00:15:00 +PlatformOperator__Grants__0__Subject= +PlatformOperator__Grants__0__Permissions__0=platform.killswitch.write +``` + +The registered permissions are `platform.killswitch.write` +([killswitch](killswitch.md)), `platform.tenant.write` and +`platform.tenant_bootstrap.write` ([tenant onboarding](tenant-onboarding.md)), and +`platform.identity_authority.admin`, which the offline +[issuer rebind](identity-issuer-rebind.md) tool checks against the same grants. That +tool reads the same `PlatformOperator__*` settings from its own environment and is not +an API route. `platform.delivery.read` and `platform.delivery.write` are the two +permissions of [operator recovery](operator-recovery.md): the first for the inspection +routes and the second for a replay or a producer reset. `platform.federation.read` and +`platform.federation.admin` are the two permissions of the [federation +operator](federation-operator.md): the first for the report and the second for a remove +or a disable. + +A Self-Hosted issuer other than the shipped realm must issue access tokens that meet the +profile below. If it cannot, no operator can act, by design. + +## The token profile + +A token is accepted only when every line holds: + +- It is signed with RS256 by a key the issuer publishes, its header `typ` is `JWT`, and + it has not expired (30 seconds of clock skew). +- `iss` equals `PlatformOperator:Issuer` exactly. +- `aud` contains `learnstack-platform`. +- `azp` is one of `PlatformOperator:AuthorizedParties`. +- `acr` is one of `PlatformOperator:AcceptedAcr`. +- `auth_time` is present, not in the future, and no older than + `PlatformOperator:MaxAuthenticationAge`. +- `iat` and `exp` are present and `exp - iat` is at most 15 minutes. +- `sub` is present. + +Roles and every other claim carry no authority. To see what a token claims, decode its +middle segment: + +```sh +printf %s "$TOKEN" | cut -d. -f2 | tr '_-' '/+' \ + | awk '{ while (length($0) % 4) $0 = $0 "="; print }' | base64 -d | jq . +``` + +## Getting a token + +You need `curl`, `openssl` and `jq`. In the local stack the API answers at +`http://localhost:5080`; set `API` to the address of the deployment you are calling. + +The shipped realm provides the public client `learnstack-operator` (authorization code +with PKCE, redirect `http://127.0.0.1:8765/*`). In the compose stack the issuer is +`http://localhost:8080/realms/learnstack-hub`; the demo operator is +`demo-operator@learnstack.test` with the password `demo-dev-secret`, and its first login +asks it to set up an authenticator application (scan the code, or use the manual key +with any TOTP tool). + +1. Make a verifier and its challenge: + + ```sh + ISSUER=http://localhost:8080/realms/learnstack-hub + verifier=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n') + challenge=$(printf %s "$verifier" | openssl dgst -sha256 -binary \ + | openssl base64 -A | tr '+/' '-_' | tr -d '=') + ``` + +2. Open the address in a browser (`xdg-open` on Linux). `prompt=login` makes the issuer + ask again even when a browser session exists; without it a stale `auth_time` is + refused later. Sign in with the password and the one-time code: + + ```sh + URL="$ISSUER/protocol/openid-connect/auth?client_id=learnstack-operator" + URL="$URL&response_type=code&scope=openid&prompt=login&state=x" + URL="$URL&redirect_uri=http://127.0.0.1:8765/callback" + URL="$URL&code_challenge=$challenge&code_challenge_method=S256" + open "$URL" + ``` +3. The browser lands on the callback address and shows a connection error. Copy `code` + from its address bar and set `CODE` to it. +4. Redeem it. The access token lasts at most 15 minutes: + + ```sh + TOKEN=$(curl -s "$ISSUER/protocol/openid-connect/token" \ + -d grant_type=authorization_code -d client_id=learnstack-operator \ + -d redirect_uri=http://127.0.0.1:8765/callback \ + -d code="$CODE" -d code_verifier="$verifier" | jq -r .access_token) + ``` + +## Making a call + +Send `Authorization: Bearer $TOKEN` and `Content-Type: application/json`. Every write +may carry an optional `ticket` of 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -`. The +response carries a `correlationId`, the request's W3C trace identifier, which is also +the trace id in the logs; record it against your own ticket, because the audit rows a +tenant can read never hold the ticket. + +```sh +API=http://localhost:5080 +curl -sS -X PUT "$API/api/platform/v1/killswitches/killswitch.notifications.email" \ + -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -d '{"enabled": false, "ticket": "INC-123"}' +``` + +The operator contract is the document `/openapi/platform-v1.json`. It is served only +when an issuer is configured and is not part of the tenant contract or SDK. + +## Giving and withdrawing a grant + +Edit `PlatformOperator:Grants` in the deployment configuration: the operator's `sub` +from the issuer's console and the permission keys. Each entry is validated when the +process starts, and a key that is not registered stops the start. A configuration +provider that reloads (a file or a mounted secret) applies a change on the operator's +next act; one that cannot reload needs a restart. Withdrawal is the same edit, and it +takes effect on the next act, not at the token's expiry. + +**Grant only after the operator's authenticator exists.** In the shipped realm an +account that has no one-time-password credential is asked to enrol one at its first +login, and that login then carries `mfa`. Until the operator has enrolled, anyone who +knows the password could enrol their own device. So the order is: the operator signs in +once and sets up the authenticator, you confirm it in the realm's console, and only then +is the grant added. + +Password reset is switched off in the shipped realm, so a forgotten password or a lost +device is recovered by the realm's administrator, not by an emailed link that skips the +second factor. + +The demo operator's grant is accepted in Development only; the process refuses to start +in any other mode while it is present. Never import the shipped realm's demo user into a +production realm. + +## Reading a refusal + +| Answer | Meaning | What to do | +|---|---|---| +| 401, `Bearer` challenge | The token is missing, malformed, expired, signed by another issuer, for another audience or client, lacks an accepted `acr`, has no `auth_time`, was authenticated too long ago, or lives longer than 15 minutes. It also covers an issuer that cannot be reached: at start, or for more than 15 minutes after its keys were last fetched | Decode the token and compare it with the profile; sign in again; check the issuer settings and the signals below | +| 403 | The token is good and this operator holds no grant for the act | Ask for the grant | +| 400 | The ticket or the body is malformed | Fix the request | +| 404 | Unknown killswitch key, an onboarding route's tenant that does not exist, a recovery that names no such row, a federation disable of an alias no instance has, or the surface is not configured | Check the key, the tenant or the row and the issuer setting | +| 409 | An onboarding act refused the state it found (a `failed` audit row is written in the tenant), or a recovery found a stale fence or a row it may not act on, or a federation act refused its state (`errors.owner`, `errors.connection`, `errors.class` or `errors.provider`; see the [federation runbook](federation-operator.md#act)) | See the [onboarding runbook](tenant-onboarding.md#when-an-act-answers-something-else) or the [recovery runbook](operator-recovery.md#act) | +| 415 | The body is not `application/json` | Send the header shown above | +| 503 | The audit row could not be written, or a connection or a lane was unavailable, so nothing changed, except that a recovery's or a federation act's `503` can carry `errors.outcome` for a change that may have landed. `Retry-After` says when to try again | Retry; the act is safe to repeat. For a recovery that names `errors.outcome`, read the [recovery runbook](operator-recovery.md#an-unknown-outcome) first, and for a federation act the [federation runbook](federation-operator.md#an-unknown-outcome) | +| 500 | Something unexpected failed. For a toggle, a commit whose outcome is unknown may have landed | Read the switch's state before repeating (see the [killswitch runbook](killswitch.md)); an onboarding act is idempotent, so repeat the same request. A recovery is not: list again first; nor is a federation act, which may have changed the provider | + +The answer to a refused credential is always the same; the reason is in the signals, not +the response. + +## Signals + +| Signal | Meaning | +|---|---| +| `learnstack_platform_operator_admissions_total{outcome,operation}` | Acts admitted or refused at the gate; `operation` is the audit slug, for example `tenancy.killswitch.toggle` | +| `learnstack_platform_operator_refusals_total{cause}` | Refusals, by cause: `request_aborted`, `metadata_stale`, `metadata_unavailable`, `token_missing`, `token_expired`, `token_lifetime`, `token_signature`, `token_issuer`, `token_audience`, `token_type`, `token_algorithm`, `token_invalid`, `profile_issuer`, `profile_subject`, `profile_azp`, `profile_acr`, `profile_iat`, `profile_auth_time`, `profile_lifetime`, `profile_auth_age`, and at the gate `invalid_ticket`, `missing_permission`, `unknown_operation`, `invalid_witness` | +| `learnstack_platform_operator_results_total{operation}` | MUST result rows committed by an operator act: the killswitch toggle and a federation remove or disable (the completion row) in the platform scope, and a replay or a reset on the dispatcher's outbox role | +| `learnstack_platform_operator_recoveries_total{operation,outcome}` | Recovery transitions by how they ended; see the [recovery runbook](operator-recovery.md#signals) | +| `learnstack_platform_operator_federation_total{operation,outcome}` | Federation reports, removes and disables by how they ended; see the [federation runbook](federation-operator.md#signals) | +| `learnstack_platform_operator_acts_total{operation,outcome}` | Onboarding acts by how they ended (`applied`, `replayed`, `refused`, `failed`); see the [onboarding runbook](tenant-onboarding.md#signals) | +| `learnstack_platform_operator_audit_failures_total{operation}` | Acts refused because the MUST row was not durable (the 503) | +| `learnstack_platform_operator_metadata_failures_total` | The issuer's discovery document or key set could not be read, was refused, or named another origin. While it climbs, new keys are not learned; a fetch that failed is not retried for 30 seconds, and once the keys held are more than 15 minutes old with a later fetch failed, every operator is refused (`metadata_stale`) | + +A log line accompanies each. Search by event id: 7102 (Warning) a refused act, 7103 +(Warning) a refused credential with its cause, 7106 (Warning) a metadata failure, 7105 +(Error) a refused audit write, and 7101 (Error) a grant configuration that failed +validation on reload; while 7101 appears every operator act is refused until the +configuration is valid. Every admitted killswitch act, recovery inspection page and +federation report, remove or disable logs a Warning with event 7001 and the text +"Platform-admin scope entered" (other hosts reuse the number for unrelated lines, so +match the text too); the onboarding acts and the two recovery acts do not enter the +platform scope and log no 7001. Event 7109 (Warning) +is an onboarding act the request pipeline itself refused as forbidden, which is a +defect. Event 7110 (Warning) is a recovery, an inspection or a federation call the owner +could not finish, with whether its commit's outcome is unknown; see the [recovery +runbook](operator-recovery.md#a-503-that-does-not-clear). A refused operator leaves no database row; the one exception is an +onboarding act an admitted operator had refused for a business reason, which writes a +`failed` row in the tenant. + +## Not recoverable here + +A refusal at the gate leaves no record in the audit log, only the counter and the log +line. An operator cannot grant themselves anything: grants are configuration, edited by +whoever deploys it. + +The offline [issuer rebind](identity-issuer-rebind.md) tool reads the same grants from +its own environment, and it writes no log: a refusal there leaves the printed line and, +when an OTLP endpoint is set, the counter. Because the grant and the database password +sit in that one environment, the tool cannot tell who wrote them, so keeping the person +who writes the environment apart from the operator who signs in is a practice the +runbook asks for, not a control the tool enforces ([ADR-0104 Amendment +1](../decisions/0104-controlled-issuer-rebind.md), item 10). \ No newline at end of file diff --git a/docs/runbooks/operator-recovery.md b/docs/runbooks/operator-recovery.md new file mode 100644 index 000000000..604fec767 --- /dev/null +++ b/docs/runbooks/operator-recovery.md @@ -0,0 +1,246 @@ +# Operator recovery of asynchronous work + +How an operator inspects dead-lettered events and quarantined jobs, and resets one +dead-lettered delivery or outbox row under a fence. Decided in +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md). There is **no +dashboard** and **no job recovery**: this is an API and this document. + +## What exists + +| Route | Does | Permission | +|---|---|---| +| `GET /api/platform/v1/asynchronous-work/outbox-messages` | Lists dead-lettered or terminal-requested outbox rows | `platform.delivery.read` | +| `GET /api/platform/v1/asynchronous-work/event-deliveries` | Lists dead-lettered or terminal-requested subscriber deliveries | `platform.delivery.read` | +| `GET /api/platform/v1/asynchronous-work/quarantined-jobs` | Lists quarantined jobs with their reservation occupancy | `platform.delivery.read` | +| `POST .../event-deliveries/{tenantId}/{subscriptionId}/{eventId}/replay` | Resets one dead-lettered delivery (a **replay**) | `platform.delivery.write` | +| `POST .../outbox-messages/{tenantId}/{eventId}/reset` | Resets one retry-exhausted outbox row (a **producer reset**) | `platform.delivery.write` | + +Authentication, the token profile and how a grant is given are in [Platform operator +access](operator-access.md). The served operator document, `platform-v1`, is the +contract for these routes, and it is the only client there is. + +An act changes a row. An inspection changes nothing: it reads metadata only, and it +cannot read an event body, a job's parameters or plan, a causal id or a lease token, +because the database refuses those columns to the platform role. The inspections need +the Platform migration `20261120120000` applied; without it the first one fails with a +permission error in the API's log. + +Three names for one thing trip people. The act on a subscriber delivery is a **replay** +and writes `platform.delivery.replay`. The act on an outbox row is a **producer reset** +and writes `platform.delivery.reset`. The rows the dispatcher itself writes when it +gives up are `platform.delivery.dead_letter` (a delivery) and +`platform.outbox.dead_letter` (an outbox row). + +## What is not here + +- **Job recovery.** A quarantined job stays frozen, keeps its reservation and keeps the + `jobs` health check unhealthy. Nothing here requeues, retries, releases or re-arms + it, because the only proof that would make that safe is a provider's fence or the + termination of the process that started the effect, and no adapter can supply one + today. The inspection shows the job (`phase`, `quarantineReason`), how many + reservations it holds (`heldReservations`) and how many its capacity group holds + (`groupOccupancy`); it is an operator's evidence for an escalation, not a remedy. +- **A recurrence skip, pause or resume.** None exists. +- **The Hangfire dashboard.** `/admin/hangfire` answers 404 in every deployment mode. +- **A privileged subscription.** A delivery that belongs to one is refused. +- **A read of one row.** The lists are oldest first and cannot be filtered by tenant or + event, so finding one row means paging; each page is one audited scope. + +## When to look + +- `learnstack_outbox_deadletter_total` or `learnstack_inbox_deadletter_total` rises, or + the `jobs`, `outbox` or `delivery` health check goes unhealthy. +- A tenant reports an effect that never happened and the audit trail shows a + `platform.outbox.dead_letter` or `platform.delivery.dead_letter` row for it. + +## Inspect + +Each page is one entered platform scope, so each page writes one +`platform.admin_scope.enter` audit row with the reason `delivery_inspect`, your +attribution and your ticket. It does not say which of the three lists you read or how +far you paged. Pass the ticket as `?ticket=`: 1 to 64 letters, digits or `.` `_` `:` +`/` `#` `-`, and percent-encode `#` as `%23`, because a bare `#` ends the query. +Inspections run on `ConnectionStrings:PlatformAdmin`; the two acts run on +`ConnectionStrings:OutboxDispatcher` +([setup](operator-access.md#what-must-be-configured)). + +```sh +curl -s -H "Authorization: Bearer $TOKEN" \ + "$API/api/platform/v1/asynchronous-work/outbox-messages?state=dead_lettered&limit=20&ticket=CHG-123" +``` + +- `state` is `dead_lettered` (default) or `terminal_requested`. A **terminal-requested** + row has a terminal reason recorded and the commit of its dead-letter not yet made: its + state is shown and it is **not actionable**. It becomes dead-lettered by itself, or it + does not. One that stays means the dispatcher cannot write its audit row or has + stopped: look at the `outbox`, `delivery` and audit health checks and the error + line 7105 in the dispatcher's host log. +- `limit` is 1 to 100 (default 20; a larger value, however large, is clamped, and zero + or less is refused with `errors.limit`). The answer holds `items` and a `pageInfo` + with `nextCursor` and `hasNext`; send `nextCursor` back as `cursor`. A cursor belongs + to the route and state that issued it. The quarantined-jobs list takes no `state`. +- Each row carries `eventType` as the registry's label (`unknown` and `retired` mean + the registry no longer dispatches that stored type), `lastError` and `actionable`. + `lastError` is the dispatcher's closed descriptor of the last failure, whose first + part says where it failed (`publish:`, `execute:`, `recovery:` or `terminal:`), or + `unrecognized`. It carries no handler message: that is in the dispatcher's log, found + by event type and subscription. Treat `actionable` as advice about the row and the + registry: the act also checks the tenant's service state and the fence, so a suspended + tenant's row can be listed actionable and refused. +- **The fence travels with the row.** A delivery shows `replayCount`, `deadLetteredAt`, + `terminalReason`; an outbox row shows `attempts` and `deadLetteredAt`. Send **every** + fence field back exactly as returned. `deadLetteredAt` has microsecond precision: a + client that parses it and writes it back at millisecond precision, or changes the + case of a reason, sends a fence that never matches. + +## Choose: replay or reset + +- **Replay** resets one *delivery*: one subscription of one event. Use it when a + subscriber's handler failed for a reason that is now fixed, or its subscription became + Active. Its reasons are `retry_exhausted`, `unknown_type`, `retired_type` and + `invalid_subscription`. It renews the delivery's attempts to zero too. The completed + siblings, the inbox row, the producer row and every other event are untouched. +- **Producer reset** resets one *outbox row* whose terminal reason is `retry_exhausted`: + a burst of dispatch failures, and not the event itself, used up its six attempts. It + **renews the six-attempt budget**, so a row that fails for a lasting reason fails six + more times and is dead-lettered again, after about an hour and six minutes of + backoff, with a new audit row. The reset reaches the subscriptions that have no + delivery row yet, and a publication that already reached a subscriber is absorbed by + the event's stable identity; a delivery that already ended terminal needs its own + replay. +- **Neither** if the reason is `invalid_envelope`: the stored envelope is immutable and + cannot become valid. For a *replay*, a reason of `unknown_type` or `retired_type` + follows the registry now: an event the registry still does not know, or has retired, + is refused, and one it knows again is replayed. A *producer reset* acts only on + `retry_exhausted`; any other reason is refused. A reset of a type that is not yet + Active is applied, and the dispatcher claims the row once the type is Active. + +## Act + +Send the fence read at inspection. A ticket is optional and is **checked, not stored**: +the audit row is readable by the tenant, so it never carries one (see [Check it +worked](#check-it-worked)). + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/asynchronous-work/event-deliveries/$TENANT/$SUBSCRIPTION/$EVENT/replay" \ + -d '{"replayCount":0,"deadLetteredAt":"2026-10-01T12:00:00.123456+00:00","terminalReason":"retry_exhausted","ticket":"CHG-123"}' +``` + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/asynchronous-work/outbox-messages/$TENANT/$EVENT/reset" \ + -d '{"attempts":6,"deadLetteredAt":"2026-10-01T12:00:00.123456+00:00","ticket":"CHG-123"}' +``` + +A refusal names its reason inside `errors`, as a list under the field, so with `jq` a +stale fence is `.errors.fence[0].key`, a refused state is `.errors.state[0].key` and its +rule is `.errors.state[0].params.cause`, and an unknown commit outcome is +`.errors.outcome[0].key`: + +```json +{ "status": 409, "code": "business_rule_violation", + "errors": { "state": [ { "key": "lockey_not_recoverable", "params": { "cause": "tenant_not_serving" } } ] } } +``` + +| Answer | Meaning | +|---|---| +| `200`, `outcome: applied` | The row was reset and its MUST audit row committed with it. `countAfter` is the new replay count, or zero attempts | +| `409`, `errors.fence` = `lockey_stale_fence` | The row no longer shows the fence you sent: the dispatcher, another operator or a retry moved it, or a fence field was altered on the way back. Nothing changed and nothing was written. **List again** and decide again. If it persists on a fence you just read, a field was not sent exactly as returned | +| `409`, `errors.state` = `lockey_not_recoverable` | The fence holds and the row is not one the act may take. The rule is `params.cause`: `processed`, `leased`, `invalid_envelope`, `reason_refused` (a producer reset acts only on `retry_exhausted`), `subscription_not_active`, `type_not_dispatchable` (the registry has retired the type or no longer knows it) or `tenant_not_serving` (not Trial or Active, or deleted: nothing here changes a tenant's state, so escalate). Nothing changed | +| `404` | No such row for that tenant | +| `401` | The credential is missing or does not meet the token profile; the cause is in [the operator's signals](operator-access.md#signals) | +| `403` | You hold no grant for the route: `platform.delivery.read` for a list, `platform.delivery.write` for an act. Nothing was opened | +| `400` | The route, the body or the ticket is malformed. A refusal at the gate carries no per-field errors; a refused page parameter names itself (`errors.state`, `errors.limit`, `errors.cursor`) | +| `413`, `415`, `429` | The body is over 4096 bytes, is not `application/json`, or the caller exceeded the per-peer request budget | +| `500` | An unexpected failure, a missing connection string or a deployment defect such as a refused credential or a missing grant: the API's log names it. An act's commit may have landed: list again before changing anything | +| `503`, `audit_unavailable` | The MUST row could not be written, so nothing changed. Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | A connection, the one operator lane or an inspection's read was unavailable. Nothing changed. Only one operator call runs per store at a time, and a second is refused at once and not queued; retry after the delay. The cause is in the API's log (warning 7110), found by the response's `correlationId`, and never in the response; see [A `503` that does not clear](#a-503-that-does-not-clear) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The commit was sent and its answer was lost, or a fault followed it. It **may have landed**. **Do not repeat blindly**: see [An unknown outcome](#an-unknown-outcome) | + +An applied replay makes the delivery due at once; the dispatcher claims it like any +other. A client that never received any answer (a timeout, a gateway error) is in the +same position as an unknown outcome. + +## An unknown outcome + +A landed act leaves the dead-lettered list: it clears the terminal fields. So an +advanced count is not what you will find. Reconcile in this order: + +1. List again. If the row is **gone**, or it is there with a **new** fence (a new + `deadLetteredAt`), the act landed; if it still carries the fence you sent, it did not + land, and repeating it is safe. +2. To tell *your* act from another operator's, read the tenant's audit row by the + `correlationId` of the failed response, as in [Check it worked](#check-it-worked). + A repeat of an act that had landed answers `409` on `errors.fence`, and that answer + alone cannot say whose act it was. + +## Check it worked + +1. List again: the row is no longer in the dead-lettered list (an applied act moves it + back to the ordinary queue). +2. Watch the dispatcher claim it: `learnstack_delivery_pending_count` or + `learnstack_outbox_pending_count` moves, unless the type is not yet Active, and the + executor runs the handler. A row that fails for a lasting reason is dead-lettered + again after its attempts, with a second `platform.*.dead_letter` row. Fix the cause + before you act again. +3. Read the audit trail. The row is in the **tenant's** trail (it names the real event + tenant) with no actor, the operation `platform.delivery.replay` or + `platform.delivery.reset`, the reason `delivery_replay` or `delivery_reset`, your + attribution in `metadata.operator` and the fence before and after in + `metadata.fence`. There is no audit API: read it as the application role + announcing the tenant, by the response's `correlationId`, with the query and the + digest recipe of [Tenant onboarding](tenant-onboarding.md#reading-the-record) and + [Killswitch](killswitch.md#reading-the-record). The ticket is not on it, because the + tenant can read it: record the `correlationId` against your own change reference. + +## A 503 that does not clear + +A `503` `dependency_unavailable` is retryable, and one that never clears is not a +transient fault. Find the cause in the API's host log by the response's `correlationId` +(warning 7110; it carries the operation and whether the outcome is unknown, and the +exception holds the cause): + +- **The lane is busy.** Another operator call is running on that store: wait for it and + send acts one at a time. +- **The database or the credential.** `ConnectionStrings:OutboxDispatcher` (acts) or + `ConnectionStrings:PlatformAdmin` (inspections) cannot connect. A refused credential + or a missing grant is not reported as a `503`: it is a `500` and the log names it. A + connection string that is not set is a `500` on an inspection and a `503` on an act, + and in both the log names the key. +- **The store is sealed.** A connection-cleanup fault on a lane seals that store, for + the dispatcher's own lanes too: its claims fail, so the outbox or the delivery + dispatch halts, and every call to it answers `503` until the API instance restarts. + The remedy is to restart the instance. The three lanes of one store share the seal, and the two + stores do not. + +## Signals + +`learnstack_platform_operator_recoveries_total{operation,outcome}` counts every +transition by `applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavailable` +and `commit_unknown`. A rising `stale_fence` is two operators, or a script, replaying +the same rows. `learnstack_platform_operator_audit_failures_total` counts the refusals +for an audit failure, and the admission and refusal counters are in [Platform operator +access](operator-access.md#signals). Each inspection page also logs the scope-entry line +7001, as a killswitch act does. + +## Limits + +- **Erasure.** The rule that the tenant is serving is the guard until P03-10 (G16) + defines what a replay may reach after a tenant's data is erased; it re-verifies these + transitions. The check is not locked against a suspension that commits at the same + moment. Do not reset anything for a tenant that is being erased. +- **The invitation path.** A stuck or unknown outbound invitation email is a *job*, and + nothing here releases it. Reissuing an invitation helps only while the tenant has a + free slot; it neither reconciles nor releases the old effect, and four unresolved + effects can hold every slot with no operator remedy. +- **Capacity.** The operator lane is one connection per store, so acts are one at a + time, and a second concurrent call is refused with `503` at once. Send them one after + another. + +## Not recoverable here + +- A quarantined job, a held reservation, a recurrence. +- An `invalid_envelope` delivery. +- A reset of a row that was processed, or an event the registry no longer knows. +- A dashboard. diff --git a/docs/runbooks/tenant-onboarding.md b/docs/runbooks/tenant-onboarding.md new file mode 100644 index 000000000..113a85b0e --- /dev/null +++ b/docs/runbooks/tenant-onboarding.md @@ -0,0 +1,196 @@ +# Tenant onboarding + +Creating a production tenant that resolves to a host and has one administrator who can +sign in, and recovering one that has none. Decided in +[ADR-0102](../decisions/0102-production-tenant-onboarding.md); the storage contract of +the one definer it adds is in +[Database Standards](../standards/05-database.md#operator-subject-resolution). The +development seed is not this procedure: the seeder refuses to run outside a Development +deployment. + +## What it needs + +An operator with a current token (see [operator access](operator-access.md)) holding +`platform.tenant.write` for the first two acts and `platform.tenant_bootstrap.write` for +the other three. The grant is read from configuration on every act. No platform database +credential is involved: every act below runs on the application role, under the +tenant's own row security, through the same pipeline a request uses. + +You also need, before you start: + +- A tenant id, an organization id, a role id per template and a membership id, each a + **UUIDv7** that you generate (`psql -At -c 'SELECT uuidv7()'` against any PostgreSQL + 18, including the local stack's; `uuidgen` makes a version 4, which is refused with a + `400` that names no field). The ids are the acts' identity: sending an act again + with the same ids is a retry and never a second write. +- A slug for the tenant and for its default organization, and the host the tenant will + answer on. +- The first administrator's provider subject (`sub`) at the tenant issuer, read from the + identity provider's own console. An email address is never accepted. + +## The order + +Each act commits in its own transaction. Stop between any two and resume at the first +act that has not been answered `200`. + +1. **Provision the tenant and its default organization.** + `PUT /api/platform/v1/tenants/{tenantId}` + + ```json + { + "slug": "acme", + "displayName": "Acme Academy", + "defaultOrganization": { "id": "", "slug": "main", "displayName": "Main" }, + "ticket": "CHG-123" + } + ``` + +2. **Map the host.** `PUT /api/platform/v1/tenants/{tenantId}/host-mappings/{host}` with + `{ "isActive": true, "isPubliclyLive": true, "ticket": "CHG-123" }`. **Both flags are + required** (a body without them is a `400`), because no act unmaps a host and a + mapping must never go live by omission. `organizationId` is optional and pins the + host to one branch. **You assert that the tenant owns the host.** LearnStack checks + no DNS and issues no certificate: a Self-Hosted operator is responsible for both. A + SaaS custom domain is the Hub's to approve and is not reachable from here. + +3. **The person signs in once at that host.** The tenant has no members yet, and the + zero-membership entry binds the person to the identity authority the first time they + sign in. The next acts refuse a subject that is not an Active, bound user of that + authority (`lockey_bootstrap_required`). The check is global, not per host: a subject + that signed in anywhere is accepted, so **confirm the `sub` is the intended + person's** (their own console entry), because a mistyped `sub` of another real person + is accepted and makes that person the administrator. + +4. **Initialize the Role templates** the tenant will need, one act each: + `PUT /api/platform/v1/tenants/{tenantId}/roles/{roleId}` with + `{ "builtInKey": "TenantAdmin", "capabilityScope": "Tenant", "ticket": "CHG-123" }`. + The foundation admits eight templates: at scope `Tenant` the `builtInKey` is + `TenantAdmin`, `Instructor`, `Learner`, `Guardian` or `Editor`; at scope + `Organization` it is `OrgAdmin`, `OrgInstructor` or `Learner`. `TenantAdmin` at + `Tenant` is the one step 5 needs. **Initialize every template the tenant will use + now:** a Role template cannot be created once the tenant has had a Membership. + +5. **Create the first administrator.** + `PUT /api/platform/v1/tenants/{tenantId}/first-administrator/{membershipId}` with + `{ "roleId": "", "providerSubject": "", "ticket": "CHG-123" }`. + It refuses any tenant that has had a tenant-wide Membership, so it cannot add an + administrator to a tenant that has members. + +The `ticket` in each body is optional and is the operator's own reference: LearnStack +validates its grammar and **does not record it** (it is kept only on the platform's +tenantless rows, which these acts do not write), so keep it with the correlation id in +your own change record. Every answer +is `200 { "result": ..., "correlationId": "..." }`. Keep the correlation id. + +## Recovering a tenant with no administrator + +`PUT /api/platform/v1/tenants/{tenantId}/administrator-recovery/{membershipId}` with the +same body as step 5. It creates a replacement administrator and is the only act that +adds one to a tenant with tenant-wide Membership history. + +**It refuses while any Active tenant-wide administrator Membership exists** +(`lockey_administrator_exists`). The database also refuses to leave a tenant without an +available administrator, so revoking or suspending the last one through the product is +not possible. Recovery therefore applies to a tenant whose administration was lost +outside that guard, for example after an owner-level repair. It does **not** apply to a +tenant whose administrator is Active but cannot sign in: escalate that to the platform +owner, because it is a decision about identity, not a runbook step. The act names an +initialized `TenantAdmin` Role of the tenant and an Active, bootstrapped person, and +leaves the last-administrator guard as it found it. + +## When an act answers something else + +| Status | Reason (in the problem's `errors`) | What it means and what to do | +|---|---|---| +| 400 | `validation_failed` | The body is malformed, a value is out of its grammar, an id is not a UUIDv7 (or is the platform sentinel), a host mapping omits a flag, the `providerSubject` is blank or over 255 characters, or the ticket is not 1 to 64 characters of `A-Z a-z 0-9 . _ : / # -` | +| 401 | | The token does not meet the profile; there is one answer for every cause, and the cause is in the operator's signals | +| 403 | | The token is good and the operator holds no grant for this act. An admitted act the request pipeline itself refused as forbidden also answers `403`; that is a defect, not a grant, and logs event 7109 | +| 404 | | The tenant does not exist, or the act can no longer see it. Provision first | +| 409 | `lockey_slug_taken`, `lockey_identifier_taken` | Another tenant has the slug, or an id is already used by a different record. Use another value; an exact repeat of your own act is a `200` | +| 409 | `lockey_bootstrap_required` | The named person has not signed in at the tenant's host (or is not Active). Ask them to sign in, then repeat | +| 409 | `lockey_role_not_initialized` | The role id names no initialized `TenantAdmin` template of this tenant. Run step 4 first | +| 409 | `lockey_tenant_has_memberships` | The tenant has had a Membership, so a first administrator or a new template is refused. Use recovery only if no administrator is active | +| 409 | `lockey_administrator_exists` | Recovery refused: an Active administrator exists | +| 409 | `lockey_role_template_unknown`, `lockey_identity_foundation_refused` | The template or the resulting graph is not one the identity foundation admits | +| 409 | `lockey_host_taken` | The host is mapped to another tenant, or to this one with other flags; the answer never says which | +| 409 | `lockey_host_reserved` | The host is a platform host and can never resolve to a tenant | +| 409 | `lockey_organization_not_in_tenant` | The `organizationId` of a host mapping is not one of this tenant's | +| 409 | `lockey_concurrency_conflict` | Another change won, or a statement's lock timed out; repeat the same request. If it repeats, a second template of the same key and scope already exists | +| 503 | | The audit row could not be written, or the act could not take its ordered tenant lock (`lockey_dependency_unavailable`), so nothing changed. Retry after a short delay | + +The reason of a `409` is in the problem's `errors`, keyed by the body field it concerns, +as `{"slug": [{"key": "lockey_slug_taken"}]}`, or by `$` when it concerns the tenant as +a whole, as `{"$": [{"key": "lockey_tenant_has_memberships"}]}`. A `400` raised at the +gate or by a route check carries no `errors`. + +A business refusal of an admitted act (a `409`) writes a `failed` audit row in the +tenant, so the attempt is on the record. A refusal at the gate (`401`, `403`, or a `400` +for the ticket) writes none: it leaves a counter and a log line, and the operator is not +yet an admitted actor of any tenant. + +## Repeating an act + +Every act is idempotent on the ids you chose, so any failure that leaves you unsure, a +timeout or a connection reset or a `500` after a commit, is answered by sending the same +request again. The retry finds what was written and answers `200` from the stored +record; it never writes a second tenant, Role, Membership or mapping. It does record +itself: the repeated act commits its ordinary audit rows as a `success` with no entity +or before and after state, so a repeat is visible in the trail as the repeat it is. A +retry whose ids match but whose other values differ, a changed display name or +organization slug for example, is refused as `lockey_identifier_taken` or +`lockey_slug_taken` rather than changing the record. A retry of the first administrator +or of a Role act still answers after the new administrator has edited the template. The +host-mapping retry also drops the host's cached resolution again, which repairs a miss +cached between the first run's invalidation and its commit. + +## Reading the record + +Each act writes its MUST audit rows in its own transaction, in the target tenant, with +`actor_user_id` NULL, a closed reason slug (`tenant_provision`, `host_map`, +`role_initialize`, `first_admin_create`, `admin_recover`) and `metadata.operator` +carrying the issuer, the operator's subject digest, the accepted `acr` and the executor. +The ticket is not on these rows, because the tenant can read them. As the application +role, announcing the tenant inside a transaction, by the correlation id the answer +returned: + +```sql +BEGIN; +SELECT set_config('app.tenant_id', '', true); +SELECT timestamp, operation, outcome, reason, metadata->'operator' AS operator +FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; +COMMIT; +``` + +The operator's digest is computed as in [Killswitch](killswitch.md#reading-the-record). + +## Signals + +`learnstack_platform_operator_acts_total{operation,outcome}` counts each act as +`applied`, `replayed`, `refused` or `failed`; a `replayed` count is a setup resumed at +that step. Event 7109 (Warning) means an admitted act was refused as forbidden by the +request pipeline itself, which is a defect and not an operator mistake, and which writes +no audit row. The gate's counters and events 7101 to 7103, 7105 and 7106 are in +[operator access](operator-access.md); 7104, 7107 and 7108 belong to the killswitch. + +## Not recoverable here + +- **A host mapping's flags and organization pin.** No act updates or removes a mapping, + and a repeat that changes a flag or the pin is refused as `lockey_host_taken`. A + mistaken mapping stays until the platform owner repairs it at the database; escalate. +- **A wrong administrator.** A mistyped `sub` makes that person the administrator, and + this surface has no act to remove or replace them: the first administrator and + recovery both refuse once an administrator is active, and the database refuses to + revoke the last one. Confirm the `sub` before step 5, and escalate a mistake. +- **A tenant.** Nothing here renames, suspends or deprovisions one, or moves it to + another issuer. +- **Role templates after the first Membership.** They can no longer be created here; + the tenant's own administrators edit them. + +## What this does not do + +It does not verify DNS, issue TLS, send an invitation, set a plan or an entitlement, +create a Hub record, or deprovision a tenant. A tenant that needs an entitlement before +it serves is waiting on the Hub's push or the operator-configured default, which is the +Hub's runbook. Nothing here moves the deployment between identity issuers; that is a +separate offline act ([runbook](identity-issuer-rebind.md), +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md)). diff --git a/docs/standards/04-api-design.md b/docs/standards/04-api-design.md index 3c9908a3c..3ef1ae072 100644 --- a/docs/standards/04-api-design.md +++ b/docs/standards/04-api-design.md @@ -50,7 +50,15 @@ Examples: - `PATCH /api/v1/courses/{id}` - `POST /api/v1/courses/{id}/versions` -Platform-admin endpoints live under `/api/v1/platform/...` and require platform-admin scope. +Platform operator endpoints live under `/api/platform/v1/...`, outside the tenant +`/api/v1` contract and its OpenAPI document, and require a Platform-scope permission +([ADR-0101](../decisions/0101-platform-operator-authority.md)). The federation routes +(`GET /api/platform/v1/federation/brokers` and the `remove` and `disable` acts under it, +[ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)) take an +optional `ticket`, checked and recorded only on the platform scope's entry row and +never on a tenant-readable row, answer a refusal on the field it concerns, and answer +an act whose outcome is unknown, or whose completion could not be recorded after the +provider changed, `503` `dependency_unavailable` with `errors.outcome`. **P02d-4 Accepted contract — 2026-10-03.** Steps 2–3 deliver all four GET/HEAD read pairs; Step 4 delivers the contract/SDK controls. Institution diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index dfe326972..4a06ab706 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -925,9 +925,9 @@ CREATE POLICY platform_killswitches_read ON platform_killswitches USING (true); -- No write policy for learnstack_app, and no write privilege either — see the matrix --- below. Every toggle runs as learnstack_platform inside --- EnterPlatformAdminScope(reason), which is what gives tenancy.killswitch.toggle a real --- actor and a MUST-class audit row. No such caller ships in Packet 9 — see below. +-- below. Every toggle runs as learnstack_platform inside the admission-gated platform +-- scope, which is what gives tenancy.killswitch.toggle a MUST-class audit row that names +-- the operator. Its one writer shipped with P03-9 Step 1 — see below. ``` `USING (true)` widens nothing: there is no tenant term to widen, and the `GRANT` is what @@ -953,16 +953,13 @@ no context, `learnstack_app` reads **all** of `platform_killswitches`, which is `USING (true)` exists to guarantee. **Packet 9 shipped the table and the read path, and no writer.** The reason is -reachability rather than scheduling: every toggle runs inside -`EnterPlatformAdminScope(reason)`, the registered `IPlatformAdminGate` is -`DenyAllPlatformAdminGate`, and nothing can enter that scope until the Platform-scope -permission arrives with the registry in -[Phase 03](../roadmap/phase-03-identity-admin.md) — which owns the toggle command, its -permission and its runbook -([ADR-0045 Amendment 1](../decisions/0045-entitlement-and-feature-flag-socket.md)). The -`learnstack_platform` write grant in the matrix below is written ahead of its caller, -and no runtime path puts a row in the table until that phase lands. Every gated read -honours a flipped switch the day one exists; what is absent is the flipping. +reachability rather than scheduling: every toggle runs inside the platform scope, and no +Platform gate existed. P03-9 Step 1 ships the writer, a service entered with an operator +admission for `platform.killswitch.write` +([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md), +[ADR-0045 Amendment 5](../decisions/0045-entitlement-and-feature-flag-socket.md)); an +architecture rule confines the table's write verbs to it. The `learnstack_platform` +write grant in the matrix below is that writer's. The overlay is read through the L1 cache and invalidated on toggle, so the table itself is touched on a cache miss rather than on every request @@ -972,8 +969,10 @@ is touched on a cache miss rather than on every request The original four roles retain separate login credentials and connection strings. [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) -adds only the [confined fifth machine role](#provider-event-intake-storage); the -role model remains closed. +adds only the [confined fifth machine role](#provider-event-intake-storage), and +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) adds only the +[confined sixth rebind role](#controlled-issuer-rebind-storage); the role model remains +closed. | Role | Connection string | Present in | Used by | RLS posture | |------|---|---|---------|-------------| @@ -982,6 +981,7 @@ role model remains closed. | `learnstack_platform` | `ConnectionStrings:PlatformAdmin` | API host, worker host | `EnterPlatformAdminScope(reason)` and nothing else | `BYPASSRLS` | | `learnstack_outbox_admin` | `ConnectionStrings:OutboxDispatcher` | API host only; never Seeder or web | confined dispatcher infrastructure only | `BYPASSRLS` | | `learnstack_identity_ingress` | `ConnectionStrings:IdentityIngress` | API provider-ingress lane only | fixed minimized intake/claim/retire and scan/problem progress; no business/Audit/outbox grants | `NOINHERIT`, `NOBYPASSRLS` | +| `learnstack_identity_rebind` | `ConnectionStrings:IdentityRebind` | the offline rebind tool's environment only — **never** an API, worker, seeder or web host | `UPDATE (issuer)` on `identity_authority`, four `users` columns read, two audit rows inserted | `NOINHERIT`, `NOBYPASSRLS` | Migration **credentials** remain deploy-only. The five [enumerated Identity SECURITY DEFINER contracts](#confined-owner-functions) deliberately add runtime @@ -1026,6 +1026,13 @@ the fence omits and without which the grants add nothing: measured, an **unset** variable leaves the placeholder unbound and aborts init rather than creating a passwordless superuser-adjacent role — failing loud is the point. +The shipped script also creates the two confined roles after the four, with the same +shape and `NOINHERIT NOBYPASSRLS` (`ingress_pw` and `rebind_pw`), converges their +attributes, revokes every membership either holds or is granted, and adds both to the +`CONNECT` and schema `USAGE` grants. A missing password variable aborts initdb for them +as for the others. `DatabaseRoleTests` proves both log in, hold the declared attributes +and are taken back from an escalation. The fence below is the abridged baseline. + ```sql -- One-time provisioning, run once per database before the first migration. Ships as -- infra/compose/postgres-init/02-create-roles.sql in Phase 02a Packet 6. @@ -1093,7 +1100,7 @@ Step 3; contextual Membership/Role grants are implemented in Step 4. | `membership_role_assignments` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | | `roles` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | — | — | | `role_permission_grants` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | -| `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | — | — | +| `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | `SELECT` of `id`, `tenant_id`, `state` and `deleted_at` only ([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 11); exact [projection grant](#federation-operator-projection) | — | | `tenants` | `SELECT, INSERT, UPDATE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `organizations` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `tenant_domains` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT` | — | @@ -1105,12 +1112,12 @@ Step 3; contextual Membership/Role grants are implemented in Step 4. | `platform_killswitches` | `SELECT` | `SELECT, INSERT, UPDATE, DELETE` | — | | `idempotency_keys` | `SELECT, INSERT, UPDATE` | `SELECT, DELETE` | — | | `inbox_messages` | `SELECT`, `INSERT (tenant_id, subscription_id, event_id)` | — | — | -| `event_deliveries` | `SELECT`, acceptance-column `INSERT`, `UPDATE (processed_at)`; exact lists [below](#inbox) | — | routing/status-column `SELECT`, scheduling/status-column `UPDATE`; exact lists [below](#inbox) | -| `outbox_messages` | `SELECT, INSERT` | `SELECT, DELETE` | `SELECT`, `UPDATE (processed_at, attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at)` (P02b-2 Step 1) | -| `background_jobs` | RLS `SELECT`; envelope `INSERT`, admission/checkpoint `UPDATE` | — | Routing/status `SELECT, UPDATE` | +| `event_deliveries` | `SELECT`, acceptance-column `INSERT`, `UPDATE (processed_at)`; exact lists [below](#inbox) | inspection-metadata column `SELECT` ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)) | routing/status-column `SELECT`, scheduling/status-column `UPDATE`; exact lists [below](#inbox) | +| `outbox_messages` | `SELECT, INSERT` | `DELETE`, and `SELECT` of twelve inspection-metadata columns only ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md); the earlier table-wide `SELECT` is revoked) | `SELECT`, `UPDATE (processed_at, attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at)` (P02b-2 Step 1) | +| `background_jobs` | RLS `SELECT`; envelope `INSERT`, admission/checkpoint `UPDATE` | 27 metadata columns `SELECT`, no parameter, plan, trace, causal or capability column | Routing/status `SELECT, UPDATE` | | `background_job_attempts` | RLS `SELECT`; receipt `INSERT`, evidence `UPDATE` | — | Enumerated metadata `SELECT`, excluding outcome DTO | | `background_job_capacity` | RLS `SELECT, INSERT`; immutable-column `UPDATE` for row locking | — | `SELECT` | -| `background_job_reservations` | RLS `SELECT, INSERT`; positive-evidence release `UPDATE` | — | `SELECT` | +| `background_job_reservations` | RLS `SELECT, INSERT`; positive-evidence release `UPDATE` | `SELECT` of every column, for occupancy | `SELECT` | | `background_job_recurrences` | — | — | Manifest `INSERT`, control `SELECT, UPDATE` | | `background_job_occurrences` | — | — | Slot `INSERT`, control `SELECT, UPDATE` | | `background_job_recipients` | RLS `SELECT`; child receipt `UPDATE` | — | Route `INSERT`, routing `SELECT, UPDATE` | @@ -1207,11 +1214,14 @@ composition root registers a keyed `PrivilegedDataSource` facade from `LearnStack.Infrastructure.MultiTenancy.PlatformAdminScope`. The facade owns the separately credentialed lazy Npgsql pool without exposing it. Every synchronous or asynchronous acquisition checks the independent ordinary-job ceiling before pool -creation or reuse, under [ADR-0047](../decisions/0047-transactional-background-job-runtime.md). -`IPlatformAdminScope.EnterAsync(reason, …)` opens a **connection and a transaction** on -that guarded source and returns an `IAsyncDisposable` handle carrying both; -disposing without committing rolls back. Module code cannot resolve the data source; -`Platform_DataSource_Resolved_Only_By_PlatformAdminScope` enforces that. +creation or reuse, under +[ADR-0047](../decisions/0047-transactional-background-job-runtime.md). +`IPlatformAdminScope.EnterAsync(admission, …)` takes the `PlatformAdmission` the +operator gate minted (there is no caller-supplied reason), opens a **connection and a +transaction** on that guarded source and returns an `IAsyncDisposable` facade over both, +which exposes neither; disposing without committing rolls back. Module code cannot +resolve the data source; `Platform_DataSource_Resolved_Only_By_PlatformAdminScope` +enforces that. An earlier wording here — and in the glossary — said the scope opens "a DI scope whose `DbContext` is built on that data source". A connection is what shipped, for a reason @@ -1618,6 +1628,9 @@ CREATE INDEX ix_outbox_messages_recovery CREATE INDEX ix_outbox_messages_terminal ON outbox_messages (available_after, occurred_at, id) WHERE processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL; +-- ADR-0103: the operator inspection's dead-lettered page, in key order. +CREATE INDEX ix_outbox_messages_dead_lettered + ON outbox_messages (dead_lettered_at, id) WHERE dead_lettered_at IS NOT NULL; ALTER TABLE outbox_messages ENABLE ROW LEVEL SECURITY; ALTER TABLE outbox_messages FORCE ROW LEVEL SECURITY; @@ -1635,7 +1648,10 @@ CREATE POLICY outbox_messages_isolation ON outbox_messages -- DELETE; status transitions belong to the dispatcher and purging belongs to the -- audited platform scope. GRANT SELECT, INSERT ON outbox_messages TO learnstack_app; -GRANT SELECT, DELETE ON outbox_messages TO learnstack_platform; +GRANT DELETE ON outbox_messages TO learnstack_platform; +GRANT SELECT (id, tenant_id, organization_id, occurred_at, type, processed_at, attempts, + last_error, available_after, locked_until, terminal_reason, dead_lettered_at) + ON outbox_messages TO learnstack_platform; GRANT SELECT ON outbox_messages TO learnstack_outbox_admin; GRANT UPDATE (processed_at, attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at) @@ -1826,6 +1842,9 @@ CREATE INDEX ix_event_deliveries_recovery CREATE INDEX ix_event_deliveries_terminal ON event_deliveries (available_after, occurred_at, event_id, tenant_id, subscription_id) WHERE processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NOT NULL; +CREATE INDEX ix_event_deliveries_dead_lettered + ON event_deliveries (dead_lettered_at, tenant_id, subscription_id, event_id) + WHERE dead_lettered_at IS NOT NULL; ALTER TABLE event_deliveries ENABLE ROW LEVEL SECURITY; ALTER TABLE event_deliveries FORCE ROW LEVEL SECURITY; @@ -1901,6 +1920,10 @@ GRANT SELECT (tenant_id, subscription_id, event_id, organization_id, occurred_at GRANT UPDATE (attempts, last_error, available_after, locked_by, locked_until, terminal_reason, dead_lettered_at, replay_count, replayed_at) ON event_deliveries TO learnstack_outbox_admin; +GRANT SELECT (tenant_id, subscription_id, event_id, organization_id, occurred_at, + type, processed_at, attempts, last_error, available_after, locked_until, + terminal_reason, dead_lettered_at, replay_count, replayed_at) + ON event_deliveries TO learnstack_platform; ``` The app acceptance INSERT excludes all scheduling/completion/terminal columns; @@ -2144,6 +2167,12 @@ owns current review and qualification state. These limits add at most six retained connectors, not six per job or borrower; tests may reduce caps, deployment settings cannot widen them. They are bounded local concurrency choices, not throughput or fairness guarantees. +- Neither auxiliary source takes the shared rebind lock that authority qualification + and the User-creation admission take + ([§ Controlled issuer rebind storage](#controlled-issuer-rebind-storage)): they run + under the five-second startup deadline and no business advisory lock, and a start + that straddles a rebind already fails at the locking qualification or at their own + comparison of the stored issuer. - Both auxiliary sources use the same guarded `learnstack_app` role, actual database, installed identity authority and tenant/org RLS as business work. Neither has a raw general-DI datasource alias, generic SQL/callback API or @@ -4153,6 +4182,15 @@ GRANT INSERT (id, occurrence_id, tenant_id, organization_id, recurrence_key, rev ON background_job_recipients TO learnstack_outbox_admin; GRANT UPDATE (available_after, ownership_token, ownership_until, skipped_at, skipped_reason, last_error, quarantined_at) ON background_job_recipients TO learnstack_outbox_admin; +-- ADR-0103: the platform role reads job metadata for operator inspection through named columns only. +GRANT SELECT (id, tenant_id, organization_id, definition_key, profile, queue, capacity_group, + original_due_at, created_at, phase, normal_attempts, finalize_attempts, available_after, + ownership_kind, ownership_until, attempt_deadline, probe_after, unsuccessful_probes, last_error, + quarantine_reason, terminal_reason, processed_at, dead_lettered_at, finalization_status, + finalization_reason, business_finalization_incomplete, wake_generation) + ON background_jobs TO learnstack_platform; +GRANT SELECT (tenant_id, capacity_group, job_id, attempt_id, reserved_at, released_at, release_reason) + ON background_job_reservations TO learnstack_platform; REVOKE ALL ON FUNCTION public.fn_background_job_no_delete() FROM PUBLIC; @@ -4569,21 +4607,25 @@ driver's later no-op into cleanup evidence. The dispatch and bridge stores retain concrete connections and disposal tasks on connection-cleanup failure and seal later acquisitions. Each messaging store has -two fixed ownership slots for terminal-COMMIT reconciliation; the bridge has one -serialized SQL slot. These witnesses concern physical-source release, not all +two fixed ownership slots for terminal-COMMIT reconciliation and a third, reserved +for the operator recovery owner of [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md), +so an operator's reset can never take the slot the dispatcher's own reconciliation +needs and a second concurrent operator call is refused as unavailable; the bridge +has one serialized SQL slot. These witnesses concern physical-source release, not all application callbacks or private driver tasks. Failed opens rely on the pinned driver's qualified ordinary unwind; an arbitrary driver-cleanup fault is not a release guarantee. `BackgroundJobPhysicalCapacity` calculates the current Step 8 floor as -`W + 4P + 2C + 18 + U = 2W + 8P + 2C + 18`, where `W` is total workers, `P` is +`W + 4P + 2C + 20 + U = 2W + 8P + 2C + 20`, where `W` is total workers, `P` is pools, `C` is control pools and `U = W + 4P` is retained invocation owners. Each invocation issues at most one privileged routing, recovery acquisition, confirmation or checkpoint-history SQL operation at a time, including actual cleanup. A clean unavailable history retry follows cleanup in that same slot; it does not add another simultaneous checkout. The original eleven covers two shared components, four bridge calls, one bridge -SQL lane and two depth-two messaging lanes. Step 5 adds one batch-renewal slot, +SQL lane and two depth-two messaging lanes; the operator recovery owner adds one +lane in each messaging store, which makes thirteen. Step 5 adds one batch-renewal slot, one recovery slot plus its fresh-probe slot, and one terminal slot plus its fresh-probe slot. Step 8 adds one serialized recurrence SQL lane and one separately owned native recurring-manager call. The latter reuses its dedicated provider @@ -4591,7 +4633,7 @@ connection for its stock lock and write transaction. A held native call cannot consume another recurrence SQL slot. Failed cleanup retains the concrete owner and seals that lane; probes do not recursively acquire another probe. The default topology requires -**52**; the maximum valid topology requires **158**. Pooled startup refuses a +**54**; the maximum valid topology requires **160**. Pooled startup refuses a lower `MaxPoolSize` before bootstrap, using settings captured from the same immutable configuration as the source. Nonpooling remains allowed with the same owner bounds; its positive `MaxPoolSize` is not a physical-checkout cap. @@ -4605,6 +4647,7 @@ peak. Its complete acquisition ledger is: | `4P` | Per-generation metadata heartbeat, watchdog, cancellation watcher and lifecycle allowance; retained cleanup still belongs to that one generation. | | `2C` | Delayed and recurring schedulers, each with parallelism one and sequential reuse of its outer distributed-lock connection. | | Original eleven | Shared expiration and fetched-job heartbeat; four bridge native calls plus serialized SQL; two concrete slots in each messaging store. | +| Two operator lanes | The third slot of each messaging store, reserved for the operator recovery owner ([ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md)); a second concurrent operator call on a store is refused and does not wait. | | Five control slots | One batch renewal, control/recovery plus fresh probe, terminal plus fresh probe; unconfirmed cleanup seals each lane. | | Two recurrence slots | One serialized SQL flight and one native manager, including actual return and cleanup. | | `U` | One privileged routing/recovery/history/status flight per admitted invocation, including retained cleanup; application work uses the separate source. | @@ -4636,7 +4679,7 @@ including live work and unresolved receipt history; it does not add stock worker slots. Adding control pools adds neither terminal nor recipient application owners. External Prepare, read, Arm, Outcome, recovery checkpoints and fresh Finalize use the same sequential main/auxiliary inventory; their phase count is not a -connection multiplier. The facade fixture for privileged maximum 158 +connection multiplier. The facade fixture for privileged maximum 160 has eight pools of four workers, six of them control, and requires 42 application connections. Other worker distributions can share the same privileged maximum with a different application floor; neither maximum substitutes for calculating @@ -4719,8 +4762,10 @@ Qualify the anchor/configuration pair before enabling identity admission; the request path uses that immutable admitted configuration and performs no anchor lookup before the subject quota. A changed pair requires requalification, not live replacement of a request's verified authority. -P03-9/G13 owns a future controlled issuer rebind with verified continuity and a -freeze boundary; no runtime rebind owner is admitted here. +Only the controlled issuer rebind of +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) changes `issuer`, through the +[confined sixth role](#controlled-issuer-rebind-storage) used by one offline tool, +with verified continuity and a freeze boundary; no runtime role has a path to it. **Canonical subject-key encoding.** Compute SHA-256 over three concatenated length-prefixed byte strings: UTF-8 `learnstack.identity.subject.v1`, the stable @@ -5643,18 +5688,26 @@ rewriting the selected terminal status. ## Invitation entry and consumption -**Derives from:** [ADR-0093](../decisions/0093-verified-invitation-acceptance-and-handoff.md). -Implemented P03-4 contract; the -[phase Status](../roadmap/phase-03-identity-admin.md) owns qualification and follow-ups. This section extends the earlier global/contextual contracts; -the earlier eight-function/ten-setter counts describe their historical slices. -The delivered ADR-0093 baseline is eleven confined definers, eleven logical tenant -setters and four physical context writers. The [P03-5 extension](#custom-field-and-consent-storage) -implements twelve definers/twelve logical setters. The -[provider-event extension](#provider-event-intake-storage) brings the census to -fifteen definers/thirteen logical setters, preserving those four physical -writers; qualification remains source-bound in the phase Status. SMTP adds no tenant setter. -The [federation host-alias read](#federation-host-alias-read) is the fourteenth logical -setter; it adds no definer and no physical context writer. +**Derives from:** +[ADR-0093](../decisions/0093-verified-invitation-acceptance-and-handoff.md). Implemented +P03-4 contract; the [phase Status](../roadmap/phase-03-identity-admin.md) owns +qualification and follow-ups. This section extends the earlier global/contextual +contracts; the earlier eight-function/ten-setter counts describe their historical +slices. The delivered ADR-0093 baseline is eleven confined definers, eleven logical +tenant setters and four physical context writers. The +[P03-5 extension](#custom-field-and-consent-storage) implements twelve definers/twelve +logical setters. The [provider-event extension](#provider-event-intake-storage) brings +the census to fifteen definers/thirteen logical setters, preserving those four physical +writers; qualification remains source-bound in the phase Status. SMTP adds no tenant +setter. The [federation host-alias read](#federation-host-alias-read) is the fourteenth +logical setter; it adds no definer and no physical context writer. The +[operator subject resolution](#operator-subject-resolution) is the sixteenth definer; it +adds no logical tenant setter. The operator act executor that installs an operator act's +resolved context is a fifth logical writer of the context accessor, beside the four of +[ADR-0036 Amendment 2](../decisions/0036-tenant-resolution-trusted-inputs.md) (the Hub +correlation writer is the one not yet built); the earlier counts in this section +describe their own slices +([ADR-0040 Amendment 25](../decisions/0040-ambient-unit-of-work.md)). ### Invitation root and constrained transitions @@ -6159,7 +6212,9 @@ owns qualification. classes): `[TenantOwned]` only, no organization column, the tenant-wide EF filter, `ENABLE` and `FORCE` RLS with the one tenant-only isolation policy of [the canonical template](#tenant-owned-and-organization-scoped-tables), and -`SELECT`, `INSERT`, `UPDATE` to `learnstack_app` only — no `DELETE` grant. It is the +`SELECT`, `INSERT`, `UPDATE` to `learnstack_app` and a four-column `SELECT` to +`learnstack_platform` ([below](#federation-operator-projection)); no `DELETE` grant. +It is the eighth member of the `SchemaTableClasses` Identity contextual class. The forward-only migration refuses reversal. @@ -6213,6 +6268,26 @@ columns: that is NULL because a nullable pending or test column is NULL refuses: the guard fails closed. +### Federation operator projection + +**Derives from:** [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment +10 item 5 and Amendment 11 item 2. The operator's report asks one question of the +registry, whether a broker the realm lists still has a live row, and reads it as +`learnstack_platform` through four columns, which the platform role's `BYPASSRLS` +makes readable across tenants and the grant alone bounds: + +```sql +GRANT SELECT (id, tenant_id, state, deleted_at) ON public.federation_connections TO learnstack_platform; +``` + +The platform role receives no other privilege on the table: a statement that names the +alias, display name, issuer, client identifier, configuration digest or any other column +is refused by PostgreSQL, and so is every write. The grant is a forward-only migration +of the Identity chain, because the table is created there after the Platform chain has +run. The reader is the one statement of the operator's owner, which sees tombstones +and reads by primary key; the architecture census pins it whole, and tests read the +granted columns, refuse every other, and read two tenants' rows through the role. + ### Federation host-alias read **Derives from:** [ADR-0099 Amendment 6](../decisions/0099-confined-tenant-federation.md#amendment-6--host-alias-carrier-and-test-record-carrier-2026-11-14) @@ -6241,3 +6316,280 @@ pins its statements, implementation and caller; `Out_Of_Band_Setters_Open_Read_Only_Transactions` lists it among the own-connection readers. +## Operator onboarding storage + +**Derives from:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) and its +Amendment 1. An operator onboarding act runs on the application role under the ordinary +tenant announcement, so it adds no table, no policy and no table grant. It adds one +confined definer. + +### Operator subject resolution + +`users` is under forced row security keyed by identity settings that every tenant +announcement blanks, so a tenant transaction cannot read it. The act that names a first +administrator by provider subject needs the `UserId` of an Active user, so one definer +answers exactly that: + +- **Function.** + `public.fn_identity_operator_resolve_user(selected_authority uuid, selected_subject_key bytea) RETURNS uuid`, + `LANGUAGE plpgsql STABLE SECURITY DEFINER`, owned by `learnstack_migration` (whose + policy branch sees `users`), fixed `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC`, + `EXECUTE` to `learnstack_app` only. +- **Refusals.** Any session user but `learnstack_app`, an empty tenant announcement, a + read-only or non-`READ COMMITTED` transaction, a null argument, a key that is not 32 + bytes, and any authority id other than the one stored in `identity_authority`. Each + raises `23514` and reveals nothing. +- **Answer.** The `id` of the one `users` row with that authority and key whose `status` + is `Active` and whose `deleted_at` is null, otherwise null. It reads + `identity_authority` for its refusal check and `users` for its answer, and nothing + else, and it writes nothing. +- **Caller.** `OperatorSubjectResolver`, which derives the key with the one + `IdentitySubjectKey` implementation under the deployment's qualified authority, so a + request supplies the provider subject and nothing else. The body, ACL, owner and + volatility are pinned by the definer census (sixteen definers), and the callers of the + function and of its port by + [`Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject`](21-architecture-tests-catalogue.md#only_the_operator_administrator_core_resolves_an_operator_subject). + +A Membership written under that answer still passes the ordinary admission guard, which +re-reads the User's eligibility under the user fence, so the resolver is a lookup and +not an authority. + +**Residual.** The function is executable by `learnstack_app` and checks the session and +the arguments, not a witness bound to an operator act, as the invitation and consent +definers do. Any application-role transaction that announces a tenant can ask it whether +a provider subject is an Active user and receive the `UserId`. The key is an unkeyed +hash that supplies neither secrecy nor admission authority +([ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md)), so the answer +discloses that a person exists, not who they are or what they may do. The handlers check +that the act is live before they call it; no SQL-level binding is added. + +## Controlled issuer rebind storage + +**Derives from:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) and its +Amendment 1. The rebind changes one column of the one `identity_authority` row, from a +sixth login role used by an offline tool. It adds a role, exact column grants, four +policy changes, one trigger and one advisory-lock key, and **no** definer: the definer +census stays at sixteen. + +### The role + +`learnstack_identity_rebind` is `LOGIN NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB +NOCREATEROLE NOREPLICATION`, a member of nothing and with no member. Its credential is +`ConnectionStrings__IdentityRebind`, read by the tool from its own environment with +`Environment.GetEnvironmentVariable`, never by `GetConnectionString`, and confined to +the one tool file that reads it by +[`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool). +No API, worker, seeder, web or compose service receives it. The migration refuses with +a readable message when the role does not exist, because the roles script is its only +definition. + +A runtime role's membership in either confined role is not detected at runtime start, +because the guard of a runtime connection asks about bypass attributes. The roles script +revokes such a membership on every run, and the tool's own posture check refuses a role +that has one. + +### Grants, read from the column view + +Table-level views do not show column grants, so the census reads +`information_schema.column_privileges`, and the table-level census lists only the two +table-wide grants. + +| Object | Privilege | +|---|---| +| `identity_authority` | `SELECT`, and `UPDATE (issuer)` only | +| `users` | `SELECT (authority_id, subject_key, provider_subject, status)` only | +| `audit_log` | `INSERT` only, on every column; the policy bounds the row | + +It holds no function `EXECUTE` of its own, no sequence, no schema `CREATE` and no +database `CREATE`. `IdentityAuthorityRebindStorageTests` asserts the exact column set, +the absence of the rest, and each refusal as the role itself. + +### Policies + +One permissive policy per command is kept. `identity_authority_read` gains the role +beside the application role and the owner; a third policy, `identity_authority_rebind`, +admits `UPDATE` of the `id = 1` row to the role and nothing else; `users_isolation` +gains the role in its `USING` and keeps its `WITH CHECK`, so the role sees every user +and may write none. + +The `audit_log_isolation` policy is restated in its `WITH CHECK`, by the central audit +installer because no module names the table. The ordinary tenant arm now excludes this +role: that arm admits whatever tenant a session announces, any session can announce one, +and an arm that admitted the role there would let it write a row into any tenant's +trail. The rebind arm admits only the platform sentinel tenant, the identity module, no +organization, `Must` and `SecurityEvent`, entity type `IdentityAuthority`, reason +`issuer_rebind`, no actor, mail, address or agent, an operator attribution in +`metadata`, and exactly `identity.authority.rebind_attempt` with outcome +`indeterminate` or `identity.authority.rebind` with outcome `success`. The role has no +`SELECT` on the table, so it cannot read its own rows back. + +### The key trigger + +`fn_identity_authority_immutable_key()` is a `SECURITY INVOKER` trigger function, owner +`learnstack_migration`, `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC`, on `BEFORE +UPDATE` of `identity_authority`. It raises `23514` when `id` or `authority_id` changes, +for every role, so the stable key the subject keys hash cannot move even where a grant +would allow it. It is the thirtieth function and thirtieth trigger of the Identity +chain census. The issuer grammar stays in the tool and in qualification, not in SQL. + +### The lock + +One bigint advisory key, `IdentityAdvisoryLockKey.ForAuthorityRebind()`, SHA-256 over +the length-prefixed strings `learnstack.identity.lock.v1` and `authority-rebind`, the +first eight bytes as a big-endian signed integer, with an independently computed vector +pinned in `GlobalIdentityKeyTests`. The tool takes it **exclusive** +(`pg_advisory_xact_lock`) as the first statement of one direct, never-pooled +transaction. Authority qualification and the User-creation admission take the **shared** +form first and always before the subject lock, so the order is fixed and the tool, +which takes only this key, cannot form a cycle. + +- **Qualification** takes it after `SET TRANSACTION READ ONLY` and before its read; + under `READ COMMITTED` the next statement sees the rebind it waited for and compares + against the new issuer. It sets no `lock_timeout`, so a start that overlaps a rebind + waits until the command timeout (thirty seconds) and then fails with the fixed + qualification message, which stays failed until the process restarts. +- **The creation admission** takes it under its two-second `lock_timeout` and then reads + the stored authority and issuer, refusing with `IdentityAuthorityChangedException` + when they are not the facts the process qualified with. A creation during a rebind is + therefore refused after two seconds, not held. A lock alone would only delay a + creation from a process that qualified before the rebind; the comparison is what + refuses it. The refusal answers as the sibling storage failures do and is counted + in `learnstack_identity_lock_refusals_total{lock_kind="authority",reason="mismatch"}`. +- **The tool's reconciliation** of an unknown `COMMIT` takes the shared form too, so it + reads the issuer only once the original transaction has ended. +- [`Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock`](21-architecture-tests-catalogue.md#only_the_rebind_run_and_the_two_freeze_readers_take_the_rebind_lock) + pins the takers. + +### What the tool checks before it uses the role + +Server-side, as the role: `session_user` and `current_user` are the role; it is not +`INHERIT`, `BYPASSRLS`, superuser, `CREATEDB`, `CREATEROLE` or `REPLICATION`; it has no +membership either way, owns no relation, function or schema, and has no schema or +database `CREATE`; it holds no privilege, table, column or sequence, including the +maintenance privilege of PostgreSQL 17, on any other relation of `public`; and on the +three it uses it holds exactly the declared grants, compared column by column in both +directions, so an extra column privilege and a missing declared one both refuse. A +relation that belongs to an extension (`pg_depend` type `e`) is not counted, so the +`PUBLIC`-readable views of `pg_stat_statements` do not lock the tool out; any other +relation in `public` that the role can reach, a privilege through `PUBLIC` included, is. +The session's own `lock_timeout`, `statement_timeout` and +`idle_in_transaction_session_timeout` are read back from `pg_settings` and must be what +the tool asked for, so a connection pooler that drops startup options refuses the run +instead of silently removing the lock wait and the idle fence. A check the catalog +cannot answer is a failed check. Any other posture refuses the run before the lock, and +the refusal names the first check that failed as a closed `detail`. + +The freeze check counts sessions of the application, outbox, ingress and platform roles +in the database other than its own, from `pg_stat_activity`, which shows another role's +session with its role and database even where the statement is hidden. It runs before +the new realm is read and again immediately before the change. The server serves that +view from one snapshot per transaction, so each count first calls +`pg_stat_clear_snapshot()`, which every role may execute; without it the second count +would repeat the first and a host that starts while the proof runs, and never takes the +rebind lock, would not be seen. The tool turns Npgsql's application keepalive off and +asks the operating system for TCP probes instead: a client keepalive is a message, and +every message the server receives restarts its idle-in-transaction clock, so the +fifteen-minute fence that frees a hung tool's lock would never fire. + +### Proof + +Real PostgreSQL as the role itself and as each other role: +`IdentityAuthorityRebindStorageTests` (column privileges, the one admitted `UPDATE`, +the key trigger with the grant present, the `users` read, the two audit rows, every +refused variant, and the rows a role cannot widen by announcing a tenant), +`IdentityAuthorityRebindLockTests` (a start that waits for a rebind and then fails or +passes on the value it left, a creation refused within its timeout, a straggler refused +after the change), `IdentityAuthorityRebindTests` (the run end to end, every refusal +class and posture drift, the continuity rules, an audit failure rolling the change back, +a killed session, a lost commit acknowledgement and a reconciliation that waits) and +`IdentityAuthorityRebindToolTests` (the offline tool as a child process). The census +counts are in `GlobalIdentitySchemaTests` (thirty functions, sixteen definers, thirty +triggers) and the head pin in `MigrationRollbackTests`. + +## Operator recovery storage + +**Derives from:** +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) and its +Amendment 1. Operator inspection reads metadata through the platform role's column +grants, and the two fenced transitions run on the dispatcher's outbox role. The +canonical SQL of every grant and index named here is in the [Outbox](#outbox), +[Inbox](#inbox) and Background jobs blocks, which migration tests compare with the +applied schema, and the head of the Platform chain is pinned in +`MigrationRollbackTests`. + +### The platform role's inspection grants + +`learnstack_platform` holds `SELECT` on named columns of four tables and nothing +wider: twelve columns of `outbox_messages`, fifteen of `event_deliveries`, +twenty-seven of `background_jobs` and every column of `background_job_reservations`. +It never reads `payload`, `metadata`, `correlation_id`, `causation_id`, +`actor_user_id`, `topic`, `partition_key`, `locked_by`, a job's `parameters`, `plan`, +`plan_fingerprint`, `traceparent`, a causal column, `operation_id` or an ownership +or bridge token, so a statement that names one is refused by PostgreSQL itself. The +role kept `DELETE` on `outbox_messages` for the retention purge of +[Phase 11](../roadmap/phase-11-production-hardening.md), and the table-wide `SELECT` +it held beside it was revoked, because a column grant next to a table grant excludes +nothing. Column privileges are read from `information_schema.column_privileges`, as +for every column-grant table. The database bounds which columns a page can read and +the length of `last_error`, not its content, so the inspection shows a `last_error` +only when it has the shape of the dispatcher's descriptors. Two partial indexes, +`ix_outbox_messages_dead_lettered` and `ix_event_deliveries_dead_lettered`, serve +the dead-lettered scan the inspection pages by keyset, and a test asks PostgreSQL for +the plan of the statement the inspection runs. The migration builds them without +`CONCURRENTLY`, inside its transaction, as the earlier ledger indexes were. The +migration is forward-only. + +### The two transitions + +Both run on the outbox role, which already holds the column `UPDATE` grants they +need, the lifecycle `SELECT` of `tenants` and `INSERT` on `audit_log`: no write +grant was added. Each locks one row with `FOR UPDATE`, compares the fence the +operator read, checks the state, and updates under the same predicate with +`RETURNING old.*` and `new.*`, so the witness is built from what the statement did +and the row is written on the same transaction before `COMMIT`. Which fences and +which states are refused is decided by ADR-0103 (§ 2, § 3 and Amendment 1) and is +not restated here. + +- **Replay** fences one `(tenant, subscription, event)` row of `event_deliveries` + and writes that table only. The inbox row, the siblings and the producer row are + untouched. +- **Producer reset** fences one `outbox_messages` row and writes that table only. + It writes no delivery row. + +The timestamp of a fence is `timestamptz` to the microsecond. It is carried and +compared exactly, and a test presents a fence one microsecond off. + +### The operator lane + +Each messaging store has two slots for the dispatcher's own SQL owner and its +uncertain-COMMIT reconciliation and a third, reserved for the operator owner. The +operator never takes the dispatcher's slots, and a second concurrent operator call +on a store is refused. The lanes are two of the thirteen messaging and bridge slots +in the [capacity ledger](#shared-dispatcher-source-lifetime-and-capacity), which is +54 for the default topology and 160 for the maximum. The stores share one +unconfirmed-cleanup seal, so a cleanup fault on the operator lane seals the store +as one on the dispatcher's lanes does. + +### Proof + +Real PostgreSQL as each role: + +- `DeliveryDispatchStoreTests` and `OutboxDispatchStoreTests`: the current fence + applies; every stale variant, one microsecond included, refuses and changes + nothing; each refused state; a tenant that is not serving; a forced audit failure + rolling the change back; an admission for another operation, a stale one or a spent + one; the witness refusing each substituted field of the row and a transaction that + is not its own, and a witness reused on a later transition; a busy operator lane + that leaves the dispatcher's slots alone, in each store; a lost commit + acknowledgement; the real `OperatorRecovery` owner reaching the right store and + counting each outcome under its own operation; and the siblings and the inbox + byte-identical after a replay. +- `DeliveryInspectionTests`: pages and keyset cursors (equal instants and the + tenant, subscription and event tie-break included), a cursor refused under another + resource or state, the entry row, the job occupancy counts, the descriptor shape of + `last_error`, the exact columns the platform role can and cannot select, the two + indexes' keys and predicates and the plan of each dead-lettered page, and a + refused credential surfacing as a defect where an unreachable database is a + retryable outage. +- `PlatformOperatorHttpTests` and `PlatformAdminGateTests`: the routes, their + statuses and contract, and the pair of permissions, each held alone. diff --git a/docs/standards/06-testing.md b/docs/standards/06-testing.md index 88b5c691c..8a29719b1 100644 --- a/docs/standards/06-testing.md +++ b/docs/standards/06-testing.md @@ -237,6 +237,11 @@ source of truth; the finite workflow matrix must agree before launch. Actual Release discovery supplies assembly, case ID and FullyQualifiedName. Selected filters are independently rediscovered before execution; all theory rows stay with their selector. Advisory weights never define membership or a wall bound. +A theory's data must be serializable by xUnit, or discovery lists one case and +execution completes one id once per row, which the protocol refuses as +`completed_case_unexpected`; no local run shows it. `xUnit1044` and `xUnit1045` are +errors in `backend/tests/.editorconfig` for that reason: pass a label or a key and +build the object inside the test. `scripts/ci-test-shards.py` and `scripts/ci-test-shard-results.py` implement the two always-running aggregates under the unchanged backend/integration required diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index 872bb8087..2630d9e87 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -475,6 +475,15 @@ backend treat business rejections as system failures. | `learnstack_tenant_assertion_unresolved_total` | counter | dimension, source | | `learnstack_tenant_subject_admission_rejected_total` | counter | reason (`quota`, `registry_capacity`, `registry_fault`) | | `learnstack_tenant_subject_cleanup_failed_total` | counter | none | +| `learnstack_platform_operator_admissions_total` | counter | outcome (`admitted`, `refused`), operation (a registered slug or `unknown`) | +| `learnstack_platform_operator_refusals_total` | counter | cause (a closed set: token, profile and gate causes; [runbook](../runbooks/operator-access.md#signals)) | +| `learnstack_platform_operator_results_total` | counter | operation | +| `learnstack_platform_operator_federation_total` | counter | operation (`platform.federation.report`, `platform.federation.remove`, `platform.federation.disable`), outcome (a report's `ok`, `invalid_cursor`, `unavailable`; an act's `applied`, `already_applied`, `not_found`, `not_owned`, `live_connection`, `not_applicable`, `refused`, `unavailable`, `uncertain`; [runbook](../runbooks/federation-operator.md#signals)) | +| `learnstack_platform_operator_recoveries_total` | counter | operation (`platform.delivery.replay`, `platform.delivery.reset`), outcome (`applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavailable`, `commit_unknown`; [runbook](../runbooks/operator-recovery.md#signals)) | +| `learnstack_platform_operator_audit_failures_total` | counter | operation | +| `learnstack_platform_operator_metadata_failures_total` | counter | none | +| `learnstack_identity_rebind_runs_total` | counter | outcome (`applied`, `already_applied`, `unknown`, or a `refused_` class; [runbook](../runbooks/identity-issuer-rebind.md#when-it-refuses)) | +| `learnstack_identity_rebind_continuity_total` | counter | class (`active`, `closing`, `closed`, `reported`, `unkeyable`, `missing_active`, `reappearing_closed`, `unbootstrapped`) | | `learnstack_db_query_duration_seconds` | histogram | module, operation | | `learnstack_outbox_pending_count` | gauge | — | | `learnstack_outbox_dispatch_duration_seconds` | histogram | event_type | @@ -523,7 +532,11 @@ backend treat business rejections as system failures. Accepted ADR-0072/0073/0074 require `lock_kind` closed to `subject`, `user`, `tenant`; wait `outcome` closed to `acquired`, `timeout`, `cancelled`, `fault`; and refusal -`reason` closed to `timeout`, `cancelled`, `fault`. No tenant, actor, subject, +`reason` closed to `timeout`, `cancelled`, `fault`. +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) adds `lock_kind=authority` +for the shared rebind lock a User creation takes, and `reason=mismatch` for a creation +that waited out a rebind and found the stored issuer was not the one its process +qualified with. No tenant, actor, subject, digest, raw issuer, SQL, correlation or exception text is a label. Typed closed binding diagnostic reasons remain separate from public Problem Details and are not trusted identity-refusal witnesses. A contextual lock-plan fault increments diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index 835055203..d5b94c2a4 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -159,10 +159,33 @@ LearnStack runs **two Keycloak realms** per - `learnstack` — the tenant-facing realm. All tenant admins, instructors, and learners authenticate here. The realm includes the tenant id in token claims; the API re-validates against the resolved tenant context. -- `learnstack-hub` — the **operator realm**, used **only** by the Hub operator portal - (`hub.learnstack.dev`). Tenant-facing apps **never** accept `learnstack-hub` tokens; - the internal API (`/api/internal/*`) **only** accepts `learnstack-hub` tokens plus - the mTLS client certificate. +- `learnstack-hub` — the **operator realm**, used by the Hub operator portal + (`hub.learnstack.dev`) and by LearnStack's platform operator surface + (`/api/platform/v1/*`, [ADR-0101](../decisions/0101-platform-operator-authority.md)). + Tenant-facing apps and the tenant API **never** accept `learnstack-hub` tokens; the + internal API (`/api/internal/*`) **only** accepts `learnstack-hub` tokens plus the + mTLS client certificate; and the platform operator prefix accepts operator tokens of + its pinned issuer only, for its own audience. The operator's onboarding acts + ([ADR-0102](../decisions/0102-production-tenant-onboarding.md)) run on the application + role, under row security, through the ordinary pipeline; the `BYPASSRLS` uses of the + operator surface are the platform scope's callers (the killswitch writer, the recovery + inspections and the federation report, remove and disable of + [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)), each behind + an entry row and a per-act admission. The federation acts reach the identity provider + only through the confined admin client and its operator port, after an intent row the + scope handle commits, and never read or remove a realm user. The executor that + installs an act's tenant context accepts only an admission the gate minted for that + act within the last 30 seconds and spends it once, and the seeder refuses to run + outside a Development deployment. The controlled issuer rebind + ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md)) is not an HTTP route at + all: an offline tool validates the same operator token with the same validator, admits + the act against the same per-act grant (`platform.identity_authority.admin`) and then + uses a sixth, confined database role + ([§ Confined identity-rebind role](#confined-identity-rebind-role)). Its realm + credential is an operator-supplied `view-users` client for the new realm, created for + the run and deleted after it; it is not a LearnStack runtime or federation + credential, and [ADR-0099](../decisions/0099-confined-tenant-federation.md)'s refusal + of user-level authority for LearnStack is unaffected. General rules: @@ -564,6 +587,32 @@ for the full strategy. Standards-side: `SET LOCAL` inside the ambient transaction — see § Tenant Context immediately below, which is the single authority for that placement. +### Confined identity-rebind role + +`learnstack_identity_rebind` is the sixth login role and the one login credential that +can change `identity_authority.issuer`; the owner credential is deploy-only and can +alter any policy. It is `NOINHERIT` and `NOBYPASSRLS`, holds a handful of column grants +and one policy arm, and is configured on no API, worker, seeder, web or compose service: +[`The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool`](21-architecture-tests-catalogue.md#the_identity_rebind_credential_is_named_only_by_the_rebind_tool) +confines the key to the one tool file that reads it, and the tool refuses to use a role +whose posture is not exactly the declared one. A column grant to a runtime role guarded +by a transaction setting was rejected, because any session can set the setting. The +role's `audit_log` access is bounded by a policy arm that excludes the role from the +ordinary tenant arm, so the tenant a session announces does not widen its rows. + +**Residual.** The operator token, the grant and the attribution in the audit rows are +checked by the tool, and the database does not force them: whoever holds the role's +password can change the issuer without the tool and write a rebind row of the admitted +shape, and the platform and outbox roles, which bypass row security, can write such a +row too. The grant and the password sit in the tool's one environment, so keeping the +person who writes it apart from the operator is a practice, and the password is retired +after the window ([runbook](../runbooks/identity-issuer-rebind.md#two-people)). A +database-enforced pairing of the change and its result row would need a confined +definer that reads `audit_log`, and is the maintainer's decision +([ADR-0104 Amendment 1](../decisions/0104-controlled-issuer-rebind.md), item 10). +[Database Standards](05-database.md#controlled-issuer-rebind-storage) owns the grants, +policies, trigger and lock. + ### Confined event dispatcher ADR-0046 accepts this P02b-2 boundary. Step 1 implements source/role guards; diff --git a/docs/standards/12-infrastructure.md b/docs/standards/12-infrastructure.md index 9649120f8..d30550bf1 100644 --- a/docs/standards/12-infrastructure.md +++ b/docs/standards/12-infrastructure.md @@ -362,7 +362,9 @@ Budgets are reviewed quarterly. Cost dashboards drive the next review. - RTO target: 4 hours for production restore. - RPO target: 15 minutes (WAL archiving cadence). -- Runbooks live in `docs/runbooks/` (Phase 11 deliverable). +- Runbooks live in `docs/runbooks/`. Phase 03 begins them with the platform operator + runbooks ([ADR-0101](../decisions/0101-platform-operator-authority.md) to + [ADR-0104](../decisions/0104-controlled-issuer-rebind.md)); Phase 11 completes the set. - Annual full DR drill required. ## Forbidden diff --git a/docs/standards/13-documentation.md b/docs/standards/13-documentation.md index 457965c0e..e90ab067d 100644 --- a/docs/standards/13-documentation.md +++ b/docs/standards/13-documentation.md @@ -21,7 +21,7 @@ docs/ roadmap/ phase-NN-topic.md (with phase-NNa / phase-NNb splits for parallel tracks) phase-NN-delivery-log.md a phase's dated packet records (ADR-0069) standards/ NN-topic.md engineering rules - runbooks/ *.md operations procedures (Phase 11+) + runbooks/ *.md operations procedures (begun in Phase 03; Phase 11 completes) modules/ / per-module specs (one directory per module, created with its first spec) glossary.md terminology ``` diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index c99aad524..fbd4c50ad 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -222,13 +222,33 @@ will raise them — which this standard requires it to do. matrix. A copy is a second answer that passes every comparison the moment it agrees, so the matrix → catalogue direction refuses it, and the catalogue → matrix direction compares every row that carries a slug rather than the first. -- **A row can carry both markers**. `tenancy.killswitch.toggle` is - `(off-path)` because every write runs inside `EnterPlatformAdminScope(reason)` rather - than through the pipeline, and `(planned)` because Packet 9 ships the table, the policies - and the read path but no writer — - [Phase 03](../roadmap/phase-03-identity-admin.md) owns the toggle command, its - Platform-scope permission and its runbook - ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). +- **A row can carry both markers**. `tenancy.entitlement.refresh` is `(off-path)` + because its writer is a port method rather than a request, and `(planned)` because no + real provider exists yet. `tenancy.killswitch.toggle` carried both until P03-9 Step 1 + shipped its writer + ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)); it keeps + `(off-path)` because the write runs inside the platform scope rather than through the + pipeline. The controlled issuer rebind's two rows, + `identity.authority.rebind_attempt` and `identity.authority.rebind` + ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 8), are `(off-path)` for + the same reason one step further: they are written by an offline tool on its own role + through two witness-bound methods, under the platform sentinel, with no actor and the + ticket in `metadata.operator`. The operator recovery operations of + [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) are + `(off-path)` too: `platform.delivery.inspect` is the admitted operation whose + reason `delivery_inspect` the platform scope's entry row carries, and + `platform.delivery.replay` and `platform.delivery.reset` are + written on the dispatcher's outbox-role transaction through one witness-bound method, + under the real event tenant, with no actor, the operator attribution and the fence in + `metadata`, and no ticket, because a tenant can read the row. The operator federation + operations of [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10 + and 11 are `(off-path)` as well: `platform.federation.report` is audited by the + platform scope's entry row, and `platform.federation.remove` and + `platform.federation.disable` each write an intent row on their `_attempt` slug at the + scope handle's checkpoint, with the outcome `indeterminate`, committed before the + provider call ([ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md)), and a + completion row on their own slug. Both rows name the tenant the owner marker names + and carry no ticket and no tenant-authored text. ## Baseline Coverage (LearnStack Core Modules) @@ -318,18 +338,32 @@ Rules: member name on the wire and in the column, which is why the example above reads `Create` and `Must` where the tables read `create` and **MUST**. - `outcome` is one of `success`, `denied`, `failed`, `indeterminate` - ([ADR-0044 § 5](../decisions/0044-audit-write-path.md); ADR-0016's `is_success boolean` - is superseded, because a boolean cannot carry `denied`). `denied` is used when an - authorisation check rejects the operation — these MUST be audited so we can detect - probing. `indeterminate` is the commit whose server-side outcome is unknown: the - standalone re-write carries the **same** `id` as the in-transaction attempt, and the - pair is what a reviewer reads as one commit in doubt. `PostgresAuditStore` supplies - `occurredAt` from `IClock` — the intent's declaration time in the transaction, a fresh - reading for a standalone re-write — which is what keeps that pair legal under the - composite primary key `(id, timestamp)`. This describes ordinary resource - reconciliation; [trusted denial occurrences](#trusted-authorization-evidence) - instead retain one fixed key, timestamp and draft. -- `reason` is required when the operator is a platform admin acting on a tenant they are not a member of. It is `EnterPlatformAdminScope(reason)`'s short operator-authored slug naming the operation — never caller-supplied text — and it is surfaced in the tenant admin's audit view. A refusal's cause is not a `reason`: it is the refusal's message key, in the `error_key` column. + ([ADR-0044 § 5](../decisions/0044-audit-write-path.md); ADR-0016's + `is_success boolean` is superseded, because a boolean cannot carry `denied`). `denied` + is used when an authorisation check rejects the operation — these MUST be audited so + we can detect probing. A Platform operator admission refusal is tenantless and outside + that population: it leaves a counter and a Warning log + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 11), and an + authorization refusal of an operator act inside the pipeline leaves a counted + `refused` outcome and a Warning, event 7109, with no durable row + ([ADR-0033 Amendment 14](../decisions/0033-audit-durability-model.md)). A business + refusal of an admitted operator act writes the ordinary `failed` row in the target + tenant, with `actor_user_id` NULL, the closed reason slug and `metadata.operator`. + `indeterminate` is the commit whose server-side outcome is unknown: the standalone + re-write carries the **same** `id` as the in-transaction attempt, and the pair is what + a reviewer reads as one commit in doubt. `PostgresAuditStore` supplies `occurredAt` + from `IClock` — the intent's declaration time in the transaction, a fresh reading for + a standalone re-write — which is what keeps that pair legal under the composite + primary key `(id, timestamp)`. This describes ordinary resource reconciliation; + [trusted denial occurrences](#trusted-authorization-evidence) instead retain one fixed + key, timestamp and draft. +- `reason` is required when the operator is a platform admin acting on a tenant they are + not a member of. It is the closed reason slug of the registered operator operation + (`PlatformOperation.ReasonSlug`) — never caller-supplied text — and it is surfaced in + the tenant admin's audit view when the row targets that tenant. Rows under the + platform sentinel are visible to no tenant + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 9, § 10). A refusal's + cause is not a `reason`: it is the refusal's message key, in the `error_key` column. - `correlationId` matches the trace id in logs and the value in the Problem Details response for failures. - `changes` is always a JSON **array** of `{ path, before, after }`, never the polymorphic object-or-array shape ADR-0016 described. A reader that has to branch on the shape gets diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 911f0ad7a..1268a56bd 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,16 +92,49 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.tenant.write`, `platform.feature_flag.admin`, `platform.audit.read` | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write`, `platform.identity_authority.admin`, `platform.delivery.read`, `platform.delivery.write`, `platform.federation.read` and `platform.federation.admin` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | +The registered Platform catalogue is `PlatformPermissions` in `LearnStack.SharedKernel`, +apart from the tenant registry and never assignable, so the served tenant document does +not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authority.md) § +5). A key is registered with the operation that has a denied proof for it: + +| Key | Operation | Packet | +|---|---|---| +| `platform.killswitch.write` | `tenancy.killswitch.toggle` | P03-9 Step 1 | +| `platform.tenant.write` | `tenancy.tenant.create` (tenant provisioning), `tenancy.hostmapping.write` (host mapping) | P03-9 Step 2 | +| `platform.tenant_bootstrap.write` | `identity.role.initialize`, `identity.membership.create_first_admin`, `identity.membership.recover_admin` | P03-9 Step 2 | +| `platform.identity_authority.admin` | `identity.authority.rebind` (the controlled issuer rebind, an offline tool and not a route) | P03-9 Step 3 | +| `platform.delivery.read` | `platform.delivery.inspect` (metadata-only inspection of dead-lettered work and quarantined jobs, in the platform scope) | P03-9 Step 4 | +| `platform.delivery.write` | `platform.delivery.replay`, `platform.delivery.reset` (the two fenced transitions, on the dispatcher's outbox role) | P03-9 Step 4 | +| `platform.federation.read` | `platform.federation.report` (the report of orphaned, unreadable and nonconforming identity-provider brokers, in the platform scope) | P03-9 Step 5 | +| `platform.federation.admin` | `platform.federation.remove`, `platform.federation.disable` (the two provider changes, each with an intent and a completion row) | P03-9 Step 5 | + +The five onboarding acts of +[ADR-0102](../decisions/0102-production-tenant-onboarding.md) run under the +`PlatformOperator` authorization source, which is not a Membership candidate: their +policies are `FiniteTrusted` with that single source, the business actor of every row +they write is `UserId.SystemActor`, and the operator is recorded in audit only. The +grant is evaluated by the gate on every act, never cached across acts. The rebind of +[ADR-0104](../decisions/0104-controlled-issuer-rebind.md) is not an act of that executor +and not a route: the scope refuses an operation that needs no platform role, and the +executor runs only the closed catalog of five onboarding acts, which refuses the rebind +operation by construction (`PlatformOperatorActCatalog`). The offline tool that consumes +the admission validates the same token and evaluates the same grant. The two recovery +transitions of [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) +are likewise not pipeline acts: each operation records where it runs +(`PlatformOperationExecutor`: the pipeline, the platform scope, the offline tool or the +recovery owner), and the catalog admits only the first. + Tenant permissions are only meaningful inside an admitted tenant scope. Organization grants require an eligible Membership for that exact organization. An explicit eligible Tenant grant can independently authorize the declared -operation; same-key pairs never imply one another. Platform admission remains -P03-9 and requires its privileged authentication/audit contract (see -[18-audit-coverage.md](18-audit-coverage.md)). +operation; same-key pairs never imply one another. Platform admission is decided by +[ADR-0101](../decisions/0101-platform-operator-authority.md) (operator scheme, per-act +grants held by LearnStack, a separate non-assignable catalogue) and ships in P03-9 with +its audit contract (see [18-audit-coverage.md](18-audit-coverage.md)). Registered architecture obligation `Permission_Scope_Matches_Resource_Scope` requires permissions registered as diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index 44e617aed..190e48054 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -259,9 +259,9 @@ adapter trigger. admits the two families by **enumeration**, so the overlay's own four-segment per-key spelling is refused rather than merely unused: one entry holds the whole switch set, because `ICacheService` has no `RemoveByPrefixAsync` for a toggle to - sweep a per-key family with. The toggle that invalidates it arrives with the - Platform-scope permission in [Phase 03](../roadmap/phase-03-identity-admin.md) - ([ADR-0045 Amendment 1](../decisions/0045-entitlement-and-feature-flag-socket.md)). + sweep a per-key family with. The toggle that invalidates it is + `KillswitchToggle`, which drops the entry after its commit + ([ADR-0101 § 13](../decisions/0101-platform-operator-authority.md)). Every `ICacheService` implementation calls `CacheKey.EnsureValid`, and none re-prefixes. There is no query filter and no RLS policy in front of a dictionary, so the key is the entire isolation boundary — which is why the shape is validated rather @@ -486,8 +486,14 @@ after its outcome settled; the timeout is 2.5 s, the circuit breaker on, and the bulkhead exactly 4 without a queue. These values are fixed: the composition root refuses any other value at startup, and refuses breaker parameters outside the ranges the provider specification states. -The operator egress allow-list `Federation:Egress:AllowedHosts` is composition -configuration, never tenant input. The +The same class implements the operator port `IFederationOperator` +([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendments 10 to 13), +held only by the operator's owner and by the adapter, and built as a second instance +with its own `IProviderResilience` pipeline of the same fixed +shape so that an operator sweep cannot starve a tenant's calls; its fail-closed default +is registered beside the provider's. It adds one provider route, a paged listing of +the realm's instances. The operator egress allow-list `Federation:Egress:AllowedHosts` +is composition configuration, never tenant input. The [provider specification](../modules/identity/providers.md#tenant-federation-adapter) owns the admitted calls, profile and egress rules; the [realm runbook](../../infra/keycloak/README.md#federation-administration-client) owns the @@ -793,6 +799,15 @@ actual routing/terminal identity and a validated attempt trace; it adds no causal-envelope or payload read to the bypass scheduler. See [Audit Coverage](18-audit-coverage.md#required-behaviours). +The dispatcher's two stores have a second writer, the operator recovery owner of +[ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md): a fenced +subscriber replay and a narrow producer reset, each behind an operator admission and +each writing its MUST row through a sibling witness (`OperatorRecoveryTransition`) on +the same outbox-role transaction. The owner holds no credential: it is a DI consumer of +the two stores, whose third connection slot is reserved for it, and `IOperatorRecovery` +is the only port the two acts hold. The inspection that precedes a reset runs in the +platform scope on column grants through `IDeliveryInspection` and writes no change. + ## Background Jobs and Hangfire Accepted [ADR-0047](../decisions/0047-transactional-background-job-runtime.md) diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 295d3b39e..f42b9b1aa 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -177,24 +177,23 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**377 test methods run in +**393 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), -[Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, Packet 7, -Packet 8, Packet 9, Packet 10, P02d-1, P02d-2, P02d-3, P02d-4 Steps 1–3, P02b-1, -P02b-2 Steps 2–4, P02b-3 Steps 3–6 and P02b-4 Steps 1–8, with further -source-boundary, observation and production-manifest companions in Step 9. -Its nineteen packet obligations are implemented with actual canonical owners and -complementary structural, native-runtime and PostgreSQL controls. The +[Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, +Packet 7, Packet 8, Packet 9, Packet 10, P02d-1, P02d-2, P02d-3, P02d-4 Steps 1–3, +P02b-1, P02b-2 Steps 2–4, P02b-3 Steps 3–6 and P02b-4 Steps 1–8, with further +source-boundary, observation and production-manifest companions in Step 9. Its nineteen +packet obligations are implemented with actual canonical owners and complementary +structural, native-runtime and PostgreSQL controls. The [P02b-4 merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) -owns its final review/CI qualification. Authentication, realm and BFF obligations -have unit/integration/frontend/offline owners in their entries below; the -[Phase 02b Status block](../roadmap/phase-02b-events-auth.md) links current delivery -and qualification. The analyzer and asynchronous inventory controls also have -actual owners; registration alone promotes none of these obligations. -Methods are not rows: -a `[Theory]` is one row and many cases, -and most rows pair a rule with the companion assertion that stops it passing vacuously. +owns its final review/CI qualification. Authentication, realm and BFF obligations have +unit/integration/frontend/offline owners in their entries below; the +[Phase 02b Status block](../roadmap/phase-02b-events-auth.md) links current delivery and +qualification. The analyzer and asynchronous inventory controls also have actual owners; +registration alone promotes none of these obligations. Methods are not rows: a +`[Theory]` is one row and many cases, and most rows pair a rule with the companion +assertion that stops it passing vacuously. **Every number in this section is recomputed by `The_Catalogue_Counts_Its_Own_Rules`.** They are a second copy of what the repository already knows, and the first version of this section @@ -218,7 +217,7 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**282 rules in this catalogue are Implemented, and 164 of them are in that assembly.** +**293 rules in this catalogue are Implemented, and 175 of them are in that assembly.** The other 118 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite @@ -1878,13 +1877,15 @@ catalogue as the carrier of their status — so all three are Packet 10's. and every `DbContext` service in it is one `AddModuleDbContext` registered — scoped, from an implementation factory, never a type registration EF could give its own connection. Under `backend/src`, the configuration/construction scan - admits exactly **thirteen** files: six design-time factories, one per migration + admits exactly **sixteen** files: six design-time factories, one per migration chain; `ModuleDbContextRegistration`, which passes a *connection*; `PersistenceCompositionExtensions`, with the guarded platform-role builder; `ApplicationDataSource`, shared by the API and one-shot Seeder; - ADR-0046's confined `OutboxDispatcherDataSource`; and ADR-0072's deployment-only - `LearnStack.Tools.IdentityAuthorityInstaller/Program.cs`; and ADR-0076/0077's - private authorization and evidence source builders. Another construction + ADR-0046's confined `OutboxDispatcherDataSource`; ADR-0072's deployment-only + `LearnStack.Tools.IdentityAuthorityInstaller/Program.cs`; ADR-0076/0077's + private authorization and evidence source builders; the invitation SMTP and + provider-event intake sources; and ADR-0104's `IdentityIssuerRebind`, which opens + the rebind role's own direct connections. Another construction site requires its owning decision and an explicit allow-list change. A context on its own connection never saw the announcement, so every read through it returns zero rows under the corrected policy — silently. @@ -2070,6 +2071,13 @@ diagnostic above row security, not the boundary, as its own note says. connection after grant removal, for both direct and transitive membership. - **Phase:** 02b, P02b-2. +- **Accepted extension:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) + adds exactly one more consumer of the two stores' connections, the operator recovery + owner `OperatorRecovery`, which holds no credential and reaches the outbox role only + through each store's reserved operator lane. The dispatcher census pins the stores' + recovery methods and their parameters, and + [OperatorRecoveryBoundaryTests](../../backend/tests/LearnStack.Tests.Architecture/OperatorRecoveryBoundaryTests.cs) + closes who may mint the recovery witness and who may write its row. - **Accepted extension:** ADR-0047 preserves this canonical name while adding enumerated H1 credential consumers and the minimal lifecycle reader. P02b-4 Step 2 implements role/table grants; Step 4 adds the closed facade, source pin @@ -2793,10 +2801,13 @@ promotes an unrun proof. [source ledger](05-database.md#authorization-and-evidence-source-ledger). - **Type:** source/caller/role census plus real app-role PostgreSQL/PgBouncer progress and lifetime controls. **Kind:** behavioural and structural. -- **Test owners:** `IdentityAuthorizationReaderTests`, - `AuthorizationReadSourceTests`, `AuthorizationPoolProgressTests`, - `IdentityAuthorizationConventionTests`, `TrustedOperationSourceConventionTests`, - `OperationPolicyOwnershipTests`, `IdentityAuditConventionTests`. +- **Test owners:** `IdentityAuthorizationReaderTests`, `AuthorizationReadSourceTests`, + `AuthorizationPoolProgressTests`, `IdentityAuthorizationConventionTests`, + `TrustedOperationSourceConventionTests`, `OperationPolicyOwnershipTests`, + `IdentityAuditConventionTests`. `TrustedOperationSourceConventionTests` pins four + minting sources, the seed, delivery, job and operator-act owners + ([ADR-0102](../decisions/0102-production-tenant-onboarding.md)), and the operator + source's one caller and its closed evidence lifetime. - **Status:** **Implemented** — `IdentityAuditConventionTests`; source/caller controls complement the real PostgreSQL/PgBouncer owners above. - **Coverage:** the confined reader/source, actual PostgreSQL/ @@ -3777,9 +3788,13 @@ which decides identity, multiplicity, capture and classification; `The_AppendOnly_Sweep_Can_Actually_Fail`, that checks the pattern against the shapes it must catch and the shapes it must not, because with no offending statement anywhere the sweep passes whether it works or matches nothing; and a reflection check, - `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly eight - write methods and no update: the event/job seams ship in Phase 02b, and - ADR-0072's two global seams ship in P03-1 Step 3. None + `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly fifteen + write methods and no update: the event/job seams ship in Phase 02b, ADR-0072's two + global seams in P03-1 Step 3, the two trusted authorization seams in P03-2, the + operator result seam of ADR-0101 in P03-9 Step 1, the two controlled-rebind seams + of ADR-0104 in P03-9 Step 3, the operator recovery seam of ADR-0103 in P03-9 + Step 4 and the platform scope's intent seam of ADR-0044 Amendment 18 in P03-9 + Step 5. None of the three sanctioned redaction sites exists yet — they land in Phase 03 and Phase 11 — so the exemption set ships with the rule **empty**, as exact paths: the first site to land adds its own path, so it is exempted by name rather than the pattern @@ -5703,29 +5718,34 @@ structural test proves — and what it does not. #### `SetTenant_Callers_Are_The_Enumerated_Four` - **Asserts:** `ITenantContextAccessor.Current` is **written** only by the HTTP, - internal Hub, job and integration-event boundaries. ADR-0047 names JobExecutor - as the sole job-path writer, replacing the unshipped Hangfire JobActivator. - `EnterPlatformAdminScope` opens a separate connection and writes no tenant - context. Reads are unconstrained; no new writer is admitted before it ships. + internal Hub, job, integration-event and operator-act boundaries. ADR-0047 names + JobExecutor as the sole job-path writer, replacing the unshipped Hangfire + JobActivator; `PlatformOperatorActExecutor` is the operator-act writer + ([ADR-0040 Amendment 25](../decisions/0040-ambient-unit-of-work.md)). + `EnterPlatformAdminScope` opens a separate connection and writes no tenant context. + Reads are unconstrained; no new writer is admitted before it ships. - **Source:** ADR-0036 § Rules, second bullet, as corrected by its erratum and [Amendments 2 and 12](../decisions/0036-tenant-resolution-trusted-inputs.md). - **Type:** xUnit + source scan. **Kind:** structural. - **Status:** **Implemented** (`TenantContextConstructionTests`, Packet 7 step 5). - **Phase:** 02a (Packet 7). - **Note:** the name predates the correction and is kept. `ITenantContextAccessor` - declares one member, `ITenantContext? Current { get; set; }`, and the `SetTenant` - this row used to name has never existed; ADR-0036 Amendment 2 fixes the ADR and - keeps the test's spelling, because § Canonical names makes a rename its own - liability and the name describes the caller set, which is what ADR-0036 decides. + declares one member, `ITenantContext? Current { get; set; }`, and the `SetTenant` this + row used to name has never existed; ADR-0036 Amendment 2 fixes the ADR and keeps the + test's spelling, because § Canonical names makes a rename its own liability and the + name describes the caller set, which is what ADR-0036 decides. The set is five logical + writers since the operator executor landed (ADR-0036 Amendment 22), and the name is + kept for the same reason. - **Note:** a source scan rather than NetArchTest: NetArchTest resolves *type* references and cannot see a write to a property, which is the whole assertion — the same reason `Effective_Host_Computed_In_One_Place` is a scan. The needle (`.Current =`) is receiver-agnostic, so an unrelated `Activity.Current =` would trip it; that is a false positive to exempt by path, never a reason to filter by folder. -- **Note:** **three of the four logical boundaries exist** — TenantResolverMiddleware, +- **Note:** **four of the five logical boundaries exist** — TenantResolverMiddleware, the integration-event acceptance/execution scope in InProcessEventBus and - DeliveryExecutor, and JobExecutor's framework/business partials. The two JobExecutor - files are one logical writer. HubCorrelationMiddleware belongs to Phase 02c. + DeliveryExecutor, JobExecutor's framework/business partials and the operator act + executor. The JobExecutor partials are one logical writer. HubCorrelationMiddleware + belongs to Phase 02c. The whole-source census also refuses every writer outside the exact file set. The first version of the test scanned only files whose path contained `Tenancy`, which deleted the `InProcessEventBus` writer from its own expectation *and* let a @@ -5875,46 +5895,233 @@ structural test proves — and what it does not. #### `PlatformAdminScope_Entry_Requires_Platform_Permission` -- **Asserts:** `EnterPlatformAdminScope(reason)` cannot open without an authenticated principal holding a Platform-scope permission, and no handler carries both `[AllowsUnresolvedTenantContext]` and a platform-scope entry. -- **Source:** ADR-0036 § The platform-admin override is not a resolution source. -- **Type:** xUnit — reflection, a source scan, and a call to the registered gate. - **Kind:** structural (the marker and the scan) + behavioural (the gate refuses). -- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, Packet 7 step 7) — conjunct A only. -- **Phase:** 02a (Packet 7). -- **Note:** **the permission clause is live in its mechanism and vacuous in its subject; - the marker clause is vacuous outright.** Two Notes previously stood here assigning - "live" to opposite clauses — one written when the rule was Registered and one when it - landed — and this replaces both. - - *Mechanism, live:* the gate is a real port, the registered implementation refuses - everyone, `PlatformAdminScope` consults it, and no second implementation exists in any - production assembly — which is how a permissive default actually arrives, registered - elsewhere for a demo. The ordering, gate before the credential is touched, is +- **Asserts:** entering the platform scope takes a `PlatformAdmission` and nothing else, + and the censuses that make an admission mean something are closed across every + production assembly: `PlatformAdmission.Minter` has exactly one subclass, the operator + gate; `PlatformOperatorWitness.Minter` has exactly one, the private nested minter of + `PlatformOperatorTokenProfile`; `IPlatformOperatorGate` and + `IPlatformOperatorGrantSource` each have exactly one implementation. The census + compares full type names and counts abstract subclasses, so a lookalike in another + namespace or an abstract stand-in is a failure. A second of any of them is how a + permissive default ships. +- **Source:** ADR-0036 § The platform-admin override is not a resolution source; + [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and § 8. +- **Type:** xUnit — reflection over every production assembly, and behavioural cases + without Docker (`PlatformAdminGateTests`) and over HTTP with controlled signed tokens + (`PlatformOperatorHttpTests`). **Kind:** structural + behavioural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, Packet 7 step 7; + rewritten against the real gate by P03-9 Step 1). +- **Phase:** 02a (Packet 7); P03-9. +- **Note:** the rule was live in its mechanism and vacuous in its subject while the + registered gate refused everyone. It now has a subject: a Platform permission exists + (`PlatformPermissions`), an operator can hold it through a grant, and a permitted + entry is exercised. The ordering — admission before the credential is touched — is behavioural and asserted in `PlatformAdminGateTests`; a structural rule cannot see it. - - *Subject, vacuous:* there is no Platform permission to hold. The canonical - `AuthorizationBehavior` uses explicit live policies, while the retained - assignable manifest contains only Tenant/Organization pairs. API authentication - is delivered under ADR-0064; the Platform-scope permission remains Identity work in - [Phase 03](../roadmap/phase-03-identity-admin.md). So - nothing exercises a *permitted* entry, and the gate refusing everyone blocks nothing - this packet ships. Packet 9 gives the scope its first real work and inherits the gate: - the platform-scope `security-event` row the scope writes on entry through - `IAuditStore.WritePlatformScopeAsync` - ([ADR-0044 § 10](../decisions/0044-audit-write-path.md)). The killswitch toggle is not - that caller. Packet 9 ships `platform_killswitches`, its policies, the overlay and the - cache family and **no writer at all**: a toggle command would sit behind - `DenyAllPlatformAdminGate` carrying a permission key nothing registers, so - [Phase 03](../roadmap/phase-03-identity-admin.md) owns the command, its permission and - its runbook - ([ADR-0045 Amendment 1 § 4](../decisions/0045-entitlement-and-feature-flag-socket.md)). - Neither is the GDPR redaction handler, which lands in Phase 03 with the `users` table - it needs. - - *Marker clause, still vacuous — but for a narrower reason since Packet 7 step 9:* no - handler carries both `[AllowsUnresolvedTenantContext]` and a platform-scope entry. - `ProvisionTenantCommand` now carries the first, and nothing carries the second, so the - conjunction is empty because one half of it is — not because both are. + The marker clause, that no handler carries both `[AllowsUnresolvedTenantContext]` and + a platform-scope entry, is now structural as well: + `Only_The_Operator_Services_Hold_The_Platform_Scope` lists every file that may hold + the scope, and no request handler is among them. + +#### `The_Operator_Token_Profile_Is_Called_From_The_Authentication_Boundary_Only` + +- **Asserts:** the source files that name `PlatformOperatorTokenProfile` are exactly the + profile's own file, the API scheme's boundary + (`LearnStack.Api/Authentication/PlatformOperatorAuthentication.cs`) and the offline + validator + (`LearnStack.Infrastructure/PlatformOperator/PlatformOperatorTokenValidator.cs`); + the files that call its `TryRead` are exactly the scheme boundary and the offline + validator, the two callers of ADR-0101 § 7 through one validator; and the only file + that names `PlatformOperatorWitness.Minter` is the profile's own, where the one + private nested minter lives. A further caller joins by an edit here. +- **Why it matters:** the witness is evidence that a token passed the closed profile, + and `TryRead` is the only door to the minter that makes one. +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1 + review; widened to the second caller by P03-9 Step 3). +- **Phase:** P03-9. + +#### `The_Operator_Token_Validator_Has_Two_Callers_Of_The_Profile_And_One_Of_Its_Own` + +- **Asserts:** by IL, the callers of `PlatformOperatorTokenProfile.TryRead` in every + production assembly are exactly the API scheme's validated event + (`PlatformOperatorEvents.TokenValidated`) and + `PlatformOperatorTokenValidator.ValidateAsync`, and the callers of the offline + validator's constructor and `ValidateAsync` are exactly the rebind tool's + `RebindTool.RunAdmittedAsync`. `TryRead` and the validator accept the two executor + constants and refuse any other. +- **Why it matters:** the validator and the profile are public so that the API scheme + and the tool share one definition, and the witness they mint is evidence that a token + passed the closed profile. Before the move the compiler confined the profile to the + API project; now these rules do, for the production assemblies, and a test assembly + or reflection is outside them. Pinning the callers keeps a second public door from + becoming a second place a witness can be made + ([ADR-0101](../decisions/0101-platform-operator-authority.md) § 7). +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 7 and + [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 3. +- **Type:** xUnit + IL scan. **Kind:** structural. +- **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3 review). +- **Phase:** P03-9. + +#### `The_Identity_Rebind_Credential_Is_Named_Only_By_The_Rebind_Tool` + +- **Asserts:** in code under `backend/src`, comments stripped, none of the spellings + `ConnectionStrings__IdentityRebind`, `ConnectionStrings:IdentityRebind` or + `GetConnectionString("IdentityRebind")` appears outside + `LearnStack.Tools.IdentityAuthorityRebind/RebindToolInput.cs`, which must itself name + the first. A planted source file in a temporary directory is found by the same scan, + and none of the demo launcher, the migration script or the two compose files carries + the key. +- **Why it matters:** the sixth role is the only credential that can change the issuer, + and the claim that no runtime host can change it is exactly the claim that no runtime + configuration names it + ([ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 2). +- **Source:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 2. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 3). +- **Phase:** P03-9. + +#### `Only_The_Rebind_Run_And_The_Two_Freeze_Readers_Take_The_Rebind_Lock` + +- **Asserts:** by IL, the callers of `IdentityAdvisoryLockKey.ForAuthorityRebind` in + every production assembly are exactly + `NpgsqlUnitOfWork.AcquireGlobalIdentitySubjectLockAsync`, + `IdentityAuthorityQualification.QualifyCoreAsync`, `IdentityIssuerRebind.CommitAsync` + (the reconciliation of an unknown COMMIT, which waits behind the original + transaction) and `IdentityIssuerRebind.RunCoreAsync`. +- **Why it matters:** the exclusive form is the freeze and the shared form is what a + start or a creation waits behind; a further taker is a further party that can hold or + wait on it. +- **Source:** [ADR-0104](../decisions/0104-controlled-issuer-rebind.md) § 5. +- **Type:** xUnit + IL scan. **Kind:** structural. +- **Status:** **Implemented** (`IdentityAuditConventionTests`, P03-9 Step 3). +- **Phase:** P03-9. + +#### `Operator_Recovery_Audit_Identity_Is_Row_Bound` + +- **Asserts:** by IL, over every production assembly, that `OperatorRecoveryTransition` + is sealed with one private live-reader constructor, readonly state and getter-only + properties, in an assembly with no friend; that its nested `MintingSource` is + public, abstract and protected-constructed with exactly the two protected static + factories (`FromReplayUpdate`, `FromResetUpdate`); that the only subtypes are the + private sealed `RecoveryMint` classes nested in `DeliveryDispatchStore` and + `OutboxDispatchStore`; that the factories' only callers are those classes' two + wrappers, whose only callers are the stores' `ReplayCoreAsync` and `ResetCoreAsync`; + that the witness constructor's only callers are the factories; and that + `IAuditStore.WriteOperatorRecoveryAsync` is declared on the port and implemented by + `PostgresAuditStore` alone, with the two stores' `WriteRecoveryRowAsync` as its only + callers. Its companion + `Operator_recovery_census_detects_extra_derivers_constructors_and_callers` plants a + second subtype, an extra mint helper for each factory, a direct constructor call, an + extra writer caller and a helper on the sanctioned stores, and requires the same + detector to reject each. +- **Why it matters:** the witness is evidence that a row was reset under a fence in a + live transaction, and it binds the audit row to the admitted operation, the operator + and the fence. A second way to make one, or to write the row, is a second way to + forge that evidence. The terminal witness could not carry an operator, so this is a + sibling, not a third factory on it. +- **Source:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) § 5 + and its Amendment 1. +- **Type:** xUnit + IL scan. **Kind:** structural. +- **Status:** **Implemented** (`OutboxDispatchConventionTests`, P03-9 Step 4). +- **Phase:** P03-9. + +#### `Only_The_Recovery_Routes_And_Their_Owners_Name_The_Operator_Recovery_And_Inspection_Ports` + +- **Asserts:** the files, by their path under `backend/src`, that name `IOperatorRecovery` + are exactly the port, its one implementation, the outbox composition and the recovery + routes, and the files that name `IDeliveryInspection` are exactly the port, its + implementation, the persistence composition and the recovery routes. Adding a caller + is a deliberate edit here, with its denied proof. +- **Why it matters:** the two transitions are the dispatcher's second writer and the + inspection reads across tenants; a handler that held either port would reach a + reset or a cross-tenant read from a request path the operator gate does not guard. +- **Source:** [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) § 4. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 4). +- **Phase:** P03-9. + +#### `Only_The_Federation_Routes_And_Their_Owner_Name_The_Federation_Operator_Ports` + +- **Asserts:** the files, by their path under `backend/src`, that name + `FederationBrokerOperations` (the port's name contains it, so the owner's class is + found too) are exactly the port, its one owner, the persistence composition and the + federation routes, and the files that name `IFederationOperator` + are exactly the port, the owner, the adapter that implements it, its factory, the + federation composition and the Identity foundation registration that gives it a + fail-closed default. The tenant runner is in neither list. Adding a caller is a + deliberate edit here, with its denied proof. +- **Why it matters:** the removal and the disable change the realm's identity providers + for every tenant, and the tenant's provider port is held by the runner alone; a second + holder of the operator port, or a handler that reached the owner, would make a + cross-tenant provider change from a path the operator gate does not guard. +- **Source:** [ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 10. +- **Type:** xUnit + source scan, with a planted holder of each port and of the + concrete owner (`The_Federation_Port_Census_Finds_A_Planted_Holder_Of_Either_Port_Or_The_Concrete_Owner`). + **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 5). +- **Phase:** P03-9. + +#### `Only_The_Operator_Services_Hold_The_Platform_Scope` + +- **Asserts:** the files, by their path under `backend/src`, that name + `IPlatformAdminScope` are exactly the interface, the scope, the persistence + composition and the operator services that perform an admitted act (today the + killswitch toggle, the delivery inspection and the federation owner). Adding a + service is a deliberate edit here, with its denied proof. +- **Why it matters:** a request handler holding the scope would enter a cross-tenant + scope from a tenant request path. +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). +- **Phase:** P03-9. + +#### `Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act` + +- **Asserts:** the files, by their path under `backend/src`, that name + `PlatformOperatorActExecutor` in code, comments stripped, are exactly the executor, + the registration beside the source it enters and the onboarding routes. A second + caller is a second route to an act; adding one is a deliberate edit here, with its + denied proof. +- **Why it matters:** the executor installs a tenant context from an admission, so what + may call it is what may run an operator act. The admission is the barrier, and this + keeps the set of places that can spend one small and visible. +- **Source:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) § 1. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 2). +- **Phase:** P03-9. + +#### `Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject` + +- **Asserts:** the files, by their path under `backend/src`, that name + `fn_identity_operator_resolve_user` in code are exactly the adapter that calls it and + the migration helper that installs it, and the files that name + `IOperatorSubjectResolver` are exactly the port, the operator administrator core, the + registration and the adapter. A second caller is a second way to ask whether a + provider subject is an Active user; adding one is a deliberate edit here, with its + denied proof. +- **Why it matters:** the definer is executable by the application role, so what may ask + it is what the code, and not the database, confines + ([Database Standards § Operator subject resolution](05-database.md#operator-subject-resolution)). +- **Source:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) § 5. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`IdentityFoundationConventionTests`, P03-9 Step 2). +- **Phase:** P03-9. + +#### `Writes_To_The_Killswitch_Table_Are_Confined_To_The_Writer` + +- **Asserts:** the write verbs `INSERT INTO`, `UPDATE`, `DELETE FROM` and `TRUNCATE` + against `platform_killswitches` appear only in `KillswitchToggle`, matched in any case + with an optional schema, quotes and `ONLY`, and that file uses `INSERT` and `UPDATE` + and never the other two. The overlay's reads and a `SELECT … FOR UPDATE` are + unaffected. A companion case, + `The_Killswitch_Write_Pattern_Can_Fail_And_Catches_The_Ordinary_Spellings`, checks the + pattern against shapes it must and must not catch, so a pattern that matches nothing + cannot pass the rule. +- **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 13. +- **Type:** xUnit + source scan. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 1). +- **Phase:** P03-9. ## P02d-4 public-read obligations @@ -7581,15 +7788,20 @@ sign-in read). The `state <> 'Deleted' AND deleted_at IS NULL`; every production source, both Identity projects included, that reads `federation_connections` (`FROM` or `JOIN`, any case or whitespace, with or without the schema, quoted or through the mapped table-name - constant) is exactly `FederationConnectionStore`, `FederationHostAliasReader` or - `PublicSignInReader`; and each such statement, not merely its file, interpolates that - constant and spells no tombstone predicate of its own, so the three raw reads cannot - drift from each other or from the EF `Live` filter silently. + constant) is exactly `FederationConnectionStore`, `FederationHostAliasReader`, + `PublicSignInReader` or the operator's `FederationBrokerOperations`; each of the + three tenant statements, not merely its file, interpolates that constant and spells + no tombstone predicate of its own, so the three tenant reads cannot drift from each + other or from the EF `Live` filter silently. The operator's read is the one + exception: it must see tombstones, so it is pinned whole instead, by primary key + through the four columns the platform role may read + ([ADR-0099 Amendment 11](../decisions/0099-confined-tenant-federation.md) item 2). - **Source:** [ADR-0099 Amendment 1](../decisions/0099-confined-tenant-federation.md#amendment-1--step-1-storage-deviations-2026-11-13) (the tombstone) and the P03-8 Step 2 review round 1 (S-D). - **Type:** source scan with planted controls: an own predicate, a second statement without the constant, an unlisted reader by `JOIN`, without the schema, with other - spacing, quoted or through the table-name constant, and a dropped reader. + spacing, quoted or through the table-name constant, a dropped reader, and a + widened operator statement (a fifth column, another predicate, a second statement). **Kind:** structural. - **Status:** **Implemented** (`FederationApplicationConventionTests`). - **Test owner:** [FederationApplicationConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/FederationApplicationConventionTests.cs). @@ -7638,12 +7850,19 @@ sign-in read). The #### `Federation_Adapter_Admits_Only_The_Enumerated_Routes` -- **Asserts:** `KeycloakFederationRoutes` builds exactly four routes (token, the - identity-provider collection, one owned instance and its mappers), and no string - literal in the adapter namespace names another Admin, identity-provider, +- **Asserts:** `KeycloakFederationRoutes` builds exactly six routes (token, the + identity-provider collection, one bounded page of that collection, one owned instance, + one instance by a derived alias and its mappers; the page and the by-alias read serve + the operator of + [ADR-0099 Amendment 10](../decisions/0099-confined-tenant-federation.md)), and no + string literal in the adapter namespace names another Admin, identity-provider, authentication, user, client or role path. The unit test `KeycloakFederationProviderTests.Every_admitted_request_targets_the_enumerated_routes_only` - checks the same set behaviourally against a scripted provider. + checks the same set behaviourally against a scripted provider. The listing's one + exact query is pinned too: the route builder names the fragments `?first=`, `&max=` + and `&briefRepresentation=false`, in that order, and no other file of the adapter + builds a query string (`The_one_admitted_query_is_the_listing_page_and_no_provider_file_builds_another`, + with a planted fragment). - **Source:** [ADR-0099 § Ownership and the confined adapter](../decisions/0099-confined-tenant-federation.md#ownership-and-the-confined-adapter) ("the adapter admits only the enumerated calls and aliases"). - **Type:** reflection plus source scan, with planted routes. **Kind:** structural. diff --git a/infra/compose/README.md b/infra/compose/README.md index c2549cf0f..3863d8b80 100644 --- a/infra/compose/README.md +++ b/infra/compose/README.md @@ -56,7 +56,12 @@ Two realms imported on first boot from `infra/keycloak/realms/`: - `learnstack` (tenant users) — confidential API and code/S256 web clients, with four declared tenant personas. The [realm guide](../keycloak/README.md) owns the exact identities, private secret source and callbacks. -- `learnstack-hub` (operators) — client `learnstack-hub-web` (public PKCE); demo user `demo-operator@learnstack.test` (`demo-dev-secret`). `CONFIGURE_TOTP` required-action present so the MFA flow surfaces in dev. +- `learnstack-hub` (operators) — clients `learnstack-hub-web` (the portal, public PKCE) + and `learnstack-operator` (LearnStack's platform surface, public PKCE with MFA + step-up); demo user `demo-operator@learnstack.test` (`demo-dev-secret`). + `CONFIGURE_TOTP` is a required action, so the first login sets up the authenticator + the step-up needs. A Keycloak volume from before the operator client keeps its old + realm; recreate it to import the new one. See [../keycloak/README.md](../keycloak/README.md) for the realm-isolation invariant, non-destructive reconciliation and the Phase 02b/03 wiring notes. @@ -67,7 +72,7 @@ fresh `postgres-data` volume**: | Script | Creates | |---|---| | `postgres-init/01-create-keycloak-db.sql` | the `keycloak` database Keycloak stores its realm state in | -| `postgres-init/02-create-roles.sql` | the four baseline database roles plus ADR-0097’s confined `learnstack_identity_ingress` login, reading passwords from `LEARNSTACK_*_PW` in the environment | +| `postgres-init/02-create-roles.sql` | the four baseline database roles plus ADR-0097’s confined `learnstack_identity_ingress` and ADR-0104’s confined `learnstack_identity_rebind` logins, reading passwords from `LEARNSTACK_*_PW` in the environment | **A volume created before Phase 02a Packet 6 has no roles**, and nothing will tell you: init scripts do not re-run, `make dev` reports healthy, and the first @@ -80,12 +85,14 @@ docker compose --env-file .env -f infra/compose/dev.yml exec -T postgres sh -c ``` The script converges passwords, attributes and memberships on every run; it is -not a no-op. P03-6's forward Identity migration requires the fifth role to exist. -For a warm volume, set `LEARNSTACK_IDENTITY_INGRESS_PW` in the selected private -environment, recreate the postgres container with the existing volume to pass -the new environment value, then apply the roles script above before `make migrate`. -Do not delete a volume to add the role. No runtime process receives the migration -password. The [database contract](../../docs/standards/05-database.md#provider-event-intake-storage) +not a no-op. P03-6's forward Identity migration requires the fifth role to exist, +and the P03-9 Step 3 Identity migration requires the sixth. For a warm volume, set +`LEARNSTACK_IDENTITY_INGRESS_PW` and `LEARNSTACK_IDENTITY_REBIND_PW` in the selected +private environment, recreate the postgres container with the existing volume to pass +the new environment values, then apply the roles script above before `make migrate`. +Do not delete a volume to add a role. The sixth role's connection string is never a +compose or host setting: it exists only in the environment of the offline rebind tool. +No runtime process receives the migration password. The [database contract](../../docs/standards/05-database.md#provider-event-intake-storage) owns the private machine source and its bounds; installing storage alone does not activate provider polling. diff --git a/infra/compose/dev.yml b/infra/compose/dev.yml index 2121dda5a..a6be328d6 100644 --- a/infra/compose/dev.yml +++ b/infra/compose/dev.yml @@ -61,14 +61,15 @@ services: POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-learnstack} POSTGRES_DB: ${POSTGRES_DB:-learnstack} # Read by postgres-init/02-create-roles.sql through psql's \getenv on the - # first boot of a fresh volume. The four-role model of ADR-0003 - # Amendment 3; an unset one aborts initdb rather than creating a + # first boot of a fresh volume. The role model of ADR-0003 + # Amendment 3 and 14; an unset one aborts initdb rather than creating a # passwordless role. LEARNSTACK_MIGRATION_PW: ${LEARNSTACK_MIGRATION_PW:-learnstack-migration-dev} LEARNSTACK_APP_PW: ${LEARNSTACK_APP_PW:-learnstack-app-dev} LEARNSTACK_PLATFORM_PW: ${LEARNSTACK_PLATFORM_PW:-learnstack-platform-dev} LEARNSTACK_OUTBOX_PW: ${LEARNSTACK_OUTBOX_PW:-learnstack-outbox-dev} LEARNSTACK_IDENTITY_INGRESS_PW: ${LEARNSTACK_IDENTITY_INGRESS_PW:-learnstack-identity-ingress-dev} + LEARNSTACK_IDENTITY_REBIND_PW: ${LEARNSTACK_IDENTITY_REBIND_PW:-learnstack-identity-rebind-dev} # Dev-only. Production secrets come from Vault via ISecretProvider. ports: - "127.0.0.1:5432:5432" diff --git a/infra/compose/postgres-init/02-create-roles.sql b/infra/compose/postgres-init/02-create-roles.sql index 5e51ebca8..07960d162 100644 --- a/infra/compose/postgres-init/02-create-roles.sql +++ b/infra/compose/postgres-init/02-create-roles.sql @@ -1,7 +1,7 @@ -- Postgres init script — runs ONCE on a fresh `postgres-data` volume, after -- 01-create-keycloak-db.sql. Provisions the four-role baseline plus the confined --- fifth provider-intake role of ADR-0097. The baseline is --- ADR-0003 Amendment 3, whose canonical definition is +-- fifth provider-intake role of ADR-0097 and the confined sixth issuer-rebind role +-- of ADR-0104. The baseline is ADR-0003 Amendment 3, whose canonical definition is -- docs/standards/05-database.md § Database roles. -- -- WHY FOUR ROLES AND NOT ONE. The single `POSTGRES_USER` this stack used to run @@ -22,6 +22,7 @@ \getenv platform_pw LEARNSTACK_PLATFORM_PW \getenv outbox_pw LEARNSTACK_OUTBOX_PW \getenv ingress_pw LEARNSTACK_IDENTITY_INGRESS_PW +\getenv rebind_pw LEARNSTACK_IDENTITY_REBIND_PW \getenv db POSTGRES_DB -- Idempotent in the shape 01-create-keycloak-db.sql already uses: PostgreSQL has @@ -56,6 +57,13 @@ SELECT format('CREATE ROLE learnstack_identity_ingress LOGIN NOINHERIT PASSWORD WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'learnstack_identity_ingress') \gexec +-- The sixth role belongs to the offline issuer-rebind tool alone (ADR-0104): no API, +-- worker or seeder host is ever given its credential. NOINHERIT and NOBYPASSRLS like +-- the fifth, so its few grants are bounded by policies and nothing is inherited. +SELECT format('CREATE ROLE learnstack_identity_rebind LOGIN NOINHERIT PASSWORD %L NOBYPASSRLS', :'rebind_pw') +WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'learnstack_identity_rebind') +\gexec + -- Then CONVERGE, unconditionally. The creates above fire only when the role is -- absent, so on a cluster that already has them — the documented recovery path -- is "apply this file by hand, it is idempotent" — a changed password in `.env` @@ -68,11 +76,11 @@ WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'learnstack_identity_ingr -- way to put it back. (The runtime refuses to start against such a role anyway — -- the composition root asks the server `rolbypassrls OR rolsuper` on every -- physical connection — but this is what fixes it rather than reporting it.) --- NOSUPERUSER on all five, and it is not decoration: a SUPERUSER bypasses row +-- NOSUPERUSER on all six, and it is not decoration: a SUPERUSER bypasses row -- security whatever `rolbypassrls` says — measured — so a superuser -- learnstack_app makes every policy in the database inert while the attribute -- this script converges still reads `f`. NOCREATEDB / NOCREATEROLE / --- NOREPLICATION for the same reason in miniature: none of the five needs any of +-- NOREPLICATION for the same reason in miniature: none of the six needs any of -- them, learnstack_migration owns tables rather than databases or roles, and an -- attribute nothing needs is one an escalation can use. ALTER ROLE learnstack_migration WITH LOGIN PASSWORD :'migration_pw' @@ -87,22 +95,26 @@ ALTER ROLE learnstack_outbox_admin WITH LOGIN PASSWORD :'outbox_pw' ALTER ROLE learnstack_identity_ingress WITH LOGIN PASSWORD :'ingress_pw' NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; --- And revoke every role MEMBERSHIP the five hold. Attributes were only half of +ALTER ROLE learnstack_identity_rebind WITH LOGIN PASSWORD :'rebind_pw' + NOINHERIT NOBYPASSRLS NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; + +-- And revoke every role MEMBERSHIP the six hold. Attributes were only half of -- it: `GRANT learnstack_platform TO learnstack_app` leaves learnstack_app's own -- rolbypassrls false and still lets it `SET ROLE learnstack_platform` — measured, -- directly and through a bridge role holding the membership on its behalf. None --- of the four needs to be a member of anything; every privilege they hold is +-- of the six needs to be a member of anything; every privilege they hold is -- granted to them directly, in the migration that creates each table. -- --- Generated per membership rather than written as four REVOKEs, because the +-- Generated per membership rather than written as a fixed list of REVOKEs, because the -- grantor is not knowable in advance and a bridge role has no fixed name. No -- rows means no statements, so a clean cluster is a no-op. SELECT format('REVOKE %I FROM %I', granted.rolname, member.rolname) FROM pg_auth_members am JOIN pg_roles granted ON granted.oid = am.roleid JOIN pg_roles member ON member.oid = am.member -WHERE granted.rolname='learnstack_identity_ingress' OR member.rolname IN ('learnstack_migration', 'learnstack_app', - 'learnstack_platform', 'learnstack_outbox_admin', 'learnstack_identity_ingress') +WHERE granted.rolname IN ('learnstack_identity_ingress', 'learnstack_identity_rebind') + OR member.rolname IN ('learnstack_migration', 'learnstack_app', 'learnstack_platform', + 'learnstack_outbox_admin', 'learnstack_identity_ingress', 'learnstack_identity_rebind') \gexec -- No `GRANT learnstack_platform TO learnstack_app`, ever. Membership would make @@ -114,10 +126,10 @@ WHERE granted.rolname='learnstack_identity_ingress' OR member.rolname IN ('learn -- reaches learnstack_platform). -- PUBLIC holds CONNECT and TEMPORARY on every database by default, so the grant --- below adds nothing until that default is removed. Revoke first, and the four +-- below adds nothing until that default is removed. Revoke first, and the -- explicit grants become the whole of the reach INTO THIS DATABASE — measured: -- afterwards `pg_database.datacl` carries no `=Tc` entry for PUBLIC, only the --- four `c` grants and the owner's. +-- `c` grants and the owner's. -- -- Scope is exactly one database, and that is worth saying because it is easy to -- read as more. Measured: `learnstack_app` can still connect to `keycloak` and @@ -134,7 +146,8 @@ WHERE granted.rolname='learnstack_identity_ingress' OR member.rolname IN ('learn -- exist. REVOKE CONNECT, TEMPORARY ON DATABASE :"db" FROM PUBLIC; GRANT CONNECT ON DATABASE :"db" - TO learnstack_migration, learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress; + TO learnstack_migration, learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress, + learnstack_identity_rebind; -- Since PostgreSQL 15 the public schema no longer grants CREATE to PUBLIC, and -- the schema is owned by pg_database_owner. Without the CREATE grant below the @@ -145,7 +158,8 @@ GRANT CONNECT ON DATABASE :"db" REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO learnstack_migration; GRANT USAGE ON SCHEMA public - TO learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress; + TO learnstack_app, learnstack_platform, learnstack_outbox_admin, learnstack_identity_ingress, + learnstack_identity_rebind; -- No per-table grants here. This script runs at initdb time, before any table -- exists, and under the entrypoint's ON_ERROR_STOP a single diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index e07535cf3..3d76c3011 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -186,7 +186,48 @@ manual ledger deletion, history reset, reduced retention or tenant-copy purge. | Realm | Population | Clients | |-------|------------|---------| | `learnstack` | Tenant users; four declared development accounts | `learnstack-web`: confidential code/S256 BFF; `learnstack-api`: resource and legacy service account; `learnstack-event-reader`: confined history reader; `learnstack-federation-admin`: confined federation adapter ([below](#federation-administration-client)); `account` and `account-console`: retired, disabled | -| `learnstack-hub` | Platform operators | `learnstack-hub-web`: public PKCE; unchanged by P02b-6 | +| `learnstack-hub` | Platform operators | `learnstack-hub-web`: public PKCE, the portal's; `learnstack-operator`: public PKCE for LearnStack's platform surface, audience `learnstack-platform`, 15-minute access tokens, MFA step-up | + +The `learnstack-hub` realm's browser flow is `browser-loa`: password at level 1, a +one-time password at level 2, so a login through `learnstack-operator` (which asks for +`acr` `mfa`) always ends in an `acr` that LearnStack accepts only for an operator who +passed the second factor +([ADR-0101](../../docs/decisions/0101-platform-operator-authority.md) § 3). The demo +operator has a pinned subject and sets up an authenticator at its first login; +production MFA enforcement for the realm stays +[Phase 11](../../docs/roadmap/phase-11-production-hardening.md). A realm import into +production never includes the demo user. + +Three properties of the shared realm file that an operator of it should know: + +- **`browser-loa` is realm-wide.** It is the realm's browser flow, so the Hub portal's + login (`learnstack-hub-web`) goes through it too; the portal asks for no `acr`, so it + is satisfied at level 1 and sees no change. The file is shared with the Hub + repository, so a change to the flow is made in both. +- **Credential changes need the existing second factor.** An account-console login needs + only the password, because the console asks for no `acr`. For an operator who already + has an authenticator, pinned Keycloak (26.7.5) then refuses to remove it, and asks for + the existing code before it offers to set up another; two realm tests pin both. The + window that remains is the first login, before any authenticator exists, which is why + a grant follows enrolment (see the + [operator access runbook](../../docs/runbooks/operator-access.md#giving-and-withdrawing-a-grant)). +- **Password reset is off.** `resetPasswordAllowed` is `false`: the reset-credentials + flow lets a user set a new password from an email link, which would be a second way to + a password that does not pass through the second factor. Operator credentials are + recovered by the realm administrator. The LearnStack scheme does not rely on this + alone: it accepts a token only when its `acr` is one the deployment lists, whatever + flow produced it. +- **An existing Keycloak volume keeps its old realm.** The import runs on an empty realm + only. A developer with a volume from before this change removes the volume (or the + realm) and starts again to get the flow, the client and the pinned demo subject. + +`learnstack-hub-web` keeps `fullScopeAllowed: true` as a development posture, because +the Hub operator portal maps the `hub-*` realm roles from its token. Narrowing it needs +`scopeMappings` for those roles and is coordinated with the Hub's operator-portal packet +(P02c-4), since the realm export is shared with the Hub repository. The +`learnstack-operator` client sets `fullScopeAllowed` to `false` and carries no realm +roles. The procedure for getting a token is the +[operator access runbook](../../docs/runbooks/operator-access.md). [SeedData.IdentityUsers](../../backend/src/LearnStack.Tools.Seeder/SeedData.cs) owns actor UUIDs and the account/tenant association. The read-only Seeder @@ -204,8 +245,10 @@ against it, including the host's default organization where applicable. [earlier adjustment](../../docs/roadmap/phase-02b-delivery-log.md#account-console-self-service-capability--proposal-2026-10-21) granted is retired by [ADR-0099](../../docs/decisions/0099-confined-tenant-federation.md): see [Account self-service retirement](#account-self-service-retirement). -- The operator account remains `demo-operator@learnstack.test`; its separate - realm is untouched. Neither realm's token is accepted by the other surface. +- The operator account remains `demo-operator@learnstack.test` in its separate realm, + which now also carries the `learnstack-operator` client and the `browser-loa` flow + ([above](#realms-and-accounts)). Neither realm's token is accepted by the other + surface. ## Local access and private sources diff --git a/infra/keycloak/realms/learnstack-hub.json b/infra/keycloak/realms/learnstack-hub.json index 6a2d4d218..029b3033f 100644 --- a/infra/keycloak/realms/learnstack-hub.json +++ b/infra/keycloak/realms/learnstack-hub.json @@ -8,7 +8,7 @@ "verifyEmail": true, "loginWithEmailAllowed": true, "duplicateEmailsAllowed": false, - "resetPasswordAllowed": true, + "resetPasswordAllowed": false, "editUsernameAllowed": false, "bruteForceProtected": true, "permanentLockout": false, @@ -23,6 +23,116 @@ "internationalizationEnabled": true, "supportedLocales": ["en"], "defaultLocale": "en", + "browserFlow": "browser-loa", + "attributes": { + "acr.loa.map": "{\"mfa\":\"2\"}" + }, + "authenticationFlows": [ + { + "alias": "browser-loa", + "description": "Operator browser flow: password at level 1, OTP at level 2 (ADR-0101 step-up).", + "providerId": "basic-flow", + "topLevel": true, + "builtIn": false, + "authenticationExecutions": [ + { + "authenticator": "auth-cookie", + "authenticatorFlow": false, + "requirement": "ALTERNATIVE", + "priority": 10, + "userSetupAllowed": false + }, + { + "flowAlias": "browser-loa forms", + "authenticatorFlow": true, + "requirement": "ALTERNATIVE", + "priority": 20, + "userSetupAllowed": false + } + ] + }, + { + "alias": "browser-loa forms", + "description": "The two authentication levels.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": false, + "authenticationExecutions": [ + { + "flowAlias": "browser-loa level-1", + "authenticatorFlow": true, + "requirement": "CONDITIONAL", + "priority": 10, + "userSetupAllowed": false + }, + { + "flowAlias": "browser-loa level-2", + "authenticatorFlow": true, + "requirement": "CONDITIONAL", + "priority": 20, + "userSetupAllowed": false + } + ] + }, + { + "alias": "browser-loa level-1", + "description": "Level 1: username and password.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": false, + "authenticationExecutions": [ + { + "authenticator": "conditional-level-of-authentication", + "authenticatorConfig": "loa-1", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false + }, + { + "authenticator": "auth-username-password-form", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false + } + ] + }, + { + "alias": "browser-loa level-2", + "description": "Level 2: one-time password, asked on every authentication.", + "providerId": "basic-flow", + "topLevel": false, + "builtIn": false, + "authenticationExecutions": [ + { + "authenticator": "conditional-level-of-authentication", + "authenticatorConfig": "loa-2", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 10, + "userSetupAllowed": false + }, + { + "authenticator": "auth-otp-form", + "authenticatorFlow": false, + "requirement": "REQUIRED", + "priority": 20, + "userSetupAllowed": false + } + ] + } + ], + "authenticatorConfig": [ + { + "alias": "loa-1", + "config": { "loa-condition-level": "1", "loa-max-age": "36000" } + }, + { + "alias": "loa-2", + "config": { "loa-condition-level": "2", "loa-max-age": "0" } + } + ], "requiredActions": [ { "alias": "CONFIGURE_TOTP", @@ -77,10 +187,49 @@ "post.logout.redirect.uris": "http://localhost:3100/*" }, "fullScopeAllowed": true + }, + { + "clientId": "learnstack-operator", + "name": "LearnStack Platform Operator (public PKCE)", + "description": "Operator access to LearnStack's /api/platform surface (ADR-0101). Public client, PKCE-enforced, MFA step-up, access tokens of at most 15 minutes, audience learnstack-platform, no realm roles in the token.", + "enabled": true, + "publicClient": true, + "standardFlowEnabled": true, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": false, + "redirectUris": [ + "http://127.0.0.1:8765/*", + "http://localhost:8765/*" + ], + "webOrigins": [], + "protocol": "openid-connect", + "attributes": { + "pkce.code.challenge.method": "S256", + "access.token.lifespan": "900", + "acr.loa.map": "{\"mfa\":\"2\"}", + "default.acr.values": "mfa" + }, + "protocolMappers": [ + { + "name": "learnstack-platform-audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-audience-mapper", + "consentRequired": false, + "config": { + "included.custom.audience": "learnstack-platform", + "id.token.claim": "false", + "access.token.claim": "true", + "introspection.token.claim": "true" + } + } + ], + "fullScopeAllowed": false } ], "users": [ { + "id": "5a3c8f0e-2b1d-4c6a-9e47-0d1f6a2b7c93", "username": "demo-operator@learnstack.test", "email": "demo-operator@learnstack.test", "emailVerified": true, diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index a24edd648..949fd996e 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -83,6 +83,7 @@ "LearnStack.Tests.Integration.Database.DatabaseRoleTests", "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests", "LearnStack.Tests.Integration.Database.DeliveryExecutionTests", + "LearnStack.Tests.Integration.Database.DeliveryInspectionTests", "LearnStack.Tests.Integration.Database.DeliveryProcessorTests", "LearnStack.Tests.Integration.Database.DomainEventProductionTests", "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests", @@ -95,6 +96,7 @@ "LearnStack.Tests.Integration.Database.EntitlementExpiryReversalTests", "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests", "LearnStack.Tests.Integration.Database.FeatureFlagsTests", + "LearnStack.Tests.Integration.Database.FederationBrokerOperationsTests", "LearnStack.Tests.Integration.Database.FederationConnectionStorageTests", "LearnStack.Tests.Integration.Database.FederationHttpTests", "LearnStack.Tests.Integration.Database.FixedSeedPrerequisiteReadTests", @@ -107,6 +109,10 @@ "LearnStack.Tests.Integration.Database.HangfireStorageTests", "LearnStack.Tests.Integration.Database.HostResolutionTests", "LearnStack.Tests.Integration.Database.IdentityAdministrationReadTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindLockTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindStorageTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindTests", + "LearnStack.Tests.Integration.Database.IdentityAuthorityRebindToolTests", "LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpTests", "LearnStack.Tests.Integration.Database.IdentityAuthorizationReaderTests", "LearnStack.Tests.Integration.Database.IdentityCommandQualificationTests", @@ -115,6 +121,7 @@ "LearnStack.Tests.Integration.Database.IdentityMutationLockTests", "LearnStack.Tests.Integration.Database.IdentityOwnNavigationTests", "LearnStack.Tests.Integration.Database.IdentityReadDiagnosticSinkTests", + "LearnStack.Tests.Integration.Database.IdentityRebindAuditStoreTests", "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests", "LearnStack.Tests.Integration.Database.IdentitySeederTests", "LearnStack.Tests.Integration.Database.IdentitySelfDiscoveryOwnerTests", @@ -142,6 +149,7 @@ "LearnStack.Tests.Integration.Database.ModuleReceiptDisclosureTests", "LearnStack.Tests.Integration.Database.NativeScopeAdmissionDurabilityHttpTests", "LearnStack.Tests.Integration.Database.OperationReadScopeTests", + "LearnStack.Tests.Integration.Database.OperatorSubjectResolverTests", "LearnStack.Tests.Integration.Database.OrgScopeMigrationTests", "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests", "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests", @@ -152,6 +160,7 @@ "LearnStack.Tests.Integration.Database.OutboxProducerTests", "LearnStack.Tests.Integration.Database.P02d2FoundationTests", "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests", + "LearnStack.Tests.Integration.Database.PlatformOperatorOnboardingTests", "LearnStack.Tests.Integration.Database.PlatformSchemaTests", "LearnStack.Tests.Integration.Database.PoolHangfireStorageParityTests", "LearnStack.Tests.Integration.Database.PostgresIdempotencyStoreTests",