diff --git a/.claude/skills/add-architecture-test/SKILL.md b/.claude/skills/add-architecture-test/SKILL.md index 5e637542f..01eae86c8 100644 --- a/.claude/skills/add-architecture-test/SKILL.md +++ b/.claude/skills/add-architecture-test/SKILL.md @@ -58,7 +58,7 @@ them. |-----------|----------| | **NetArchTest** | Project-graph reference bans, naming conventions on types / namespaces. | | **Mono.Cecil (IL scan)** | What a method body does — a constructor called, a member read — which NetArchTest's type-level rules cannot express. It ships with NetArchTest; there is no ArchUnitNET in this repository. | -| **Roslyn analyzer** | A syntactic pattern the build itself should fail on — `throw new DomainException(...)` outside an invariant guard is `LS0001`. | +| **Roslyn analyzer** | A compiler diagnostic over source; configured severity controls build failure. `LS0001` flags direct `throw new DomainException(...)`, including invariant guards whose justified local suppressions are checked separately. `LS0002` has its bounded sensitive-name scope in the catalogue. | | **Migration scan** | SQL patterns in `.cs` migration files (RLS-enable, policy presence, partition declaration). | | **Reflection over conventions** | Marker-attribute presence + matching property / migration shape. | | **String / regex scan** | When all else fails — explicit "no file under `Verticals/`", "no `english.*` permission key". | diff --git a/.claude/skills/add-backend-module/SKILL.md b/.claude/skills/add-backend-module/SKILL.md index ed8e6cea2..0934e7542 100644 --- a/.claude/skills/add-backend-module/SKILL.md +++ b/.claude/skills/add-backend-module/SKILL.md @@ -72,6 +72,11 @@ backend/src/Modules// LearnStack.Modules..Infrastructure.csproj ``` +All four projects inherit the analyzer from `backend/src/Directory.Build.props`; +do not duplicate its project reference or add `LS0001`/`LS0002` to `NoWarn`. +[The catalogue](../../../docs/standards/21-architecture-tests-catalogue.md#learnstackexception-sensitiveexceptionmessage-roslyn-analyzer) +owns their distinct scopes and escalation contract. + Project references follow the strict graph in [01-architecture-standards.md § Dependency Direction](../../../docs/standards/01-architecture-standards.md): @@ -109,10 +114,11 @@ Forbidden references (architecture test will catch them): > entry describes an intended shape; do not write code against it. Two real seams > replace it: > -> - **Handlers and validators** are registered today by passing the module's assembly -> marker to `AddLearnStackMediatRPipeline(params Assembly[])` from the composition -> root — one call, all modules, and it registers the validators from the same -> assemblies. +> - **Handlers and validators** use the shared +> `AddLearnStackMediatRPipeline(params Assembly[])` helper. The API's one +> `AddLearnStackCrossCuttingFoundation` call invokes it with all module assemblies; +> the Seeder calls the helper in its own composition. Both register validators +> and the scoped execution coordinators with the same behavior chain. > - **The audit catalogue** is a module-owned `IAuditCatalogSource` discovered from DI, > shipped in Phase 02a Packet 9 per > [ADR-0044 § 6](../../../docs/decisions/0044-audit-write-path.md). Register it at both @@ -129,8 +135,9 @@ Forbidden references (architecture test will catch them): Composition root (`LearnStack.Api/Program.cs` and its `Composition/` extensions): ```csharp -// Handlers + validators for every module, one call. -services.AddLearnStackMediatRPipeline( +// Extend the existing API foundation call; retain every other module marker. +builder.AddLearnStackCrossCuttingFoundation( + deploymentMode, typeof(LearnStack.Modules..Application.AssemblyMarker).Assembly, /* … the other module markers … */); @@ -139,6 +146,9 @@ services.AddLearnStackMediatRPipeline( // services.AddScopedProvider, Provider>(); ``` +Do not add a second pipeline registration in the API. Extend the Seeder's +existing `AddLearnStackMediatRPipeline` call separately with the same assembly. + And, from Packet 9, the module's audit catalogue — one class in the module's `Application` project, registered like any other DI service (see [add-audit-coverage](../add-audit-coverage/SKILL.md)): diff --git a/.claude/skills/wire-cross-cutting-foundation/SKILL.md b/.claude/skills/wire-cross-cutting-foundation/SKILL.md index 46c546ea6..b233560b8 100644 --- a/.claude/skills/wire-cross-cutting-foundation/SKILL.md +++ b/.claude/skills/wire-cross-cutting-foundation/SKILL.md @@ -5,7 +5,7 @@ description: > (`LearnStack.Api`, worker, background-service host) — `IExceptionHandler`, 8-step MediatR pipeline, `Result.ToActionResult()`, Serilog + OTel, `TenantContextSpanProcessor`, `IErrorTrackingProvider`, - `IProviderResilience`, Roslyn analyzer for `DomainException`. USE + `IProviderResilience`, and the scoped exception analyzers. USE FOR: standing up the foundation in Phase 02a (one-time wiring per host process), or restoring it after a composition-root refactor. DO NOT USE FOR: adding a new provider adapter ([add-provider-adapter](../add-provider-adapter/SKILL.md)), @@ -21,7 +21,7 @@ description: > Bring up the LearnStack error-handling + logging + observability foundation in a backend host. The contract is bound by [ADR-0032](../../../docs/decisions/0032-exception-handling-logging-and-observability.md). -This skill walks the canonical wiring step by step so the eight binding +This skill walks the canonical wiring step by step so the binding sub-decisions land in the right composition-root order and the architecture tests pass. @@ -69,8 +69,11 @@ and [33-cross-cutting-concerns.md](../../../docs/architecture/33-cross-cutting-concerns.md). You should be able to recite, before you write a line of code: -- The eight pipeline behaviors and their order +- The eight pipeline stages (seven behaviors plus the handler) and their order (`Validation → Logging → AuditLog → TenantContext → Authorization → Transaction → OutboxFlush → Handler`). +- Step 7's historical name denotes the producer enrollment/invariant guard, + not a buffered flush. Enqueue inserts immediately in the ambient transaction; + its owner drains domain events before MUST audit/commit under ADR-0057. - The Sentry-vs-OTel boundary (`ShouldCapture(ex)` table). - The Serilog + OTLP wiring rule (no `AddOpenTelemetry().WithLogging()` alongside). - The composition-root branching for `IErrorTrackingProvider`. @@ -208,24 +211,18 @@ and dispatches to `IErrorTrackingProvider.CaptureAsync` only when `ShouldCapture(ex)` returns true (see [09-error-handling.md § Sentry vs OpenTelemetry — Error Capture Boundary](../../../docs/standards/09-error-handling.md)). -### Step 8: Register the MediatR pipeline (8 behaviors in order) +### Step 8: Use the shared MediatR registration (7 behaviors plus handler) -```csharp -services.AddMediatR(cfg => -{ - cfg.RegisterServicesFromAssemblyContaining(); - - // Order matters — outermost first, innermost last. - // Architecture test MediatR_Pipeline_Order_Matches_Canonical_Sequence enforces this. - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(AuditLogBehavior<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(TenantContextBehavior<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehavior<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(TransactionBehavior<,>)); - cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(OutboxFlushBehavior<,>)); -}); -``` +The foundation call in Step 12 invokes +`services.AddLearnStackMediatRPipeline(handlerAssemblies)` once. That shared +helper registers the audit, producer and transaction coordinators, validators +and `MediatRPipelineRegistration.CanonicalBehaviorOrder`. Do not reconstruct +the behavior chain with a separate `AddMediatR` call or call the helper again +after the foundation. A separate registration path can bypass shared services; +repeating the shared helper is idempotent but needlessly obscures ownership. +`Registering_The_Pipeline_Twice_Registers_It_Once` protects that idempotency. +`MediatR_Pipeline_Order_Matches_Canonical_Sequence` verifies +the actual order, including `OutboxFlushBehavior` at position seven. Do **not** add an `ExceptionHandlingBehavior`. The `AuditLogBehavior` catches handler exceptions, writes the failure audit, and rethrows via @@ -298,24 +295,37 @@ public async Task Create(CreateCourseCommand cmd, CancellationTok No action filter, no `ResultUnwrapBehavior`. Explicit beats magic. -### Step 11: Add the Roslyn analyzer +### Step 11: Preserve automatic analyzer wiring + +`backend/src/Directory.Build.props` automatically references the in-tree +`backend/analyzers/LearnStack.Analyzers` project with +`OutputItemType="Analyzer"` and `ReferenceOutputAssembly="false"`. It is not +a NuGet package. New production C# projects inherit this wiring. Do not add +project-level +analyzer references or suppress these diagnostics with `NoWarn`. + +- `LS0001` (`LearnStackException-DomainExceptionThrow`) retains its + Domain/Application scope through the compiler-visible scope property. +- `LS0002` (`LearnStackException-SensitiveExceptionMessage`) covers bounded + sensitive-name exception expressions in every production C# project. It is + not data-flow analysis and covers no JavaScript/TypeScript. +- Both remain Warning, including CI, in `WarningsNotAsErrors` rather than + `NoWarn`. Phase 03 exit promotes them to Error and removes that exemption. -The `LearnStackException-DomainExceptionThrow` analyzer lives in -`backend/analyzers/` and ships as a NuGet package referenced by -`Domain` + `Application` projects via -``. Severity: -Warning in Phase 02a, escalates to Error after Phase 03 exit. +[ADR-0032 Amendment 6](../../../docs/decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25) +and the [catalogue](../../../docs/standards/21-architecture-tests-catalogue.md#learnstackexception-sensitiveexceptionmessage-roslyn-analyzer) +own the exact scope, expression limits and proof obligations. -### Step 12: Register module services last +### Step 12: Pass all module assemblies to the host foundation Module assemblies reach the foundation as arguments, not as separate registration calls. `AddLearnStackCrossCuttingFoundation` discovers their integration-event -handlers and hands the same assemblies to `AddLearnStackMediatRPipeline` as its -**last** statement, so behaviors and instrumentation are already wired before any -module handler is registered: +handlers and then hands the same assemblies to `AddLearnStackMediatRPipeline` +for the shared execution services, behavior chain and validator discovery. Keep +the complete assembly set in this one host call: ```csharp -// The shipped entry point, and the only one: AddLearnStackCrossCuttingFoundation +// The shipped host entry point, called once: AddLearnStackCrossCuttingFoundation // on the WebApplicationBuilder, taking the deployment mode and the assemblies whose // integration-event handlers should be discovered. builder.AddLearnStackCrossCuttingFoundation( diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index bb0dab56a..f36cfbb12 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -167,8 +167,10 @@ it. `make test` starts Testcontainers since Phase 02a Packet 6, so it needs a Docker socket and takes noticeably longer than it did. The Docker-bound cases are split out by `[Trait("Requires","Docker")]`; to skip them, run -`dotnet test backend/LearnStack.slnx --filter "Requires!=Docker"`, which is -exactly what CI's `backend` job runs. +`dotnet test backend/LearnStack.slnx --filter "Requires!=Docker"` locally. +CI partitions that population into base and architecture producers, with exact +coverage checked by the required backend aggregate under +[ADR-0063](../docs/decisions/0063-complete-bounded-ci-test-shards.md). The pre-commit hook (activated by `make install`) runs, on staged files only: `dotnet format` on `*.cs`; prettier on JS / TS / JSON / Markdown **under diff --git a/CLAUDE.md b/CLAUDE.md index ced986ca4..d0c790923 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -367,6 +367,10 @@ rules: The Roslyn analyzer `LearnStackException-DomainExceptionThrow` flags violations; full catalogue entry in [docs/standards/21-architecture-tests-catalogue.md](docs/standards/21-architecture-tests-catalogue.md). +- Silence the production `LS0002` sensitive-exception-message guard project-wide. + Its automatic wiring and bounded scope are in the + [same catalogue](docs/standards/21-architecture-tests-catalogue.md#learnstackexception-sensitiveexceptionmessage-roslyn-analyzer). + A clean report is not data-flow secrecy or a redaction guarantee. - Throw `FluentValidation.ValidationException` from `ValidationBehavior` — the behavior returns `Result.Fail(validation_failed)` and never throws. - Reference `Sentry.SentrySdk` directly from any module assembly — error diff --git a/README.md b/README.md index 8c54570f6..d4e229e44 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ skeleton. Current packet state lives in the | **Customization** | Content types, level taxonomies, exact-definition and generation-cached batched display readers, text-card metadata validation, 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) | -| **API foundation** | Error contracts, validation, tenancy, concurrency, observability, durable events/subscriber delivery, background jobs, the closed tenant bearer/AccountSite boundary and development realm reconciliation | Phase-exit enforcement in [Phase 02b](docs/roadmap/phase-02b-events-auth.md) | +| **API foundation** | Error contracts, validation, tenancy, concurrency, observability, durable events/subscriber delivery, background jobs, the closed tenant bearer/AccountSite boundary and development realm reconciliation | Membership and permissions in [Phase 03](docs/roadmap/phase-03-identity-admin.md); current exit state in [Phase 02b](docs/roadmap/phase-02b-events-auth.md) | | **Frontend** | Native TLS ingress, live locale entry, trusted server caller, localized catalog/course/lesson pages, safe themes, accessibility controls/manual smoke, generated typed SDK and optional bounded native BFF session scaffolds | Full renderer/Studio and Playwright Test/axe in [Phase 06](docs/roadmap/phase-06-renderer-admin-studio.md) | **Four modules contain domain implementations:** Tenancy, Customization, Audit and diff --git a/backend/Directory.Build.props b/backend/Directory.Build.props index ff89d4e65..40e56171a 100644 --- a/backend/Directory.Build.props +++ b/backend/Directory.Build.props @@ -7,15 +7,11 @@ enable true - $(WarningsNotAsErrors);LS0001 + $(WarningsNotAsErrors);LS0001;LS0002 true latest + + + diff --git a/backend/analyzers/LearnStack.Analyzers/SensitiveExceptionMessageAnalyzer.cs b/backend/analyzers/LearnStack.Analyzers/SensitiveExceptionMessageAnalyzer.cs new file mode 100644 index 000000000..a670bbad5 --- /dev/null +++ b/backend/analyzers/LearnStack.Analyzers/SensitiveExceptionMessageAnalyzer.cs @@ -0,0 +1,175 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using LearnStack.SharedKernel.Secrets; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; + +namespace LearnStack.Analyzers; + +/// +/// Flags sensitive named values in string arguments of directly thrown +/// exceptions (ADR-0032 Amendment 6). This bounded name guard does not trace +/// prior assignments or inspect literal contents and formatting-helper roots. +/// +/// +/// LS0002 runs in all production projects and remains a Warning, including CI, +/// until Phase 03 exit. Both token sets and word matching come from the internal +/// source compiled into this assembly and SharedKernel; no runtime reference is +/// needed. Diagnostic messages never render an expression or its value. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class SensitiveExceptionMessageAnalyzer : DiagnosticAnalyzer +{ + public const string DiagnosticId = "LS0002"; + + /// The human-readable rule name (ADR-0032 Amendment 6). + public const string RuleName = "LearnStackException-SensitiveExceptionMessage"; + + private static readonly DiagnosticDescriptor Rule = new( + id: DiagnosticId, + title: "Avoid sensitive values in exception messages (LearnStackException-SensitiveExceptionMessage)", + messageFormat: "Use a fixed exception message without sensitive values; keep sensitive data out of exception constructor strings", + category: "Security", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: "ADR-0032 Amendment 6 forbids sensitive named values in directly thrown exception strings. " + + "Use a fixed message and the existing redaction and closed diagnostic boundaries.", + helpLinkUri: "https://github.com/HodeTech/LearnStack/blob/main/docs/decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25"); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + + public override void Initialize(AnalysisContext context) + { + if (context is null) throw new System.ArgumentNullException(nameof(context)); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + context.RegisterCompilationStartAction(start => + { + var exceptionType = start.Compilation.GetTypeByMetadataName("System.Exception"); + if (exceptionType is null) return; + start.RegisterOperationAction(operation => AnalyzeThrow(operation, exceptionType), OperationKind.Throw); + }); + } + + private static void AnalyzeThrow(OperationAnalysisContext context, INamedTypeSymbol exceptionType) + { + var thrown = (IThrowOperation)context.Operation; + var creation = Unwrap(thrown.Exception); + if (creation is null || !IsException(creation.Type, exceptionType)) + { + return; + } + + // An unrelated dynamic argument changes constructor binding, not the + // known exception type or its statically known string arguments. + var sensitive = creation switch + { + IObjectCreationOperation regular => regular.Arguments.Any(argument => IsSensitiveArgument(argument.Value)), + IDynamicObjectCreationOperation dynamicCreation => dynamicCreation.Arguments.Any(IsSensitiveArgument), + _ => false, + }; + if (sensitive) context.ReportDiagnostic(Diagnostic.Create(Rule, creation.Syntax.GetLocation())); + } + + private static bool IsSensitiveArgument(IOperation argument) + { + var value = Unwrap(argument); + return value is not null && IsStringValue(argument) + && IsSupportedRoot(value) && ContainsSensitiveReference(value); + } + + private static bool IsException(ITypeSymbol? type, INamedTypeSymbol exceptionType) + { + for (var current = type; current is not null; current = current.BaseType) + { + if (SymbolEqualityComparer.Default.Equals(current, exceptionType)) return true; + } + + return false; + } + + private static IOperation? Unwrap(IOperation? operation) + { + while (true) + { + switch (operation) + { + case IConversionOperation conversion: + operation = conversion.Operand; + break; + case IParenthesizedOperation parenthesized: + operation = parenthesized.Operand; + break; + default: + return operation; + } + } + } + + private static bool IsStringValue(IOperation operation) + { + // A string may be converted to object for a provider-specific constructor, + // or an object value may be explicitly cast to its string message type. + while (true) + { + if (operation.Type?.SpecialType == SpecialType.System_String) return true; + switch (operation) + { + case IConversionOperation conversion: + operation = conversion.Operand; + break; + case IParenthesizedOperation parenthesized: + operation = parenthesized.Operand; + break; + default: + return false; + } + } + } + + private static bool IsSupportedRoot(IOperation operation) => operation is + ILocalReferenceOperation or IParameterReferenceOperation or IFieldReferenceOperation + or IPropertyReferenceOperation or IInterpolatedStringOperation + || operation is IBinaryOperation + { + OperatorKind: BinaryOperatorKind.Add, + OperatorMethod: null, + Type.SpecialType: SpecialType.System_String, + }; + + private static bool ContainsSensitiveReference(IOperation operation) + { + var pending = new Stack(); + pending.Push(operation); + while (pending.Count > 0) + { + var current = pending.Pop(); + // These operands name values or deferred bodies without evaluating them. + if (current is INameOfOperation or ITypeOfOperation or ILiteralOperation + or IAnonymousFunctionOperation or ILocalFunctionOperation) + { + continue; + } + + var name = current switch + { + ILocalReferenceOperation local => local.Local.Name, + IParameterReferenceOperation parameter => parameter.Parameter.Name, + IFieldReferenceOperation field => field.Field.Name, + IPropertyReferenceOperation property => property.Property.Name, + _ => null, + }; + + if (name is not null && SensitiveTokenMatcher.IsSensitive(name)) return true; + + foreach (var child in current.ChildOperations) + { + pending.Push(child); + } + } + + return false; + } +} diff --git a/backend/src/Directory.Build.props b/backend/src/Directory.Build.props new file mode 100644 index 000000000..a5a4e7498 --- /dev/null +++ b/backend/src/Directory.Build.props @@ -0,0 +1,19 @@ + + + + + + + false + true + + + + + + + + diff --git a/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs b/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs index f529d5e23..0cf015c80 100644 --- a/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs @@ -39,7 +39,7 @@ public static class CrossCuttingFoundationExtensions /// startup errors are captured; OpenTelemetry tracing + metrics binds /// next; branches by /// ; the MediatR pipeline registers the - /// eight canonical behaviors. + /// eight canonical stages: seven behaviors plus the handler. /// public static WebApplicationBuilder AddLearnStackCrossCuttingFoundation( this WebApplicationBuilder builder, diff --git a/backend/src/LearnStack.Application/LearnStack.Application.csproj b/backend/src/LearnStack.Application/LearnStack.Application.csproj index 1f24b4e04..80850fd8e 100644 --- a/backend/src/LearnStack.Application/LearnStack.Application.csproj +++ b/backend/src/LearnStack.Application/LearnStack.Application.csproj @@ -9,12 +9,6 @@ - - diff --git a/backend/src/LearnStack.Application/Pipeline/AuthorizationBehavior.cs b/backend/src/LearnStack.Application/Pipeline/AuthorizationBehavior.cs index 8547bfa73..524aa80f9 100644 --- a/backend/src/LearnStack.Application/Pipeline/AuthorizationBehavior.cs +++ b/backend/src/LearnStack.Application/Pipeline/AuthorizationBehavior.cs @@ -5,10 +5,9 @@ namespace LearnStack.Application.Pipeline; /// /// MediatR pipeline behavior — step 5 of the canonical 8-step order -/// (ADR-0032 § Sub-decision 2). Calls -/// IAuthorizationService.AuthorizeAsync against the command's -/// resource; on deny returns Result.Fail(forbidden) rather than -/// throwing. +/// (ADR-0032 § Sub-decision 2). The current shell passes requests through; +/// Phase 03 owns resource-aware permission checks and the +/// Result.Fail(forbidden) refusal path. /// /// /// Phase 02a Packet 3 ships the shell: there is no diff --git a/backend/src/LearnStack.Domain/LearnStack.Domain.csproj b/backend/src/LearnStack.Domain/LearnStack.Domain.csproj index 0bb1b8efd..1809e088f 100644 --- a/backend/src/LearnStack.Domain/LearnStack.Domain.csproj +++ b/backend/src/LearnStack.Domain/LearnStack.Domain.csproj @@ -7,16 +7,6 @@ - - diff --git a/backend/src/LearnStack.Infrastructure.ErrorTracking/SentryErrorTracker.cs b/backend/src/LearnStack.Infrastructure.ErrorTracking/SentryErrorTracker.cs index b07136111..63812d49d 100644 --- a/backend/src/LearnStack.Infrastructure.ErrorTracking/SentryErrorTracker.cs +++ b/backend/src/LearnStack.Infrastructure.ErrorTracking/SentryErrorTracker.cs @@ -75,8 +75,7 @@ public ValueTask CaptureAsync( // process — Sentry is external egress. Uses the same // SensitiveTokenCatalog the Serilog enricher + the // air-gapped LocalFileErrorTracker share so the three - // surfaces cannot drift (Standards 11 § Sensitive Data - // Exposure). + // surfaces cannot drift (Standards 11 § Logging Hygiene). scope.SetTag( key, SensitiveTokenCatalog.IsSensitive(key) diff --git a/backend/src/LearnStack.Infrastructure.Observability/Serilog/RedactSensitiveFieldsEnricher.cs b/backend/src/LearnStack.Infrastructure.Observability/Serilog/RedactSensitiveFieldsEnricher.cs index 622b9853b..34d20a291 100644 --- a/backend/src/LearnStack.Infrastructure.Observability/Serilog/RedactSensitiveFieldsEnricher.cs +++ b/backend/src/LearnStack.Infrastructure.Observability/Serilog/RedactSensitiveFieldsEnricher.cs @@ -9,14 +9,14 @@ namespace LearnStack.Infrastructure.Observability.Serilog; /// formatter touches them. Per /// Standards 10 /// § Logging Rules and -/// Standards 11 § Sensitive Data Exposure: +/// Standards 11 § Logging Hygiene: /// passwords, tokens, DSNs, JWTs, API keys, national / corporate identifiers, /// authorization headers, full payment payloads must never reach the /// console or the OTLP sink. /// /// /// -/// The token list lives in +/// The token list is exposed by /// — /// the canonical source the air-gapped LocalFileErrorTracker shares /// so the two redaction surfaces cannot drift. Adding a token there lights @@ -28,7 +28,7 @@ namespace LearnStack.Infrastructure.Observability.Serilog; /// field nested inside a non-sensitive top-level property /// (e.g. User.Password) is scrubbed too. Reconstruction is lazy — /// a value with no sensitive descendant is returned by reference, so the -/// common (clean) event allocates nothing. +/// clean value needs no reconstruction. Name matching can still allocate. /// /// /// Stack traces and exception messages are NOT redacted — they ride @@ -37,15 +37,13 @@ namespace LearnStack.Infrastructure.Observability.Serilog; /// exception messages) so the boundary stays honest. /// /// -/// The compile-time half of this rule is LS0002 in -/// LearnStack.Analyzers, which flags string-interpolated or concatenated -/// throw new ...Exception($"...{token}...") patterns in Domain + -/// Application. It ships as a Warning in +/// LS0002 in LearnStack.Analyzers checks direct sensitive string +/// references, interpolation and concatenation in directly thrown exceptions +/// across production C# projects (ADR-0032 Amendment 6). It ships as a Warning in /// Phase 02b -/// and escalates to Error at Phase 03 exit. Today the -/// "no secrets in exception messages" rule rests on Standards 11 review -/// discipline; promoting it to a compile-time check closes the last -/// gap the runtime redactor cannot. +/// and escalates to Error at Phase 03 exit. It is a bounded name guard, not +/// taint analysis or a replacement for review and closed diagnostic controls. +/// Runtime redaction still leaves exception messages and stack traces intact. /// /// public sealed class RedactSensitiveFieldsEnricher : ILogEventEnricher @@ -63,7 +61,7 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) // Collect first, mutate after — never mutate logEvent.Properties // while enumerating it. The list materialises only when a top-level // property needs rewriting (its name is sensitive, or a sensitive - // value lives nested inside it), so a clean event allocates nothing. + // value lives nested inside it), so a clean event needs no rewrite list. List? rewrites = null; foreach (var (name, value) in logEvent.Properties) diff --git a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs index d32fa1a1e..d03e327a7 100644 --- a/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs +++ b/backend/src/LearnStack.Infrastructure/MultiTenancy/PlatformAdminScope.cs @@ -238,9 +238,9 @@ await services.ServiceProvider /// sentinel is legal, every other announcement site refusing it (ADR-0044 § 1, § 10). /// /// - /// No actor and no correlation id, and both are deliberate. There is no - /// principal in the process — authentication is Phase 02b — so the caller is known - /// only through the compiler-supplied provenance, which lands in metadata + /// No actor and no correlation id. Tenant authentication is live, but this + /// scope accepts no operator identity and its platform-permission gate denies all + /// callers until Phase 03. Compiler-supplied provenance lands in metadata /// rather than being flattened into reason: the reason is an operator-authored /// slug that a query groups by, and appending a file and a line to it would make every /// group of one. The correlation id is scoped state, and this scope is entered from diff --git a/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContext.cs b/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContext.cs index 6fd6a3f0b..50609c4a5 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContext.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContext.cs @@ -8,9 +8,10 @@ namespace LearnStack.Infrastructure.Persistence; /// /// /// outbox_messages, idempotency_keys, event_deliveries and -/// inbox_messages belong to no module: they -/// are reached through SharedKernel ports by any module's handler and read by -/// infrastructure that belongs to none of them. IIdempotencyStore ships +/// inbox_messages belong to no module. This migration chain also owns +/// LearnStack job state and guarded Hangfire control storage. Their runtime +/// paths use the corresponding infrastructure ports and confined credentials. +/// IIdempotencyStore ships /// today, behind InMemoryIdempotencyStore until its ADR-0035 trigger /// fires; IOutbox enqueues immediately on the ambient transaction under /// ADR-0057. @@ -29,10 +30,11 @@ namespace LearnStack.Infrastructure.Persistence; /// registration and never acquire a dispatcher connection. /// /// -/// All four tables are tenant-owned despite living outside a module. The -/// delivery ledger is organization-scoped to protect retained envelopes; -/// the other three are tenant-wide machinery. Every row carries a tenant key -/// and the corresponding canonical policy applies. +/// The original outbox, idempotency, delivery and inbox tables are tenant-owned; +/// the delivery ledger is additionally organization-scoped. Job and vendor tables +/// have separate tenant, recurrence-control and vendor-control classes under +/// Database Standards. +/// They must not inherit the original four-table classification by assumption. /// The dispatcher reads across tenants through learnstack_outbox_admin's /// BYPASSRLS, bounded by a column-scoped grant rather than by the policy. /// @@ -45,9 +47,10 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) // No entity types. These tables are written through their ports with // parameterised SQL, not through a change tracker: an outbox row is - // enqueued and never updated by application code, and an idempotency - // claim is a single INSERT ... ON CONFLICT that decides five outcomes in - // one round trip (ADR-0037 Amendment 2). Mapping them as entities would + // enqueued and never updated by application code. ADR-0037 Amendment 2 + // specifies the future PostgreSQL idempotency adapter's single-round-trip + // claim; the current registered store remains in memory. Mapping these as + // entities would // add a model nothing queries and invite exactly the row-by-row use both // designs avoid. // diff --git a/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContextFactory.cs b/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContextFactory.cs index c1d6c979a..460d13b87 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContextFactory.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/PlatformDbContextFactory.cs @@ -17,7 +17,7 @@ namespace LearnStack.Infrastructure.Persistence; /// public sealed class PlatformDbContextFactory : IDesignTimeDbContextFactory { - private const string ConnectionStringVariable = "ConnectionStrings__Migration"; + private const string MigrationEnvironmentKey = "ConnectionStrings__Migration"; /// /// The migration history table for this chain — its own, so the two chains @@ -32,12 +32,12 @@ public sealed class PlatformDbContextFactory : IDesignTimeDbContextFactory - /// Who acted. Deliberately never redacted: once the users row is erased - /// it is an orphan surrogate with no path back to a natural person, which is what - /// keeps the row's existence auditable after erasure and the probe-detection queries - /// answerable. + /// Who acted. Deliberately retained for audit continuity and probe detection after + /// the users row is erased. This pseudonymous identifier may still be linked + /// to a person through other retained records; deleting that row does not establish + /// anonymization. /// public required UserId? ActorUserId { get; init; } diff --git a/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs b/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs index 52e8bf65e..cd4abc65b 100644 --- a/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs +++ b/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs @@ -43,11 +43,11 @@ namespace LearnStack.SharedKernel.Identifiers; /// It is not a foreign key, and needs no users row. /// created_by, updated_by, deleted_by and /// audit_log.actor_user_id carry no referential constraint anywhere in - /// the schema, and that absence is load-bearing: GDPR erasure leaves the audit - /// row's actor as an orphan surrogate key with no path back to a natural - /// person, which is what keeps the row's existence auditable after erasure. An - /// enforced foreign key would make that state unreachable under every - /// ON DELETE action. See + /// the schema, so an actor identifier can remain after the user row is erased. + /// It preserves audit continuity but remains pseudonymous and may be linked to + /// a person through other retained records; erasing the user row alone does not + /// establish anonymization. An enforced foreign key would require an explicit + /// deletion policy for these retained references. See /// ADR-0038 /// Amendment 1; the users table itself is owned by Phase 03. /// diff --git a/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenCatalog.cs b/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenCatalog.cs index d759e933f..e87bec173 100644 --- a/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenCatalog.cs +++ b/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenCatalog.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; + namespace LearnStack.SharedKernel.Secrets; /// @@ -6,7 +8,7 @@ namespace LearnStack.SharedKernel.Secrets; /// passwords, tokens, secrets, payment identifiers, national / corporate IDs. /// The Serilog RedactSensitiveFieldsEnricher and the air-gapped /// LocalFileErrorTracker consume this single source of truth so the -/// two redaction surfaces cannot drift. +/// redaction surfaces and the LS0002 analyzer cannot drift. /// /// /// @@ -17,13 +19,13 @@ namespace LearnStack.SharedKernel.Secrets; /// UserPassword → ["user", "password"] still matches /// password. Two-word tokens (api_key, card_number) match /// either the joined form (apikey) or adjacent segments -/// (Api+Key). Standards 11 § Sensitive Data Exposure is -/// authoritative for what counts as sensitive; this list is the runtime -/// expression of that rule. +/// (Api+Key). Standards 11 § Logging Hygiene forbids sensitive disclosure. This +/// bounded matcher implements name-based filtering, not complete PII discovery. +/// Plurals, numeric suffixes and arbitrary unsplit compounds are not inferred. /// /// -/// New tokens land here, not in the consuming projects, so a future addition -/// lights up the Serilog path and the air-gapped path together. +/// New tokens land in the shared internal matcher, so a future addition +/// reaches runtime redaction and compile-time checking together. /// /// public static class SensitiveTokenCatalog @@ -32,151 +34,14 @@ public static class SensitiveTokenCatalog public const string RedactedValue = "***REDACTED***"; /// - /// Single-word tokens matched against a whole name-segment (or the - /// separator-stripped full name). Sorted alphabetically. - /// - private static readonly HashSet SingleWordTokens = - new(StringComparer.OrdinalIgnoreCase) - { - "apikey", - "authorization", - "cardnumber", - "connectionstring", // embeds the database password - "cookie", // session material - "credential", - "creditcard", - "cvc", - "cvv", - "dsn", - "encryptionkey", - "hmac", // ADR-0019's Hub request envelope - "iban", - "jwt", - "otp", - "pan", // primary account number - "passwd", - "password", - "pin", - "privatekey", // signed-licence RSA material, per ISecretProvider - "pwd", - "secret", - "signature", - "signingkey", - "ssn", // national ID (US SSN / TR shorthand) - "tckn", // Turkish national ID - "token", - "vkn", // Turkish corporate tax number (Vergi Kimlik Numarası) - }; - - /// - /// Joined forms of two-word tokens, matched against adjacent - /// camelCase / separated segments (Api+Key → apikey). - /// - private static readonly HashSet TwoWordTokens = - new(StringComparer.OrdinalIgnoreCase) - { - "apikey", // api_key / ApiKey - "cardnumber", // card_number / CardNumber - "authheader", // auth_header / AuthHeader - "authenticationheader", // authentication_header / AuthenticationHeader - "connectionstring", // connection_string / ConnectionString - "creditcard", // credit_card / CreditCard - "encryptionkey", // encryption_key / EncryptionKey - "privatekey", // private_key / PrivateKey - "setcookie", // set_cookie / SetCookie - "signingkey", // signing_key / SigningKey - }; - - /// - /// The canonical token list (for docs / tests). Returns a snapshot, not - /// the backing set, so a caller casting the - /// result cannot mutate the catalogue. - /// - public static IReadOnlyCollection DefaultTokens => - Array.AsReadOnly(SingleWordTokens.ToArray()); - - /// - /// Returns true when any whole segment of - /// (split on camelCase boundaries and _ . - separators) matches a - /// sensitive token. Word-boundary matching prevents the substring - /// false-positives that a naive Contains would produce (e.g. - /// ssn inside className). + /// An immutable, cached snapshot of the complete single-word and two-word + /// token union. The backing matcher sets are never exposed. /// - public static bool IsSensitive(string propertyName) - { - if (string.IsNullOrEmpty(propertyName)) - { - return false; - } - - var segments = Tokenize(propertyName); - - // Whole-name fallback: a property literally named "apikey" (no - // separators / case transitions) tokenises to a single segment that - // the single-word set already covers, so this is implicit. - for (var i = 0; i < segments.Count; i++) - { - if (SingleWordTokens.Contains(segments[i]) || TwoWordTokens.Contains(segments[i])) - { - return true; - } - - if (i + 1 < segments.Count - && TwoWordTokens.Contains(segments[i] + segments[i + 1])) - { - return true; - } - } - - return false; - } + public static IReadOnlyCollection DefaultTokens => SensitiveTokenMatcher.DefaultTokens; /// - /// Splits a property name into lowercase word segments on camelCase - /// transitions and _ . - (and any non-alphanumeric) separators. + /// Returns true when the name contains a sensitive whole word or + /// adjacent word pair, using the canonical word-boundary matcher. /// - private static List Tokenize(string name) - { - var segments = new List(); - var start = 0; - - for (var i = 0; i < name.Length; i++) - { - var c = name[i]; - var isSeparator = !char.IsLetterOrDigit(c); - - // camelCase boundaries: - // case 1 aA / 1A — lower/digit → Upper (userToken → user|Token) - // case 2 ABc — Upper → Upper-then-lower (SSNToken → ssn|Token, - // APIKey → api|Key) so trailing acronym letters - // start the next word. - var isCamelBoundary = i > start && char.IsUpper(c) && - ((char.IsLower(name[i - 1]) || char.IsDigit(name[i - 1])) - || (char.IsUpper(name[i - 1]) - && i + 1 < name.Length - && char.IsLower(name[i + 1]))); - - if (isSeparator) - { - if (i > start) - { - segments.Add(name[start..i].ToLowerInvariant()); - } - - start = i + 1; - } - else if (isCamelBoundary) - { - segments.Add(name[start..i].ToLowerInvariant()); - start = i; - } - } - - if (start < name.Length) - { - segments.Add(name[start..].ToLowerInvariant()); - } - - return segments; - } + public static bool IsSensitive(string propertyName) => SensitiveTokenMatcher.IsSensitive(propertyName); } diff --git a/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenMatcher.cs b/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenMatcher.cs new file mode 100644 index 000000000..0b7d12f58 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenMatcher.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LearnStack.SharedKernel.Secrets; + +/// +/// Owns the sensitive word tokens and matcher shared by runtime redaction and +/// the LS0002 analyzer. This source also compiles under netstandard2.0. +/// +internal static class SensitiveTokenMatcher +{ + /// + /// Single-word tokens matched against a whole name-segment (or the + /// separator-stripped full name). Sorted alphabetically. + /// + private static readonly HashSet SingleWordTokens = + new(StringComparer.OrdinalIgnoreCase) + { + "apikey", + "authorization", + "cardnumber", + "connectionstring", // embeds the database password + "cookie", // session material + "credential", + "creditcard", + "cvc", + "cvv", + "dsn", + "encryptionkey", + "hmac", // ADR-0019's Hub request envelope + "iban", + "jwt", + "otp", + "pan", // primary account number + "passwd", + "password", + "pin", + "privatekey", // signed-licence RSA material, per ISecretProvider + "pwd", + "secret", + "signature", + "signingkey", + "ssn", // national ID (US SSN / TR shorthand) + "tckn", // Turkish national ID + "token", + "vkn", // Turkish corporate tax number + }; + + /// + /// Joined forms of two-word tokens, matched against adjacent + /// camelCase / separated segments (Api+Key → apikey). + /// + private static readonly HashSet TwoWordTokens = + new(StringComparer.OrdinalIgnoreCase) + { + "apikey", // api_key / ApiKey + "cardnumber", // card_number / CardNumber + "authheader", // auth_header / AuthHeader + "authenticationheader", // authentication_header / AuthenticationHeader + "connectionstring", // connection_string / ConnectionString + "creditcard", // credit_card / CreditCard + "encryptionkey", // encryption_key / EncryptionKey + "privatekey", // private_key / PrivateKey + "setcookie", // set_cookie / SetCookie + "signingkey", // signing_key / SigningKey + }; + + /// + /// The immutable complete union of both token sets. + /// + internal static IReadOnlyCollection DefaultTokens { get; } = + Array.AsReadOnly(SingleWordTokens.Concat(TwoWordTokens) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(token => token, StringComparer.Ordinal) + .ToArray()); + + /// + /// Returns true when any whole segment of + /// (split on camelCase boundaries and _ . - separators) matches a + /// sensitive token. Word-boundary matching prevents the substring + /// false-positives that a naive Contains would produce (e.g. + /// ssn inside className). + /// + internal static bool IsSensitive(string propertyName) + { + if (string.IsNullOrEmpty(propertyName)) + { + return false; + } + + var segments = Tokenize(propertyName); + + // Whole-name fallback: a property literally named "apikey" (no + // separators / case transitions) tokenises to a single segment that + // the single-word set already covers, so this is implicit. + for (var i = 0; i < segments.Count; i++) + { + if (SingleWordTokens.Contains(segments[i]) || TwoWordTokens.Contains(segments[i])) + { + return true; + } + + if (i + 1 < segments.Count + && TwoWordTokens.Contains(segments[i] + segments[i + 1])) + { + return true; + } + } + + return false; + } + + /// + /// Splits a property name into lowercase word segments on camelCase + /// transitions and _ . - (and any non-alphanumeric) separators. + /// + private static List Tokenize(string name) + { + var segments = new List(); + var start = 0; + + for (var i = 0; i < name.Length; i++) + { + var c = name[i]; + var isSeparator = !char.IsLetterOrDigit(c); + + // camelCase boundaries: + // case 1 aA / 1A — lower/digit → Upper (userToken → user|Token) + // case 2 ABc — Upper → Upper-then-lower (SSNToken → ssn|Token, + // APIKey → api|Key) so trailing acronym letters + // start the next word. + var isCamelBoundary = i > start && char.IsUpper(c) && + ((char.IsLower(name[i - 1]) || char.IsDigit(name[i - 1])) + || (char.IsUpper(name[i - 1]) + && i + 1 < name.Length + && char.IsLower(name[i + 1]))); + + if (isSeparator) + { + if (i > start) + { + segments.Add(name.Substring(start, i - start).ToLowerInvariant()); + } + + start = i + 1; + } + else if (isCamelBoundary) + { + segments.Add(name.Substring(start, i - start).ToLowerInvariant()); + start = i; + } + } + + if (start < name.Length) + { + segments.Add(name.Substring(start).ToLowerInvariant()); + } + + return segments; + } +} diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs index bed33994e..79e3f3b59 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminGate.cs @@ -54,9 +54,7 @@ public ValueTask IsPermittedAsync( public sealed class PlatformAdminScopeDeniedException : Exception { public PlatformAdminScopeDeniedException(string reason) - : base($"Platform-admin scope entry was refused for reason '{reason}'. " - + "No principal in this deployment holds a platform-scope permission: " - + "authentication arrives in Phase 02b and the permission itself in Phase 03.") => + : base($"Platform-admin scope entry was refused for reason '{reason}'.") => Reason = reason; public PlatformAdminScopeDeniedException() diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs index b38fcc467..a84930af0 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs @@ -31,7 +31,7 @@ namespace LearnStack.SharedKernel.Tenancy; /// /// /// Entry is audited, and an entry that cannot be recorded does not happen. Every -/// EnterAsync writes one platform.admin_scope.enter row — the slug the +/// permitted entry writes one platform.admin_scope.enter row — the slug the /// Tenancy catalogue source declares off-path at MUST / SecurityEvent — through /// IAuditStore.WritePlatformScopeAsync, as learnstack_platform, on the /// scope's own connection and in a transaction of its own that commits before the @@ -42,6 +42,8 @@ namespace LearnStack.SharedKernel.Tenancy; /// ride the handle's transaction, so rolling the work back erased the only record that /// privileged access had happened; the review of Packet 9 measured it, and an entry is now /// recorded whatever the work then does. +/// The permission gate runs first; a refused attempt opens no privileged connection and +/// writes no entry row. /// /// /// The Warning log line stays, and it is not the record. The row is what a @@ -67,11 +69,10 @@ public interface IPlatformAdminScope /// Supplied by the compiler; do not pass. /// Supplied by the compiler; do not pass. /// - /// The three Caller* parameters are how "the caller" is known at all. There is - /// no principal in the process — authentication is Phase 02b and - /// AuthorizationBehavior is still a pass-through — so the alternative to the - /// compiler filling these in is a log line that records only that someone - /// entered. These are the first use of the attributes anywhere in this solution. + /// The three Caller* parameters record the calling code. Tenant principals + /// do not authorize this bypass: the shipped platform gate denies everyone, and + /// this scope accepts no operator identity. Phase 03 owns permission-aware entry + /// and actor attribution. Compiler provenance remains distinct from that identity. /// Task EnterAsync( string reason, diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/LearnStack.Modules.Audit.Application.csproj b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/LearnStack.Modules.Audit.Application.csproj index 9694008c9..40a8c09af 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/LearnStack.Modules.Audit.Application.csproj +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/LearnStack.Modules.Audit.Application.csproj @@ -8,9 +8,6 @@ - diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/AuditEntry.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/AuditEntry.cs index 16b188ad6..a442d5a22 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/AuditEntry.cs +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/AuditEntry.cs @@ -66,11 +66,10 @@ private AuditEntry() /// Who acted, when there was a principal. /// - /// Never redacted, unlike . Once the users row is - /// erased this is an orphan surrogate with no path back to a natural person, which is - /// what keeps the row's existence auditable after erasure and the probe-detection - /// queries answerable. Redacting it would collapse every erased user's history into - /// one indistinguishable bucket. + /// Retained, unlike , for audit continuity and probe detection + /// after the users row is erased. This pseudonymous identifier may remain + /// linkable through other retained records; deleting that row does not establish + /// anonymization. /// public UserId? ActorUserId { get; private set; } diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/LearnStack.Modules.Audit.Domain.csproj b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/LearnStack.Modules.Audit.Domain.csproj index 9fe047726..bed685370 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/LearnStack.Modules.Audit.Domain.csproj +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Domain/LearnStack.Modules.Audit.Domain.csproj @@ -6,9 +6,6 @@ - diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContextFactory.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContextFactory.cs index d64541bb0..deffb18cb 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContextFactory.cs +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContextFactory.cs @@ -34,7 +34,7 @@ namespace LearnStack.Modules.Audit.Infrastructure.Persistence; /// public sealed class AuditDbContextFactory : IDesignTimeDbContextFactory { - private const string ConnectionStringVariable = "ConnectionStrings__Migration"; + private const string MigrationEnvironmentKey = "ConnectionStrings__Migration"; /// /// The migration history table for this chain. @@ -49,12 +49,12 @@ public sealed class AuditDbContextFactory : IDesignTimeDbContextFactory - diff --git a/backend/src/Modules/Content/LearnStack.Modules.Content.Domain/LearnStack.Modules.Content.Domain.csproj b/backend/src/Modules/Content/LearnStack.Modules.Content.Domain/LearnStack.Modules.Content.Domain.csproj index ebd5459b9..7b4e904ef 100644 --- a/backend/src/Modules/Content/LearnStack.Modules.Content.Domain/LearnStack.Modules.Content.Domain.csproj +++ b/backend/src/Modules/Content/LearnStack.Modules.Content.Domain/LearnStack.Modules.Content.Domain.csproj @@ -6,9 +6,6 @@ - diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Application/LearnStack.Modules.Customization.Application.csproj b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Application/LearnStack.Modules.Customization.Application.csproj index f10889b18..971173b01 100644 --- a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Application/LearnStack.Modules.Customization.Application.csproj +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Application/LearnStack.Modules.Customization.Application.csproj @@ -9,9 +9,6 @@ - diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Domain/LearnStack.Modules.Customization.Domain.csproj b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Domain/LearnStack.Modules.Customization.Domain.csproj index f3072407b..a8a4bc5a0 100644 --- a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Domain/LearnStack.Modules.Customization.Domain.csproj +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Domain/LearnStack.Modules.Customization.Domain.csproj @@ -6,9 +6,6 @@ - diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContextFactory.cs b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContextFactory.cs index 4c05656e4..1a303d692 100644 --- a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContextFactory.cs +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContextFactory.cs @@ -40,7 +40,7 @@ namespace LearnStack.Modules.Customization.Infrastructure.Persistence; public sealed class CustomizationDbContextFactory : IDesignTimeDbContextFactory { - private const string ConnectionStringVariable = "ConnectionStrings__Migration"; + private const string MigrationEnvironmentKey = "ConnectionStrings__Migration"; /// /// The migration history table for this chain. @@ -55,12 +55,12 @@ public sealed class CustomizationDbContextFactory public CustomizationDbContext CreateDbContext(string[] args) { - var connectionString = Environment.GetEnvironmentVariable(ConnectionStringVariable); + var connectionString = Environment.GetEnvironmentVariable(MigrationEnvironmentKey); if (string.IsNullOrWhiteSpace(connectionString)) { throw new InvalidOperationException( - $"{ConnectionStringVariable} is not set in the environment. " + $"{MigrationEnvironmentKey} is not set in the environment. " + "Migrations run as learnstack_migration, which owns every table; the value " + "is in .env.example and `make migrate` is its sanctioned carrier. " + "`dotnet ef --connection` does not help here — EF applies it after this " diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Application/LearnStack.Modules.Education.Application.csproj b/backend/src/Modules/Education/LearnStack.Modules.Education.Application/LearnStack.Modules.Education.Application.csproj index 6a586e4dd..63c40b843 100644 --- a/backend/src/Modules/Education/LearnStack.Modules.Education.Application/LearnStack.Modules.Education.Application.csproj +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Application/LearnStack.Modules.Education.Application.csproj @@ -10,9 +10,6 @@ - diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Domain/LearnStack.Modules.Education.Domain.csproj b/backend/src/Modules/Education/LearnStack.Modules.Education.Domain/LearnStack.Modules.Education.Domain.csproj index fa5b00d93..ca0ba5418 100644 --- a/backend/src/Modules/Education/LearnStack.Modules.Education.Domain/LearnStack.Modules.Education.Domain.csproj +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Domain/LearnStack.Modules.Education.Domain.csproj @@ -6,9 +6,6 @@ - diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContextFactory.cs b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContextFactory.cs index 87eb5d883..bb2bc67f9 100644 --- a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContextFactory.cs +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContextFactory.cs @@ -7,18 +7,18 @@ namespace LearnStack.Modules.Education.Infrastructure.Persistence; /// Builds the Education migration chain without runtime configuration. public sealed class EducationDbContextFactory : IDesignTimeDbContextFactory { - private const string ConnectionStringVariable = "ConnectionStrings__Migration"; + private const string MigrationEnvironmentKey = "ConnectionStrings__Migration"; /// The independent Education chain's migration history table. public const string HistoryTable = "__ef_migrations_history_education"; public EducationDbContext CreateDbContext(string[] args) { - var connectionString = Environment.GetEnvironmentVariable(ConnectionStringVariable); + var connectionString = Environment.GetEnvironmentVariable(MigrationEnvironmentKey); if (string.IsNullOrWhiteSpace(connectionString)) { throw new InvalidOperationException( - $"{ConnectionStringVariable} is not set in the environment. " + $"{MigrationEnvironmentKey} is not set in the environment. " + "Migrations run as learnstack_migration; use `make migrate`. " + "Runtime connection strings are never a migration fallback."); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj index bec2d3182..f263e6b43 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj @@ -8,9 +8,6 @@ - diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/LearnStack.Modules.Identity.Domain.csproj b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/LearnStack.Modules.Identity.Domain.csproj index 75a9043e9..59eda776a 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/LearnStack.Modules.Identity.Domain.csproj +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/LearnStack.Modules.Identity.Domain.csproj @@ -6,9 +6,6 @@ - diff --git a/backend/src/Modules/Media/LearnStack.Modules.Media.Application/LearnStack.Modules.Media.Application.csproj b/backend/src/Modules/Media/LearnStack.Modules.Media.Application/LearnStack.Modules.Media.Application.csproj index 20a7fbcf4..3566dfa5c 100644 --- a/backend/src/Modules/Media/LearnStack.Modules.Media.Application/LearnStack.Modules.Media.Application.csproj +++ b/backend/src/Modules/Media/LearnStack.Modules.Media.Application/LearnStack.Modules.Media.Application.csproj @@ -8,9 +8,6 @@ - diff --git a/backend/src/Modules/Media/LearnStack.Modules.Media.Domain/LearnStack.Modules.Media.Domain.csproj b/backend/src/Modules/Media/LearnStack.Modules.Media.Domain/LearnStack.Modules.Media.Domain.csproj index 93134df07..327287923 100644 --- a/backend/src/Modules/Media/LearnStack.Modules.Media.Domain/LearnStack.Modules.Media.Domain.csproj +++ b/backend/src/Modules/Media/LearnStack.Modules.Media.Domain/LearnStack.Modules.Media.Domain.csproj @@ -6,9 +6,6 @@ - diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/LearnStack.Modules.Tenancy.Application.csproj b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/LearnStack.Modules.Tenancy.Application.csproj index a655c7367..2971b970b 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/LearnStack.Modules.Tenancy.Application.csproj +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/LearnStack.Modules.Tenancy.Application.csproj @@ -8,9 +8,6 @@ - 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 8628b4abb..95e375595 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 @@ -126,18 +126,14 @@ [new LocalizedMessage("lockey_host_taken")], // It runs BEFORE the commit, and the guarantee is correspondingly narrower than // "the window is closed". TransactionBehavior commits after the handler returns, // so a concurrent request arriving between this line and that COMMIT still misses - // the uncommitted row and re-caches the miss with a fresh TTL. What this does - // guarantee is the case that actually happens: the request AFTER the write, which - // is the seeded-host-in-a-browser one. + // the uncommitted row and re-caches the miss with a fresh TTL. This invalidation + // helps a request after commit when no intervening miss repopulated the cache; + // concurrent misses can still keep that 404 until the TTL expires. // - // Closing the remainder needs a post-commit seam on IUnitOfWork, whose surface - // [ADR-0040](../../../../../../docs/decisions/0040-ambient-unit-of-work.md) - // governs — so it is an amendment, not an edit, and it is owed by the first - // obligation that cannot tolerate the gap. The outbox dispatch in - // [Phase 02b](../../../../../../docs/roadmap/phase-02b-events-auth.md) is that - // obligation; this call joins it there. Until then the residual window is bounded - // by the same TTL it exists to shorten, so the failure mode is the old one for a - // few milliseconds rather than a new one. + // This is a best-effort shortening of the existing TTL, not post-commit + // invalidation. The residual miss can live for that full TTL. The outbox's + // immediate transactional INSERT and independent polling dispatcher do not add + // a post-commit callback or strengthen this cache guarantee (ADR-0057). await resolutionCache.InvalidateAsync(mapping.Host, cancellationToken); return Result.Ok(new HostMappingDto( diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/LearnStack.Modules.Tenancy.Domain.csproj b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/LearnStack.Modules.Tenancy.Domain.csproj index 46f276a3e..67f0c9e9d 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/LearnStack.Modules.Tenancy.Domain.csproj +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/LearnStack.Modules.Tenancy.Domain.csproj @@ -6,9 +6,6 @@ - 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 093ce34b9..1eb0a3385 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Domain/PlatformProjections.cs @@ -279,13 +279,13 @@ public sealed class PlatformKillswitch public DateTimeOffset ToggledAt { get; private set; } /// - /// Who flipped it, once there is a principal to record. + /// Who flipped it, once Phase 03 supplies the permission-checked writer. /// /// /// Nullable and plain rather than UserId: the column holds /// no foreign key — a killswitch outlives the operator who set it and must not be - /// undeletable because of one — and there is no principal in the process until - /// Phase 02b, so the first rows Phase 03 writes are the first that can name one. + /// undeletable because of one. Tenant authentication grants no platform permission; + /// the first rows Phase 03's authorized writer creates can name the operator. /// public Guid? ToggledBy { get; private set; } } diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContextFactory.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContextFactory.cs index c4c6c4a26..614b19b5d 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContextFactory.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContextFactory.cs @@ -43,7 +43,7 @@ namespace LearnStack.Modules.Tenancy.Infrastructure.Persistence; /// public sealed class TenancyDbContextFactory : IDesignTimeDbContextFactory { - private const string ConnectionStringVariable = "ConnectionStrings__Migration"; + private const string MigrationEnvironmentKey = "ConnectionStrings__Migration"; /// /// The migration history table for this chain. @@ -58,12 +58,12 @@ public sealed class TenancyDbContextFactory : IDesignTimeDbContextFactoryReads the compiler's evaluated references and rule scope, including imports. +internal static class AnalyzerProjectWiring +{ + private static readonly char[] WarningSeparators = [';', ',']; + private static readonly string[] ExecutionProperties = ["RunAnalyzers", "RunAnalyzersDuringBuild"]; + internal sealed record Reference(string FullPath, string OutputItemType, string ReferenceOutputAssembly); + internal sealed record Evaluation(Reference[] References, bool DomainRule, bool VisibleScope, string[] Exemptions, + string[] Suppressions, bool RunsAnalyzers) + { + public bool HasAnalyzer(string analyzerPath) + { + var matches = References.Where(reference => + Path.GetFullPath(reference.FullPath) == Path.GetFullPath(analyzerPath)).ToArray(); + return matches.Length == 1 && matches[0].OutputItemType == "Analyzer" + && matches[0].ReferenceOutputAssembly.Equals("false", StringComparison.OrdinalIgnoreCase); + } + } + + public static string AnalyzerPath => Path.Combine(RepositoryPaths.RepoRoot(), + "backend", "analyzers", "LearnStack.Analyzers", "LearnStack.Analyzers.csproj"); + + public static async Task ReadAsync(string project, string configuration) + { + using var child = new Process + { + StartInfo = new ProcessStartInfo("dotnet") + { + ArgumentList = + { + "msbuild", project, "-nologo", "-property:Configuration=" + configuration, + "-getItem:ProjectReference,CompilerVisibleProperty", + "-getProperty:LearnStackAnalyzeDomainExceptionThrow,WarningsNotAsErrors,NoWarn,RunAnalyzers,RunAnalyzersDuringBuild", + }, + WorkingDirectory = Path.GetDirectoryName(project)!, + RedirectStandardOutput = true, + RedirectStandardError = true, + }, + }; + child.StartInfo.Environment["MSBUILDTERMINALLOGGER"] = "off"; + child.StartInfo.Environment["CI"] = "true"; + child.Start(); + var output = child.StandardOutput.ReadToEndAsync(); + var error = child.StandardError.ReadToEndAsync(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + try + { + await child.WaitForExitAsync(deadline.Token); + } + catch (OperationCanceledException) + { + child.Kill(entireProcessTree: true); + await child.WaitForExitAsync(); + await Task.WhenAll(output, error); + throw new InvalidOperationException("Evaluating analyzer wiring exceeded its deadline."); + } + + await Task.WhenAll(output, error); + if (child.ExitCode != 0) + throw new InvalidOperationException("Evaluating analyzer wiring failed for " + Path.GetFileName(project)); + return Parse(await output); + } + + internal static Evaluation Parse(string output) + { + using var document = JsonDocument.Parse(output); + var root = document.RootElement; + var properties = root.GetProperty("Properties"); + var items = root.GetProperty("Items"); + return new Evaluation( + items.GetProperty("ProjectReference").EnumerateArray().Select(reference => new Reference( + reference.GetProperty("FullPath").GetString()!, + reference.TryGetProperty("OutputItemType", out var type) ? type.GetString()! : "", + reference.TryGetProperty("ReferenceOutputAssembly", out var assembly) ? assembly.GetString()! : "")).ToArray(), + bool.Parse(properties.GetProperty("LearnStackAnalyzeDomainExceptionThrow").GetString()!), + items.GetProperty("CompilerVisibleProperty").EnumerateArray().Any(item => + item.GetProperty("Identity").GetString() == "LearnStackAnalyzeDomainExceptionThrow"), + properties.GetProperty("WarningsNotAsErrors").GetString()! + .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), + properties.GetProperty("NoWarn").GetString()! + .Split(WarningSeparators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), + !ExecutionProperties.Any(name => + properties.GetProperty(name).GetString()!.Equals("false", StringComparison.OrdinalIgnoreCase))); + } + + /// Evaluation on one OS cannot prove an analyzer reference is unconditional. + internal static bool HasUnconditionalReference(XDocument props) + { + var references = props.Descendants("ProjectReference").Where(element => + ((string?)element.Attribute("Include"))?.Replace('\\', '/') + .EndsWith("/LearnStack.Analyzers/LearnStack.Analyzers.csproj", StringComparison.Ordinal) == true).ToArray(); + return references.Length == 1 + && (string?)references[0].Attribute("OutputItemType") == "Analyzer" + && (string?)references[0].Attribute("ReferenceOutputAssembly") == "false" + && !references[0].AncestorsAndSelf().Any(element => + element.Attribute("Condition") is not null || element.Name.LocalName is "Choose" or "When" or "Otherwise"); + } + + /// Also inspects settings inside targets that evaluation alone would not execute. + internal static bool SuppressesSensitiveRule(XDocument build) => build.Descendants().Any(element => + element.Name.LocalName == "NoWarn" && Regex.IsMatch(element.Value, @"\bLS0002\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) + || element.Name.LocalName is "RunAnalyzers" or "RunAnalyzersDuringBuild" + && element.Value.Trim().Equals("false", StringComparison.OrdinalIgnoreCase) + || ChangesAnalyzerItem(element)); + + private static bool ChangesAnalyzerItem(XElement element) + { + var selector = element.Name.LocalName switch + { + "Analyzer" => element.Attribute("Remove"), + "ProjectReference" => element.Attribute("Remove") ?? element.Attribute("Update"), + _ => null, + }; + var fileName = element.Name.LocalName == "Analyzer" ? "LearnStack.Analyzers.dll" : "LearnStack.Analyzers.csproj"; + return selector is not null + && selector.Value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Any(pattern => + { + var selectedName = Path.GetFileName(pattern.Replace('\\', '/')); + return selectedName.Contains("$(", StringComparison.Ordinal) || selectedName.Contains("@(", StringComparison.Ordinal) + || FileSystemName.MatchesSimpleExpression(selectedName, fileName, ignoreCase: true); + }); + } + + internal static bool SuppressesSensitiveRule(string editorConfig) => Regex.IsMatch(editorConfig, + @"^\s*dotnet_(?:diagnostic\.LS0002|analyzer_diagnostic(?:\.category-Security)?)\.severity\s*=\s*(?:none|silent|suggestion)\s*(?:[#;].*)?$", + RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/AnalyzerReport.cs b/backend/tests/LearnStack.Tests.Architecture/AnalyzerReport.cs index 4a1bdd0eb..516ea564b 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AnalyzerReport.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AnalyzerReport.cs @@ -11,8 +11,8 @@ namespace LearnStack.Tests.Architecture; /// -/// Runs an in-tree analyzer over a project's real sources and reports what it found, for -/// Domain_Methods_Do_Not_Throw_For_Expected_Cases. +/// Runs the in-tree exception analyzers over real project sources, independently of +/// build severity and local suppressions. /// /// /// @@ -119,6 +119,8 @@ internal static string[] EvaluatedSymbols(string projectPath, string? configurat if (configuration is not null) msbuild.StartInfo.ArgumentList.Add("-property:Configuration=" + configuration); + msbuild.StartInfo.Environment["MSBUILDTERMINALLOGGER"] = "off"; + msbuild.StartInfo.Environment["CI"] = "true"; msbuild.Start(); var output = msbuild.StandardOutput.ReadToEndAsync(); @@ -158,13 +160,38 @@ internal static string[] EvaluatedSymbols(string projectPath, string? configurat /// over them. /// public static async Task RunAsync(string projectPath, params string[] planted) + { + var (compilation, trees, diagnostics) = await AnalyzeAsync( + projectPath, new DomainExceptionThrowAnalyzer(), DomainExceptionThrowAnalyzer.DiagnosticId, null, planted); + return new Run( + Path.GetFileNameWithoutExtension(projectPath), + [.. diagnostics.Select(diagnostic => Locate(diagnostic, compilation))], + trees.Sum(tree => ResultReturningMembers(tree, compilation).Count)); + } + + /// + /// Runs LS0002 independently of build severity and reports even locally suppressed sites. + /// Findings contain locations and member names, never source expressions or values. + /// + public static async Task> SensitiveAsync( + string projectPath, string configuration, params string[] planted) + { + var (compilation, _, diagnostics) = await AnalyzeAsync( + projectPath, new SensitiveExceptionMessageAnalyzer(), SensitiveExceptionMessageAnalyzer.DiagnosticId, + configuration, planted); + return [.. diagnostics.Select(diagnostic => Locate(diagnostic, compilation))]; + } + + private static async Task<(CSharpCompilation Compilation, List Trees, ImmutableArray Diagnostics)> + AnalyzeAsync(string projectPath, DiagnosticAnalyzer analyzer, string diagnosticId, + string? configuration, string[] planted) { var name = Path.GetFileNameWithoutExtension(projectPath); var directory = Path.GetDirectoryName(projectPath)!; // The symbols the build defines, so an `#if` region is parsed rather than skipped: code // inside one the parser drops is code this rule cannot see, and the rule is the gate. var parse = new CSharpParseOptions(LanguageVersion.Latest, DocumentationMode.None) - .WithPreprocessorSymbols(EvaluatedSymbols(projectPath)); + .WithPreprocessorSymbols(EvaluatedSymbols(projectPath, configuration)); var trees = Sources(directory) .Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parse, file)) @@ -197,21 +224,23 @@ public static async Task RunAsync(string projectPath, params string[] plant nullableContextOptions: NullableContextOptions.Enable, specificDiagnosticOptions: new Dictionary(StringComparer.Ordinal) { - [DomainExceptionThrowAnalyzer.DiagnosticId] = ReportDiagnostic.Warn, + [diagnosticId] = ReportDiagnostic.Warn, })); - var kernel = compilation.GetTypeByMetadataName("LearnStack.SharedKernel.Errors.DomainException"); + var requiredType = diagnosticId == DomainExceptionThrowAnalyzer.DiagnosticId + ? "LearnStack.SharedKernel.Errors.DomainException" : "System.Exception"; + var kernel = compilation.GetTypeByMetadataName(requiredType); if (kernel is null) { throw new InvalidOperationException( - $"{name}'s compilation cannot resolve DomainException, so the analyzer has " + $"{name}'s compilation cannot resolve {requiredType}, so the analyzer has " + "nothing to recognise and would report nothing whatever the code did."); } var diagnostics = await compilation .WithAnalyzers( - ImmutableArray.Create(new DomainExceptionThrowAnalyzer()), + ImmutableArray.Create(analyzer), new CompilationWithAnalyzersOptions( new AnalyzerOptions([]), onAnalyzerException: null, @@ -229,12 +258,7 @@ public static async Task RunAsync(string projectPath, params string[] plant $"The analyzer crashed on {name}: {crashed[0].GetMessage(CultureInfo.InvariantCulture)}"); } - return new Run( - name, - [.. diagnostics - .Where(diagnostic => diagnostic.Id == DomainExceptionThrowAnalyzer.DiagnosticId) - .Select(diagnostic => Locate(diagnostic, compilation))], - trees.Sum(tree => ResultReturningMembers(tree, compilation).Count)); + return (compilation, trees, [.. diagnostics.Where(diagnostic => diagnostic.Id == diagnosticId)]); } /// The member a diagnostic sits in, and whether that member returns a result. diff --git a/backend/tests/LearnStack.Tests.Architecture/AnalyzerWiringTests.cs b/backend/tests/LearnStack.Tests.Architecture/AnalyzerWiringTests.cs new file mode 100644 index 000000000..053cd0148 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/AnalyzerWiringTests.cs @@ -0,0 +1,126 @@ +using System.Xml.Linq; +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// Supporting structural controls for ADR-0032 Amendment 6's compiler contract. +public sealed class AnalyzerWiringTests +{ + private static readonly string[] EditorConfigNames = [".editorconfig", ".globalconfig"]; + + [Theory] + [InlineData("Debug")] + [InlineData("Release")] + public async Task Production_Projects_Run_The_Bounded_Exception_Analyzers(string configuration) + { + var projects = Directory.GetFiles(RepositoryPaths.BackendSrc(), "*.csproj", SearchOption.AllDirectories); + projects.Should().NotBeEmpty(); + projects.Should().Contain(path => Path.GetFileName(path) == "LearnStack.Api.csproj"); + projects.Should().Contain(path => Path.GetFileName(path) == "LearnStack.Infrastructure.csproj"); + var domainProjects = AnalyzerReport.Projects().ToHashSet(StringComparer.Ordinal); + foreach (var project in projects.Order(StringComparer.Ordinal)) + { + var wiring = await AnalyzerProjectWiring.ReadAsync(project, configuration); + wiring.HasAnalyzer(AnalyzerProjectWiring.AnalyzerPath).Should().BeTrue( + "{0} must load exactly one in-tree analyzer reference without a runtime dependency", project); + wiring.DomainRule.Should().Be(domainProjects.Contains(project), + "LS0001 must retain its existing Domain/Application project set: {0}", project); + wiring.VisibleScope.Should().BeTrue("the compiler must pass the scope to the analyzer: {0}", project); + wiring.Exemptions.Should().Contain(["LS0001", "LS0002"], + "both rules remain visible Warnings until Phase 03 exit: {0}", project); + wiring.Suppressions.Should().NotContain(id => id.Equals("LS0002", StringComparison.OrdinalIgnoreCase), + "LS0002 must remain visible: {0}", project); + wiring.RunsAnalyzers.Should().BeTrue("the production compiler must run its analyzers: {0}", project); + } + } + + [Fact] + public void The_Evaluated_Wiring_Control_Rejects_A_Library_Or_Duplicate_Reference() + { + var analyzer = AnalyzerProjectWiring.AnalyzerPath; + var good = new AnalyzerProjectWiring.Reference(analyzer, "Analyzer", "false"); + var evaluation = new AnalyzerProjectWiring.Evaluation([good], false, true, ["LS0001", "LS0002"], [], true); + evaluation.HasAnalyzer(analyzer).Should().BeTrue(); + (evaluation with { References = [] }).HasAnalyzer(analyzer).Should().BeFalse(); + (evaluation with { References = [good, good] }).HasAnalyzer(analyzer).Should().BeFalse(); + (evaluation with { References = [good, good with { OutputItemType = "" }] }).HasAnalyzer(analyzer).Should().BeFalse(); + (evaluation with { References = [good with { OutputItemType = "" }] }).HasAnalyzer(analyzer).Should().BeFalse(); + (evaluation with { References = [good with { ReferenceOutputAssembly = "true" }] }).HasAnalyzer(analyzer).Should().BeFalse(); + } + + [Fact] + public void Production_Analyzer_Reference_Is_Unconditional_And_Cannot_Be_Silenced_By_Build_Settings() + { + var backend = Path.Combine(RepositoryPaths.RepoRoot(), "backend"); + AnalyzerProjectWiring.HasUnconditionalReference(XDocument.Load(Path.Combine(backend, "src", "Directory.Build.props"))) + .Should().BeTrue("Fix: keep the shared production analyzer reference and its ancestors unconditional"); + + var settings = Directory.EnumerateFiles(RepositoryPaths.BackendSrc(), "*", SearchOption.AllDirectories) + .Concat(Directory.EnumerateFiles(backend, "*", SearchOption.TopDirectoryOnly)) + .Where(path => !Path.GetRelativePath(backend, path).Split(Path.DirectorySeparatorChar) + .Any(segment => segment is "bin" or "obj")) + .Where(path => Path.GetExtension(path) is ".csproj" or ".props" or ".targets" + || Path.GetFileName(path) is ".editorconfig" or ".globalconfig") + .Concat(EditorConfigNames + .Select(name => Path.Combine(RepositoryPaths.RepoRoot(), name)).Where(File.Exists)).ToArray(); + settings.Should().NotBeEmpty(); + settings.Where(path => Path.GetExtension(path) is ".csproj" or ".props" or ".targets" + ? AnalyzerProjectWiring.SuppressesSensitiveRule(XDocument.Load(path)) + : AnalyzerProjectWiring.SuppressesSensitiveRule(File.ReadAllText(path))) + .Select(path => Path.GetRelativePath(RepositoryPaths.RepoRoot(), path)) + .Order(StringComparer.Ordinal).Should().BeEmpty( + "Fix: retain LS0002 as a visible Warning and keep production analyzer execution enabled (ADR-0032 Amendment 6)"); + } + + [Theory] + [InlineData("{0}", true)] + [InlineData("{0}", false)] + [InlineData("{0}", false)] + [InlineData("{0}", false)] + public void The_Unconditional_Reference_Control_Rejects_Environment_Branches(string wrapper, bool expected) + { + const string reference = ""; + var xml = "" + wrapper.Replace("{0}", reference, StringComparison.Ordinal) + ""; + AnalyzerProjectWiring.HasUnconditionalReference(XDocument.Parse(xml)).Should().Be(expected); + AnalyzerProjectWiring.HasUnconditionalReference(XDocument.Parse(xml.Replace("OutputItemType=", + "Condition=\"'$(OS)' == 'Unix'\" OutputItemType=", StringComparison.Ordinal))).Should().BeFalse(); + } + + [Theory] + [InlineData("$(NoWarn);LS0002")] + [InlineData("false")] + [InlineData("false")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("")] + public void The_Build_Setting_Control_Rejects_LS0002_Suppression(string body) => + AnalyzerProjectWiring.SuppressesSensitiveRule(XDocument.Parse("" + body + "")).Should().BeTrue(); + + [Fact] + public void Unrelated_Analyzer_And_Warning_Settings_Are_Allowed() => + AnalyzerProjectWiring.SuppressesSensitiveRule(XDocument.Parse(""" + + trueCA1707 + + + + + """)).Should().BeFalse(); + + [Theory] + [InlineData("dotnet_diagnostic.LS0002.severity = none", true)] + [InlineData("dotnet_diagnostic.LS0002.severity = silent", true)] + [InlineData("dotnet_analyzer_diagnostic.category-Security.severity = none", true)] + [InlineData("dotnet_analyzer_diagnostic.severity = none", true)] + [InlineData("dotnet_diagnostic.LS0002.severity = warning", false)] + [InlineData("# dotnet_diagnostic.LS0002.severity = none", false)] + [InlineData("dotnet_diagnostic.CA1707.severity = none", false)] + public void The_EditorConfig_Control_Rejects_LS0002_Suppression(string setting, bool expected) => + AnalyzerProjectWiring.SuppressesSensitiveRule("[*.cs]\n" + setting).Should().Be(expected); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryCensus.cs b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryCensus.cs new file mode 100644 index 000000000..702ceeb55 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryCensus.cs @@ -0,0 +1,366 @@ +using System.Text; +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; + +namespace LearnStack.Tests.Architecture; + +/// +/// Structural table discovery from the operations the migration runner actually consumes. +/// This is a bounded table-declaration reader, not a SQL execution or field-value proof. +/// The independent integration census still checks the applied PostgreSQL catalogue. +/// +internal static class AsyncStoreInventoryCensus +{ + private static readonly Regex SqlTokens = new( + "(?--[^\\r\\n]*|/\\*[\\s\\S]*?\\*/)|(?[Ee]'(?:\\\\[\\s\\S]|''|[^'\\\\])*'|'(?:''|[^'])*')|" + + "(?\"(?:\"\"|[^\"])*\")|(?\\$(?:[A-Za-z_][A-Za-z_0-9]*)?\\$)|" + + "(?[A-Za-z_][A-Za-z_0-9$]*)|(?\\S)", + RegexOptions.CultureInvariant); + private static readonly Regex DynamicTableDeclaration = new( + @"\b(?:CREATE\s+(?:(?:TEMP|TEMPORARY|UNLOGGED|FOREIGN)\s+)?TABLE|DROP\s+TABLE|ALTER\s+TABLE)\b", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + // The pinned installer has precisely these non-table dynamic command families. + // Resolve literal concatenation only; do not evaluate format(), variables or arbitrary SQL. + private static readonly Regex PinnedInstallerCommand = new( + "^(?:CREATE SCHEMA \"public\";|ALTER SEQUENCE \"public\"\\." + + "(?:counter|hash|jobparameter|jobqueue|list|set|state|job)_id_seq " + + "(?:AS bigint )?MAXVALUE 9223372036854775807|" + + "CREATE INDEX ix_hangfire_job_statename_is_not_null ON job USING btree\\(statename\\) " + + "INCLUDE \\(id\\) WHERE statename IS NOT NULL)$", + RegexOptions.CultureInvariant); + + internal static MigrationOperation[] Operations(DbContext context) + { + var assembly = context.GetService(); + return assembly.Migrations.OrderBy(pair => pair.Key, StringComparer.Ordinal) + .SelectMany(pair => + { + var operations = assembly.CreateMigration(pair.Value, context.Database.ProviderName!).UpOperations; + foreach (var operation in operations) + operation["InventoryOrigin"] = $"{context.GetType().Name}/{pair.Key}"; + return operations; + }).ToArray(); + } + + internal static HashSet Tables(IEnumerable operations) + { + var tables = new HashSet(StringComparer.Ordinal); + foreach (var operation in operations) + { + try + { + switch (operation) + { + case CreateTableOperation create: + Create(Name(create.Schema, create.Name), false); + break; + case DropSchemaOperation: + throw new FormatException("Schema mutation requires an explicit census reader decision."); + case DropTableOperation drop: + Drop(Name(drop.Schema, drop.Name), false); + break; + case RenameTableOperation rename: + var previous = Name(rename.Schema, rename.Name); + Drop(previous, false); + Create(Name(rename.NewSchema ?? rename.Schema, rename.NewName ?? rename.Name), false); + break; + case SqlOperation sql: + ReadSql(sql.Sql); + break; + } + } + catch (FormatException exception) + { + throw new FormatException($"{operation["InventoryOrigin"] ?? "Planted migration"} " + + $"({operation.GetType().Name}): {exception.Message}", exception); + } + } + return tables; + + void Create(string name, bool conditional) + { + if (!tables.Add(name) && !conditional) + throw new FormatException($"Duplicate table declaration: {name}"); + } + + void Drop(string name, bool conditional) + { + if (!tables.Remove(name) && !conditional) + throw new FormatException($"Dropped table is absent from the census: {name}"); + } + + void ReadSql(string sql) + { + var tokens = Tokenize(sql.TrimStart('\uFEFF')); + string? dollarBody = null; + var selecting = false; + for (var index = 0; index < tokens.Length; index++) + { + if (tokens[index].Dollar) + { + if (dollarBody is null) dollarBody = tokens[index].Text; + else if (dollarBody == tokens[index].Text) dollarBody = null; + } + // Outside procedural dollar bodies SELECT INTO creates a table. Inside them + // PostgreSQL uses it for assignment to PL/pgSQL variables instead. + if (dollarBody is null) + { + if (At(index).Text == ";") selecting = false; + if (Is(index, "SELECT")) selecting = true; + if (selecting && Is(index, "INTO")) + throw new FormatException("SELECT INTO table creation requires an explicit census reader decision."); + } + if (Is(index, "DO") && !Is(index + 1, "NOTHING") && !Is(index + 1, "UPDATE")) + { + var body = index + 1; + if (Is(body, "LANGUAGE")) body += 2; + if (!At(body).Dollar) + throw new FormatException("Non-dollar procedural bodies require an explicit census reader decision."); + } + if (IdentifierIs(index, "set_config") && At(index + 1).Text == "(" + && (!At(index + 2).Literal || At(index + 2).Text[0] != '\'' || At(index + 3).Text != "," + || string.Equals(At(index + 2).Text, "'search_path'", StringComparison.OrdinalIgnoreCase))) + throw new FormatException("set_config search-path resolution requires an explicit census reader decision."); + if (((Is(index, "DROP") || Is(index, "ALTER")) && Is(index + 1, "SCHEMA")) + || (Is(index, "IMPORT") && Is(index + 1, "FOREIGN") && Is(index + 2, "SCHEMA"))) + throw new FormatException("Schema mutation requires an explicit census reader decision."); + if ((Is(index, "CREATE") || Is(index, "ALTER") || Is(index, "DROP")) + && Is(index + 1, "MATERIALIZED")) + throw new FormatException("Materialized view storage requires an explicit census reader decision."); + if (Is(index, "EXECUTE") && !IsStaticExecuteClause(index)) + RequirePinnedExecute(index + 1); + + // Dynamic table DDL cannot be resolved by this reader. Refuse it rather than + // treating a literal embedded in EXECUTE/format as a harmless absence of tables. + if (tokens[index].Literal && DynamicTableDeclaration.IsMatch(tokens[index].Text)) + throw new FormatException("Dynamic table DDL requires an explicit census reader decision."); + + // Function-header SET clauses are distinct from statements, including those + // in DO bodies. Resolve only the pinned public path; refuse aliases elsewhere. + if (Is(index, "SET") && (index == 0 || At(index - 1).Text == ";" + || Is(index - 1, "BEGIN") || Is(index - 1, "THEN") || Is(index - 1, "ELSE") || Is(index - 1, "LOOP"))) + { + var cursor = index + 1; + if (Is(cursor, "LOCAL") || Is(cursor, "SESSION")) cursor++; + if (SettingIs(cursor, "search_path") || SettingIs(cursor, "schema")) + { + var schemaAlias = SettingIs(cursor++, "schema"); + if (!schemaAlias) + { + if (At(cursor).Text != "=" && !Is(cursor, "TO")) + throw new FormatException("Unsupported search-path assignment."); + cursor++; + } + var path = At(cursor++).Text.Trim('\'', '"'); + if (path != "public" || (cursor < tokens.Length && At(cursor).Text != ";")) + throw new FormatException("The table census does not assume a non-public search path."); + } + } + + if (Is(index, "CREATE")) + { + var cursor = index + 1; + if (Is(cursor, "OR") && Is(cursor + 1, "REPLACE")) cursor += 2; + if (Is(cursor, "FUNCTION") || Is(cursor, "PROCEDURE")) + { + // A quoted routine body is opaque to this declaration reader, + // just like a quoted DO body. Split EXECUTE text can hide table + // DDL until a later SELECT/CALL executes the routine. + var parentheses = 0; + string? headerDollar = null; + var hasDollarBody = false; + for (; cursor < tokens.Length; cursor++) + { + var token = At(cursor); + if (token.Dollar) + { + if (headerDollar is null) headerDollar = token.Text; + else if (headerDollar == token.Text) headerDollar = null; + continue; + } + if (headerDollar is not null) continue; + if (token.Text == "(") parentheses++; + else if (token.Text == ")") parentheses--; + if (parentheses == 0 && Is(cursor, "SET") && SettingIs(cursor + 1, "search_path")) + { + var path = cursor + 2; + if (At(path).Text != "=" && !Is(path, "TO")) + throw new FormatException("Unresolved routine search path requires an explicit census reader decision."); + do + { + path++; + if (!IdentifierIs(path, "public") && !IdentifierIs(path, "pg_catalog") + && At(path).Text is not "'public'" and not "'pg_catalog'") + throw new FormatException("Non-pinned routine search path requires an explicit census reader decision."); + path++; + } while (At(path).Text == ","); + cursor = path - 1; + continue; + } + if (parentheses == 0 && Is(cursor, "AS")) + { + if (!At(cursor + 1).Dollar) + throw new FormatException("Non-dollar procedural bodies require an explicit census reader decision."); + hasDollarBody = true; + } + if (parentheses == 0 && token.Text == ";") break; + } + if (!hasDollarBody) + throw new FormatException("Non-dollar procedural bodies require an explicit census reader decision."); + continue; + } + if (Is(cursor, "TEMP") || Is(cursor, "TEMPORARY") || Is(cursor, "UNLOGGED") + || Is(cursor, "FOREIGN") || Is(cursor, "GLOBAL") || Is(cursor, "LOCAL")) + throw new FormatException("Unsupported table persistence declaration."); + if (!Is(cursor, "TABLE")) continue; + cursor++; + var conditional = Is(cursor, "IF"); + if (conditional) + { + Require(cursor + 1, "NOT"); + Require(cursor + 2, "EXISTS"); + cursor += 3; + } + Create(TableName(ref cursor), conditional); + } + else if (Is(index, "DROP") && Is(index + 1, "TABLE")) + { + var cursor = index + 2; + var conditional = Is(cursor, "IF"); + if (conditional) { Require(cursor + 1, "EXISTS"); cursor += 2; } + do + { + Drop(TableName(ref cursor), conditional); + } while (At(cursor++).Text == ","); + } + else if (Is(index, "ALTER") && Is(index + 1, "TABLE")) + { + var cursor = index + 2; + if (Is(cursor, "IF")) { Require(cursor + 1, "EXISTS"); cursor += 2; } + if (Is(cursor, "ONLY")) cursor++; + var previous = TableName(ref cursor); + if (Is(cursor, "SET") && Is(cursor + 1, "SCHEMA")) + throw new FormatException("Table schema moves require an explicit census reader decision."); + if (!Is(cursor, "RENAME") || !Is(cursor + 1, "TO")) continue; + cursor += 2; + var next = TableName(ref cursor); + Drop(previous, false); + Create(next, false); + } + } + if (dollarBody is not null) throw new FormatException("Unterminated SQL dollar body."); + + SqlToken At(int index) => index >= 0 && index < tokens.Length ? tokens[index] : default; + bool Is(int index, string word) => At(index).Word + && string.Equals(At(index).Text, word, StringComparison.OrdinalIgnoreCase); + bool IdentifierIs(int index, string name) => Is(index, name) + || (At(index).Quoted && At(index).Text == "\"" + name + "\""); + bool SettingIs(int index, string name) => Is(index, name) + || (At(index).Quoted && string.Equals(At(index).Text, "\"" + name + "\"", StringComparison.OrdinalIgnoreCase)); + bool IsStaticExecuteClause(int index) + { + if (dollarBody is not null) return false; + var start = index; + while (start > 0 && At(start - 1).Text != ";") start--; + if (Is(index + 1, "ON")) return Is(start, "GRANT") || Is(start, "REVOKE"); + return (Is(index + 1, "FUNCTION") || Is(index + 1, "PROCEDURE")) && Is(start, "CREATE") + && (Is(start + 1, "TRIGGER") || (Is(start + 1, "CONSTRAINT") && Is(start + 2, "TRIGGER"))); + } + void Require(int index, string word) + { + if (!Is(index, word)) throw new FormatException("Malformed table declaration."); + } + void RequirePinnedExecute(int cursor) + { + var command = new StringBuilder(); + var parentheses = 0; + var expectingLiteral = true; + while (cursor < tokens.Length && At(cursor).Text != ";") + { + var token = At(cursor++); + // Escape literals are tokenized for boundaries, never decoded as pinned values. + if (token.Literal && token.Text[0] == '\'' && expectingLiteral) + { + command.Append(token.Text[1..^1].Replace("''", "'", StringComparison.Ordinal)); + expectingLiteral = false; + } + else if (token.Text == "(" && expectingLiteral) parentheses++; + else if (token.Text == ")" && !expectingLiteral && parentheses > 0) parentheses--; + else if (token.Text == "|" && At(cursor).Text == "|" && !expectingLiteral) + { + cursor++; + expectingLiteral = true; + } + else throw new FormatException("Unresolved dynamic EXECUTE requires an explicit census reader decision."); + } + if (expectingLiteral || parentheses != 0 || !PinnedInstallerCommand.IsMatch(command.ToString())) + throw new FormatException("Dynamic EXECUTE is outside the pinned non-table installer commands."); + } + string Identifier(ref int cursor) + { + var token = At(cursor++); + if (token.Quoted) return token.Text[1..^1].Replace("\"\"", "\"", StringComparison.Ordinal); + if (token.Word) return token.Text.ToLowerInvariant(); + throw new FormatException("Malformed table identifier."); + } + string TableName(ref int cursor) + { + var first = Identifier(ref cursor); + if (At(cursor).Text != ".") return first; + cursor++; + return Name(first, Identifier(ref cursor)); + } + } + } + + private static SqlToken[] Tokenize(string sql) + { + var tokens = new List(); + var offset = 0; + string? delimiter = null; + var closing = -1; + while (offset < sql.Length) + { + // A body's closing delimiter is lexical, even in END$$. Do not let the + // ordinary identifier token consume it and hide subsequent SELECT INTO. + if (delimiter is not null && offset == closing) + { + tokens.Add(new SqlToken(delimiter, false, false, false, true)); + offset += delimiter.Length; + delimiter = null; + continue; + } + var match = SqlTokens.Match(sql, offset, (delimiter is null ? sql.Length : closing) - offset); + if (!match.Success) + { + if (delimiter is null) break; + offset = closing; + continue; + } + offset = match.Index + match.Length; + if (match.Groups["comment"].Success) continue; + // An unprefixed continuation inherits the preceding E literal's escape rules. + // Refuse that opaque value instead of reading it with ordinary quote boundaries. + if (match.Groups["literal"].Success && match.Value[0] == '\'' + && tokens.Count > 0 && tokens[^1].Literal && tokens[^1].Text[0] is 'E' or 'e') + throw new FormatException("Escape literal continuation requires an explicit census reader decision."); + tokens.Add(new SqlToken(match.Value, match.Groups["word"].Success, + match.Groups["quoted"].Success, match.Groups["literal"].Success, match.Groups["dollar"].Success)); + if (delimiter is null && match.Groups["dollar"].Success) + { + delimiter = match.Value; + closing = sql.IndexOf(delimiter, offset, StringComparison.Ordinal); + if (closing < 0) throw new FormatException("Unterminated SQL dollar body."); + } + } + return tokens.ToArray(); + } + + private static string Name(string? schema, string table) => schema is null or "public" ? table + : throw new FormatException("Non-public table storage requires an explicit census reader decision."); + + private readonly record struct SqlToken(string Text, bool Word, bool Quoted, bool Literal, bool Dollar); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs new file mode 100644 index 000000000..c8435ca87 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs @@ -0,0 +1,107 @@ +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore.Migrations.Operations; + +namespace LearnStack.Tests.Architecture; + +internal static class AsyncStoreInventoryDocument +{ + internal static readonly string[] Sections = ["first-party", "vendor", "exclusions", "module-exclusions", "custody"]; + private static readonly string[] CustodyNames = + [ + "Existing `audit_log`", "Development Keycloak user events, `EVENT_ENTITY`", + "External diagnostics and local error files", "Database, WAL and backups", "Native BFF session custody", + ]; + private static readonly Regex TableIdentifier = new(@"^`[a-z_][a-z_0-9]*`$", RegexOptions.CultureInvariant); + private static readonly Regex Separator = new(@"^:?-{3,}:?$", RegexOptions.CultureInvariant); + + internal static string[] Check(string document, IReadOnlyList platform, + IReadOnlyList audit, IEnumerable vendorContract, + IReadOnlyDictionary modules) + { + try + { + var failures = new List(); + var firstParty = Read(document, "first-party", "Store", "Copies and subject linkage", "Existing constraint"); + var vendor = Read(document, "vendor", "Vendor table", "Copy or control classification"); + var exclusions = Read(document, "exclusions", "Excluded table", "Scope boundary"); + var moduleExclusions = Read(document, "module-exclusions", "Excluded table", "Scope boundary"); + var custody = Read(document, "custody", "Store or custody boundary", "Subject linkage and limit"); + var firstNames = Names(firstParty); + var vendorNames = Names(vendor); + var excludedNames = Names(exclusions); + Count(firstParty, 10, "first-party"); + Count(vendor, 12, "vendor"); + Compare(excludedNames, ["idempotency_keys"], "explicit scope exclusion"); + Compare(custody.Select(row => row[0]), CustodyNames, "audit/provider/external/volatile custody"); + Compare(vendorNames, vendorContract, "vendor contract classifications"); + + var allInventoryNames = firstNames.Concat(vendorNames).Concat(excludedNames) + .Concat(Names(moduleExclusions)).Append("audit_log").ToArray(); + if (allInventoryNames.Distinct(StringComparer.Ordinal).Count() != allInventoryNames.Length) + failures.Add("A table appears in more than one inventory class."); + // No actual-table prefix or inventory membership filter: a newly introduced table + // must appear in the reviewed inventory or its explicit, bounded exclusion. + var discovered = AsyncStoreInventoryCensus.Tables(platform) + .Concat(AsyncStoreInventoryCensus.Tables(audit)) + .Concat(modules.Values.SelectMany(AsyncStoreInventoryCensus.Tables)).ToArray(); + if (discovered.Distinct(StringComparer.Ordinal).Count() != discovered.Length) + failures.Add("A table is declared by more than one migration chain."); + Compare(discovered, allInventoryNames, "complete five-chain migration census"); + return failures.ToArray(); + + void Count(IReadOnlyCollection rows, int expected, string label) + { + if (rows.Count != expected) failures.Add($"Expected {expected} {label} rows; found {rows.Count}."); + } + void Compare(IEnumerable actual, IEnumerable expected, string label) + { + var actualSet = actual.ToHashSet(StringComparer.Ordinal); + var expectedSet = expected.ToHashSet(StringComparer.Ordinal); + if (!actualSet.SetEquals(expectedSet)) + failures.Add($"{label}: unexpected [{string.Join(", ", actualSet.Except(expectedSet).Order(StringComparer.Ordinal))}]; " + + $"missing [{string.Join(", ", expectedSet.Except(actualSet).Order(StringComparer.Ordinal))}]."); + } + } + catch (FormatException exception) + { + return [exception.Message]; + } + } + + internal static string[][] Read(string document, string section, params string[] header) + { + var start = $""; + var end = $""; + var startIndex = document.IndexOf(start, StringComparison.Ordinal); + var endIndex = document.IndexOf(end, StringComparison.Ordinal); + if (startIndex < 0 || endIndex < startIndex + || document.IndexOf(start, startIndex + start.Length, StringComparison.Ordinal) >= 0 + || document.IndexOf(end, endIndex + end.Length, StringComparison.Ordinal) >= 0) + throw new FormatException($"Missing, repeated or reversed {section} census markers."); + var lines = document[(startIndex + start.Length)..endIndex].Split('\n', StringSplitOptions.TrimEntries) + .Where(line => line.Length != 0).ToArray(); + if (lines.Length < 2) throw new FormatException($"Missing {section} table."); + var cells = lines.Select(line => + { + if (!line.StartsWith('|') || !line.EndsWith('|')) + throw new FormatException($"Malformed {section} table row."); + var columns = line[1..^1].Split('|', StringSplitOptions.TrimEntries); + if (columns.Length != header.Length || columns.Any(string.IsNullOrWhiteSpace)) + throw new FormatException($"Missing {section} classification or malformed row."); + return columns; + }).ToArray(); + if (!cells[0].SequenceEqual(header, StringComparer.Ordinal) + || cells[1].Any(column => !Separator.IsMatch(column))) + throw new FormatException($"Malformed {section} table header."); + var rows = cells.Skip(2).ToArray(); + if (rows.Select(row => row[0]).Distinct(StringComparer.Ordinal).Count() != rows.Length) + throw new FormatException($"Duplicate {section} inventory row."); + return rows; + } + + private static string[] Names(IEnumerable rows) => rows.Select(row => + { + if (!TableIdentifier.IsMatch(row[0])) throw new FormatException("Malformed inventory table identifier."); + return row[0][1..^1]; + }).ToArray(); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs new file mode 100644 index 000000000..8def17c36 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs @@ -0,0 +1,313 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Audit.Infrastructure.Persistence; +using LearnStack.Modules.Customization.Infrastructure.Persistence; +using LearnStack.Modules.Education.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0046/0047/0057 structural inventory coverage. Locators, grants and mutability +/// require independent review; this proves neither erasure correctness nor legal compliance. +/// +public sealed class AsyncStoreInventoryTests +{ + [Fact] + public void Durable_Async_Store_Inventory_Covers_The_Storage_Census() + { + var subject = Subject(); + Check(subject.Document, subject.Platform, subject.Audit, subject.Modules).Should().BeEmpty( + "Architecture 23 inventories actual compiled Up operations, including all vendor installer tables; " + + "Fix: reconcile the inventory and its explicit exclusions against the storage definition"); + } + + [Fact] + public void Inventory_coverage_rejects_added_removed_and_reclassified_storage() + { + var subject = Subject(); + Check(subject.Document, subject.Platform, subject.Audit, subject.Modules).Should().BeEmpty("the unchanged control must pass"); + + // Both operation carriers matter: raw SQL is current Platform storage, typed table + // operations are used by Audit and must not silently bypass the census in a new migration. + MigrationOperation[] additions = + [ + new SqlOperation { Sql = "CREATE TABLE public.inventory_probe (id uuid);" }, + new CreateTableOperation { Name = "inventory_probe" }, + ]; + foreach (var addition in additions) + { + Check(subject.Document, [.. subject.Platform, addition], subject.Audit, subject.Modules) + .Should().Contain(failure => failure.Contains("unexpected [inventory_probe]", StringComparison.Ordinal)); + Check(subject.Document, subject.Platform, [.. subject.Audit, addition], subject.Modules) + .Should().Contain(failure => failure.Contains("unexpected [inventory_probe]", StringComparison.Ordinal)); + foreach (var module in subject.Modules.Keys) + { + var dirtyModules = new Dictionary(subject.Modules) + { + [module] = [.. subject.Modules[module], addition], + }; + Check(subject.Document, subject.Platform, subject.Audit, dirtyModules) + .Should().Contain(failure => failure.Contains("unexpected [inventory_probe]", StringComparison.Ordinal), + $"the {module} chain must independently expose newly added storage"); + } + } + + Check(subject.Document, [.. subject.Platform, new DropTableOperation { Name = "background_jobs" }], subject.Audit, subject.Modules) + .Should().Contain(failure => failure.Contains("missing [background_jobs]", StringComparison.Ordinal)); + Check(subject.Document, [.. subject.Platform, new RenameTableOperation { Name = "background_jobs", NewName = "renamed_jobs" }], subject.Audit, subject.Modules) + .Should().Contain(failure => failure.Contains("unexpected [renamed_jobs]; missing [background_jobs]", StringComparison.Ordinal)); + Check(subject.Document, subject.Platform, [.. subject.Audit, new DropTableOperation { Name = "audit_log" }], subject.Modules) + .Should().Contain(failure => failure.Contains("missing [audit_log]", StringComparison.Ordinal)); + AsyncStoreInventoryDocument.Check(subject.Document, subject.Platform, subject.Audit, + HangfireStorageContract.Columns.Keys.Append("new_vendor_table"), subject.Modules).Should().Contain(failure => failure.Contains( + "vendor contract classifications: unexpected []; missing [new_vendor_table]", StringComparison.Ordinal)); + } + + [Fact] + public void Inventory_coverage_rejects_every_removed_row_and_blank_vendor_classification() + { + var subject = Subject(); + Check(subject.Document, subject.Platform, subject.Audit, subject.Modules).Should().BeEmpty("the unchanged control must pass"); + foreach (var section in AsyncStoreInventoryDocument.Sections) + { + foreach (var row in DataLines(subject.Document, section)) + { + var removed = subject.Document.Replace(row + "\n", "", StringComparison.Ordinal); + removed.Should().NotBe(subject.Document, "the planted control must actually remove its row"); + var reason = section == "custody" ? "audit/provider/external/volatile custody" : "complete five-chain migration census"; + Check(removed, subject.Platform, subject.Audit, subject.Modules) + .Should().Contain(failure => failure.Contains(reason, StringComparison.Ordinal)); + + var duplicated = subject.Document.Replace(row, row + "\n" + row, StringComparison.Ordinal); + Check(duplicated, subject.Platform, subject.Audit, subject.Modules) + .Should().Contain($"Duplicate {section} inventory row."); + if (section != "vendor") continue; + var withoutClassification = row[..(row.IndexOf('|', 1) + 1)] + " |"; + var dirty = subject.Document.Replace(row, withoutClassification, StringComparison.Ordinal); + Check(dirty, subject.Platform, subject.Audit, subject.Modules) + .Should().Contain("Missing vendor classification or malformed row."); + } + } + } + + [Fact] + public void Inventory_coverage_requires_bounded_well_formed_tables() + { + var subject = Subject(); + var row = DataLines(subject.Document, "first-party")[0]; + var dirtyDocuments = new[] + { + (subject.Document.Replace("", "", StringComparison.Ordinal), + "Missing, repeated or reversed vendor census markers."), + (subject.Document.Replace("", "\n", StringComparison.Ordinal), + "Missing, repeated or reversed vendor census markers."), + (subject.Document.Replace("| Vendor table |", "| Unrecognised header |", StringComparison.Ordinal), + "Malformed vendor table header."), + (subject.Document.Replace(row, row.TrimEnd('|'), StringComparison.Ordinal), "Malformed first-party table row."), + // Keeping a removed row in nearby prose must not satisfy the canonical table. + (subject.Document.Replace(row + "\n", "", StringComparison.Ordinal) + "\n" + row, + "Expected 10 first-party rows; found 9."), + (subject.Document.Replace("| `idempotency_keys` |", "| `unreviewed_exclusion` |", StringComparison.Ordinal), + "explicit scope exclusion: unexpected [unreviewed_exclusion]; missing [idempotency_keys]."), + }; + foreach (var (document, reason) in dirtyDocuments) + Check(document, subject.Platform, subject.Audit, subject.Modules).Should().Contain(reason); + } + + [Fact] + public void Migration_census_tracks_ordered_literal_and_typed_table_lifecycle() + { + MigrationOperation[] operations = + [ + new SqlOperation { Sql = "-- CREATE TABLE commented_out (id int);\nCREATE TABLE IF NOT EXISTS public.\"first\" (id int);" }, + new SqlOperation { Sql = "CREATE TABLE IF NOT EXISTS public.\"first\" (id int); ALTER TABLE public.\"first\" RENAME TO second;" }, + new CreateTableOperation { Name = "third" }, + new RenameTableOperation { Name = "third", NewName = "fourth" }, + new SqlOperation { Sql = "DROP TABLE IF EXISTS public.second; DO $body$ BEGIN CREATE TABLE final_table (id int); END $body$;" }, + new DropTableOperation { Name = "fourth" }, + new SqlOperation { Sql = "DO $$ DECLARE selected_id int; BEGIN SELECT id INTO selected_id FROM final_table; " + + "EXECUTE 'CREATE SCHEMA \"public\";'; " + + "EXECUTE ('ALTER SEQUENCE \"' || 'public' || '\".job_id_seq AS bigint MAXVALUE 9223372036854775807'); END $$;" }, + new SqlOperation { Sql = "SET LOCAL \"search_path\" TO 'public'; SET SESSION search_path = public; SET SCHEMA 'public'; " + + "ALTER TABLE public.final_table RENAME TO renamed_table; ALTER TABLE public.renamed_table RENAME TO final_table; " + + "CREATE TRIGGER census_trigger BEFORE INSERT ON final_table FOR EACH ROW EXECUTE FUNCTION public.census_guard(); " + + "GRANT EXECUTE ON FUNCTION public.census_guard() TO PUBLIC; " + + "INSERT INTO final_table(id) VALUES(1) ON CONFLICT DO NOTHING; " + + "SELECT set_config('app.tenant_id', 'probe', true);" }, + new SqlOperation { Sql = "CREATE FUNCTION public.census_function(probe text DEFAULT $arg$)AS$arg$) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$ BEGIN NULL; END; $$; " + + "CREATE OR REPLACE PROCEDURE public.census_procedure() AS $body$ BEGIN NULL; END; $body$ LANGUAGE plpgsql SET search_path TO 'public';" }, + ]; + AsyncStoreInventoryCensus.Tables(operations).Should().BeEquivalentTo(["final_table"]); + } + + [Theory] + [InlineData("SELECT E'\\''; SELECT 1 INTO hidden; SELECT 'tail';")] + [InlineData("SELECT e'\\''; SELECT 1 INTO hidden; SELECT 'tail';")] + [InlineData("SELECT E'doubled''quote\\''; SELECT 1 INTO hidden; SELECT 'tail';")] + public void Migration_census_detects_select_into_after_escape_literals(string sql) + { + var read = () => AsyncStoreInventoryCensus.Tables([new SqlOperation { Sql = sql }]); + read.Should().Throw().WithMessage( + "Planted migration (SqlOperation): SELECT INTO table creation requires an explicit census reader decision."); + } + + [Theory] + [InlineData("SELECT E'\\'';")] + [InlineData("SELECT e'\\'';")] + [InlineData("SELECT E'backslash\\\\';")] + [InlineData("SELECT E'doubled''quote';")] + [InlineData("SELECT E'escaped\\q';")] + [InlineData("SELECT E'; SELECT 1 INTO hidden;';")] + [InlineData("SELECT E'\\'' || 'ordinary';")] + [InlineData("SELECT E'\\''; SELECT 'ordinary';")] + [InlineData("SELECT '\\';")] + [InlineData("SELECT 'doubled''quote';")] + public void Migration_census_preserves_literal_boundaries_before_table_declarations(string prefix) + { + AsyncStoreInventoryCensus.Tables([new SqlOperation + { + Sql = prefix + " CREATE TABLE literal_probe(id int); SELECT 'tail';", + }]).Should().Equal("literal_probe"); + } + + [Theory] + [InlineData("SELECT E'prefix'\n'\\''; SELECT 1 INTO hidden; SELECT 'tail';", + "Escape literal continuation requires an explicit census reader decision.")] + [InlineData("SELECT e'prefix'\n/* continuation */ '\\''; SELECT 1 INTO hidden; SELECT 'tail';", + "Escape literal continuation requires an explicit census reader decision.")] + [InlineData("SELECT E'prefix' -- continuation\n'\\''; SELECT 1 INTO hidden; SELECT 'tail';", + "Escape literal continuation requires an explicit census reader decision.")] + [InlineData("SELECT set_config(E'app.tenant_id', 'probe', true);", + "set_config search-path resolution requires an explicit census reader decision.")] + [InlineData("SELECT set_config(e'search_\\x70ath', 'other', true);", + "set_config search-path resolution requires an explicit census reader decision.")] + [InlineData("DO $$ BEGIN EXECUTE E'CREATE SCHEMA \"public\";'; END $$;", + "Unresolved dynamic EXECUTE requires an explicit census reader decision.")] + [InlineData("DO $$ BEGIN EXECUTE e'CREATE SCHEMA \"public\";'; END $$;", + "Unresolved dynamic EXECUTE requires an explicit census reader decision.")] + [InlineData("SET search_path = E'public';", + "The table census does not assume a non-public search path.")] + [InlineData("SET SCHEMA e'public';", + "The table census does not assume a non-public search path.")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void SET search_path = E'public' AS $$ BEGIN NULL; END; $$ LANGUAGE plpgsql;", + "Non-pinned routine search path requires an explicit census reader decision.")] + public void Migration_census_does_not_resolve_escape_literal_values(string sql, string reason) + { + var read = () => AsyncStoreInventoryCensus.Tables([new SqlOperation { Sql = sql }]); + read.Should().Throw().WithMessage($"Planted migration (SqlOperation): {reason}"); + } + + [Theory] + [InlineData("CREATE TEMP TABLE hidden_table (id int);", "Unsupported table persistence declaration.")] + [InlineData("CREATE UNLOGGED TABLE hidden_table (id int);", "Unsupported table persistence declaration.")] + [InlineData("CREATE GLOBAL TEMP TABLE hidden_table (id int);", "Unsupported table persistence declaration.")] + [InlineData("CREATE MATERIALIZED VIEW hidden_table AS SELECT 1 AS id;", "Materialized view storage")] + [InlineData("DO $$ BEGIN EXECUTE 'CREATE TABLE hidden_table (id int)'; END $$;", "Dynamic EXECUTE is outside")] + [InlineData("DO $$ BEGIN EXECUTE 'CREATE ' || 'TABLE hidden_table (id int)'; END $$;", "Dynamic EXECUTE is outside")] + [InlineData("DO $$ BEGIN EXECUTE format('%s %s', 'CREATE', 'TABLE hidden_table (id int)'); END $$;", "Unresolved dynamic EXECUTE")] + [InlineData("DO $$ BEGIN EXECUTE dynamic_sql; END $$;", "Unresolved dynamic EXECUTE")] + [InlineData("DO $$ DECLARE function text := 'CRE' || 'ATE TABLE hidden_table(id int)'; BEGIN EXECUTE function; END $$;", "Unresolved dynamic EXECUTE")] + [InlineData("DO $$ DECLARE procedure text := 'CRE' || 'ATE TABLE hidden_table(id int)'; BEGIN EXECUTE procedure; END $$;", "Unresolved dynamic EXECUTE")] + [InlineData("SELECT * INTO public.hidden_table FROM public.background_jobs;", "SELECT INTO table creation")] + [InlineData("DO $$BEGIN NULL; END$$; SELECT * INTO public.hidden_table FROM public.background_jobs;", "SELECT INTO table creation")] + [InlineData("DO $body$BEGIN NULL; END$body$; SELECT 1 INTO public.hidden_table;", "SELECT INTO table creation")] + [InlineData("DO 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE hidden_table(id int)''; END';", "Non-dollar procedural bodies")] + [InlineData("DO E'BEGIN EXECUTE ''CRE'' || ''ATE TABLE hidden_table(id int)''; END';", "Non-dollar procedural bodies")] + [InlineData("DO LANGUAGE plpgsql 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE hidden_table(id int)''; END';", "Non-dollar procedural bodies")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void LANGUAGE plpgsql AS 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.hidden_table(id int)''; END;'; SELECT public.inventory_probe();", "Non-dollar procedural bodies")] + [InlineData("CREATE OR REPLACE FUNCTION public.inventory_probe() RETURNS void AS E'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.hidden_table(id int)''; END;' LANGUAGE plpgsql; SELECT public.inventory_probe();", "Non-dollar procedural bodies")] + [InlineData("CREATE PROCEDURE public.inventory_probe() LANGUAGE plpgsql AS 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.hidden_table(id int)''; END;'; CALL public.inventory_probe();", "Non-dollar procedural bodies")] + [InlineData("CREATE OR REPLACE PROCEDURE public.inventory_probe() AS E'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.hidden_table(id int)''; END;' LANGUAGE plpgsql; CALL public.inventory_probe();", "Non-dollar procedural bodies")] + [InlineData("CREATE FUNCTION public.inventory_probe(probe text DEFAULT $$AS$$) RETURNS void LANGUAGE plpgsql AS 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.hidden_table(id int)''; END;'; SELECT public.inventory_probe();", "Non-dollar procedural bodies")] + [InlineData("CREATE FUNCTION public.inventory_probe(probe text DEFAULT $arg$)AS$arg$) RETURNS void LANGUAGE plpgsql AS 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.hidden_table(id int)''; END;'; SELECT public.inventory_probe();", "Non-dollar procedural bodies")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void SET search_path = other AS $$ BEGIN CREATE TABLE IF NOT EXISTS background_jobs(id int); END; $$ LANGUAGE plpgsql; SELECT public.inventory_probe();", "Non-pinned routine search path")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void SET search_path = pg_catalog, other AS $$ BEGIN NULL; END; $$ LANGUAGE plpgsql;", "Non-pinned routine search path")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void SET search_path FROM CURRENT AS $$ BEGIN NULL; END; $$ LANGUAGE plpgsql;", "Unresolved routine search path")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void SET search_path = \"PUBLIC\" AS $$ BEGIN NULL; END; $$ LANGUAGE plpgsql;", "Non-pinned routine search path")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void SET \"SEARCH_PATH\" = other AS $$ BEGIN NULL; END; $$ LANGUAGE plpgsql;", "Non-pinned routine search path")] + [InlineData("CREATE FUNCTION public.inventory_probe() RETURNS void AS $$ BEGIN CREATE TABLE IF NOT EXISTS background_jobs(id int); END; $$ LANGUAGE plpgsql SET search_path = other; SELECT public.inventory_probe();", "Non-pinned routine search path")] + [InlineData("CREATE TABLE IF absent_table (id int);", "Malformed table declaration.")] + [InlineData("CREATE TABLE (id int);", "Malformed table identifier.")] + [InlineData("SET search_path = other; CREATE TABLE hidden_table (id int);", "non-public search path")] + [InlineData("SET LOCAL search_path = other;", "non-public search path")] + [InlineData("SET SESSION \"search_path\" TO other;", "non-public search path")] + [InlineData("SET SESSION \"SEARCH_PATH\" TO other;", "non-public search path")] + [InlineData("SET SCHEMA 'other';", "non-public search path")] + [InlineData("DO $$ BEGIN SET LOCAL search_path = other; END $$;", "non-public search path")] + [InlineData("DO $$ BEGIN IF true THEN SET LOCAL search_path = other; END IF; END $$;", "non-public search path")] + [InlineData("DO $$ BEGIN IF false THEN NULL; ELSE SET SESSION search_path = other; END IF; END $$;", "non-public search path")] + [InlineData("SELECT set_config('search_path', 'other', true); CREATE TABLE IF NOT EXISTS background_jobs(id int);", "set_config search-path resolution")] + [InlineData("SELECT pg_catalog.\"set_config\"('search_path', 'other', true);", "set_config search-path resolution")] + [InlineData("SELECT set_config('search_' || 'path', 'other', true);", "set_config search-path resolution")] + [InlineData("SELECT set_config('SEARCH_PATH', 'other', true);", "set_config search-path resolution")] + [InlineData("DROP SCHEMA public CASCADE;", "Schema mutation")] + [InlineData("ALTER SCHEMA public RENAME TO previous;", "Schema mutation")] + [InlineData("IMPORT FOREIGN SCHEMA remote FROM SERVER probe INTO public;", "Schema mutation")] + [InlineData("CREATE TABLE previous (id int); ALTER TABLE previous SET SCHEMA other;", "Table schema moves")] + [InlineData("CREATE TABLE other.before_name(id int); ALTER TABLE other.before_name RENAME TO after_name;", "Non-public table storage")] + public void Migration_census_refuses_unsupported_ddl_for_the_expected_reason(string sql, string reason) + { + var operation = new SqlOperation { Sql = sql }; + operation["InventoryOrigin"] = "ProbeDbContext/20261025_unsupported"; + var read = () => AsyncStoreInventoryCensus.Tables([operation]); + read.Should().Throw() + .WithMessage($"ProbeDbContext/20261025_unsupported (SqlOperation): *{reason}*"); + } + + [Fact] + public void Typed_migration_operations_cannot_hide_non_public_storage_or_schema_removal() + { + var nonPublic = () => AsyncStoreInventoryCensus.Tables( + [new CreateTableOperation { Schema = "other", Name = "background_jobs" }]); + nonPublic.Should().Throw().WithMessage("*Non-public table storage*"); + var dropSchema = () => AsyncStoreInventoryCensus.Tables([new DropSchemaOperation { Name = "public" }]); + dropSchema.Should().Throw().WithMessage("*Schema mutation*"); + } + + private static string[] Check(string document, IReadOnlyList platform, + IReadOnlyList audit, IReadOnlyDictionary modules) => + AsyncStoreInventoryDocument.Check(document, platform, audit, HangfireStorageContract.Columns.Keys, modules); + + private static (string Document, MigrationOperation[] Platform, MigrationOperation[] Audit, + Dictionary Modules) Subject() + { + // Build migration services only. No design-time factory, environment credential or + // database connection is consulted; UpOperations expands the pinned installer resources. + using var platform = new PlatformDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=unused").Options); + using var audit = new AuditDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=unused").Options, new StaticTenantContextAccessor(null)); + using var tenancy = new TenancyDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=unused").Options, StaticTenantContextAccessor.Unresolved); + using var customization = new CustomizationDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=unused").Options, StaticTenantContextAccessor.Unresolved); + using var education = new EducationDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=unused").Options, StaticTenantContextAccessor.Unresolved); + var modules = new Dictionary + { + ["Tenancy"] = AsyncStoreInventoryCensus.Operations(tenancy), + ["Customization"] = AsyncStoreInventoryCensus.Operations(customization), + ["Education"] = AsyncStoreInventoryCensus.Operations(education), + }; + modules.Values.Should().OnlyContain(operations => operations.Length > 0); + var platformOperations = AsyncStoreInventoryCensus.Operations(platform); + var auditOperations = AsyncStoreInventoryCensus.Operations(audit); + platformOperations.Should().HaveCountGreaterThan(20, "the root must discover the real migration chain"); + auditOperations.Should().NotBeEmpty("audit discovery must independently reach its migration chain"); + return (File.ReadAllText(Path.Combine(RepositoryPaths.RepoRoot(), "docs", "architecture", "23-data-protection.md")), + platformOperations, auditOperations, modules); + } + + private static string[] DataLines(string document, string section) + { + var start = document.IndexOf($"", StringComparison.Ordinal); + var end = document.IndexOf($"", start, StringComparison.Ordinal); + return document[start..end].Split('\n').Where(line => line.StartsWith('|')).Skip(2).ToArray(); + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/CrossCuttingFoundationTests.cs b/backend/tests/LearnStack.Tests.Architecture/CrossCuttingFoundationTests.cs index 5187b70a7..966815a45 100644 --- a/backend/tests/LearnStack.Tests.Architecture/CrossCuttingFoundationTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/CrossCuttingFoundationTests.cs @@ -333,9 +333,12 @@ public async Task Domain_Methods_Do_Not_Throw_For_Expected_Cases() foreach (var project in AnalyzerReport.Projects()) { - WiresTheAnalyzer(File.ReadAllText(project)).Should().BeTrue( + var wiring = await AnalyzerProjectWiring.ReadAsync(project, "Release"); + wiring.HasAnalyzer(AnalyzerProjectWiring.AnalyzerPath).Should().BeTrue( $"{Path.GetFileName(project)} runs the LS0001 analyzer in its own build " + "(ADR-0032 Amendment 1), or the discipline holds only in this test"); + wiring.DomainRule.Should().BeTrue("the evaluated compiler scope must enable LS0001"); + wiring.VisibleScope.Should().BeTrue("the compiler must expose the evaluated rule scope"); runs.Add(await AnalyzerReport.RunAsync(project)); } @@ -352,39 +355,6 @@ public async Task Domain_Methods_Do_Not_Throw_For_Expected_Cases() + "it, and an unsuppressed LS0001 is a Warning nobody has justified"); } - /// - /// Whether a project references the analyzer as an analyzer, unconditionally. - /// - /// - /// Read as an element rather than as a line: the attributes may be written in either order, - /// comments are not references, and a Condition is refused outright — a conditionally - /// referenced analyzer is one that does not run in the configuration the condition excludes, - /// and this rule cannot tell which that is. The condition may sit on the reference or on - /// the ItemGroup around it, and both hide the analyzer equally well, so a - /// conditional group is removed before the references are read — and so is a - /// Choose block, whose When carries the condition and whose Otherwise - /// runs only when none matched. Both are conditions spelled differently. - /// - internal static bool WiresTheAnalyzer(string projectXml) - { - var project = Regex.Replace(projectXml, "", string.Empty, RegexOptions.Singleline); - - project = Regex.Replace( - project, - @"]*\bCondition\s*=.*?|", - string.Empty, - RegexOptions.Singleline); - - return Regex.Matches(project, @"[^>]*)/?>", RegexOptions.Singleline) - .Select(match => match.Groups["attributes"].Value) - .Where(attributes => attributes.Contains("LearnStack.Analyzers.csproj", StringComparison.Ordinal)) - .Any(attributes => - // Either quote: XML admits both, MSBuild reads both, and requiring double - // ones reported a correctly wired project as unwired. - Regex.IsMatch(attributes, @"OutputItemType\s*=\s*(?:""|')Analyzer(?:""|')") - && !Regex.IsMatch(attributes, @"\bCondition\s*=")); - } - [Fact] public async Task The_Domain_Exception_Report_Can_Actually_Fail() { @@ -464,28 +434,7 @@ public static Outcome Value() "the invariant guard is the sanctioned suppression, and it is the only one — an " + "aliased Result returns through the same channel as one spelled out"); - // And the wiring check reads an element rather than a line: either attribute order, no - // comment, and no condition. - const string Reference = """""").Should().BeTrue(); - WiresTheAnalyzer("""""") - .Should().BeTrue("the attributes may be written in either order"); - WiresTheAnalyzer("""""") - .Should().BeTrue("and in either quote, which is XML's rule and not ours"); - WiresTheAnalyzer(Reference + """/>""").Should().BeFalse("a plain reference is not an analyzer"); - WiresTheAnalyzer("""""") - .Should().BeFalse("a conditional analyzer does not run in the configuration the condition excludes"); - WiresTheAnalyzer("""") - .Should().BeFalse("a commented-out reference is not a reference"); - WiresTheAnalyzer( - """""" + Reference - + """OutputItemType="Analyzer" />""") - .Should().BeFalse("a condition on the group hides the analyzer exactly as well"); - WiresTheAnalyzer( - """""" + Reference - + """OutputItemType="Analyzer" />""") - .Should().BeFalse("and so does a Choose/When, which is a condition spelled differently"); + } [Fact] diff --git a/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.SourceCensus.cs b/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.SourceCensus.cs index 21e868369..469dec355 100644 --- a/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.SourceCensus.cs +++ b/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.SourceCensus.cs @@ -94,7 +94,7 @@ private static void RequireProductionProjectCoverage(IEnumerable project { "AnalysisLevel", "AnalysisMode", "AssemblyName", "EnforceCodeStyleInBuild", "EnforceExtendedAnalyzerRules", "GenerateDocumentationFile", "ImplicitUsings", "IsPackable", - "LangVersion", "ManagePackageVersionsCentrally", "NoWarn", "NuGetAuditLevel", "NuGetAuditMode", + "LangVersion", "LearnStackAnalyzeDomainExceptionThrow", "ManagePackageVersionsCentrally", "NoWarn", "NuGetAuditLevel", "NuGetAuditMode", "Nullable", "OutputType", "RootNamespace", "TargetFramework", "TreatWarningsAsErrors", "UserSecretsId", "WarningsNotAsErrors" }; diff --git a/backend/tests/LearnStack.Tests.Architecture/SensitiveExceptionMessageTests.cs b/backend/tests/LearnStack.Tests.Architecture/SensitiveExceptionMessageTests.cs new file mode 100644 index 000000000..a75546940 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/SensitiveExceptionMessageTests.cs @@ -0,0 +1,58 @@ +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// Production regression controls for ADR-0032 Amendment 6's bounded LS0002 rule. +public sealed class SensitiveExceptionMessageTests +{ + [Theory] + [InlineData("Debug")] + [InlineData("Release")] + public async Task Production_Exception_Messages_Do_Not_Contain_Sensitive_References(string configuration) + { + var projects = Directory.GetFiles(RepositoryPaths.BackendSrc(), "*.csproj", SearchOption.AllDirectories); + projects.Should().NotBeEmpty("the production corpus must be discovered"); + var findings = new List(); + foreach (var project in projects.Order(StringComparer.Ordinal)) + { + var reports = await AnalyzerReport.SensitiveAsync(project, configuration); + findings.AddRange(reports.Select(report => Path.GetFileName(project) + ": " + report)); + } + + findings.Should().BeEmpty( + "Fix: replace sensitive constructor strings with fixed messages; suppressing LS0002 does not remove the value"); + } + + [Theory] + [InlineData("Debug", "DEBUG")] + [InlineData("Release", "NETCOREAPP")] + public async Task The_Sensitive_Report_Sees_Suppressed_And_Conditional_Violations(string configuration, string symbol) + { + var source = $$""" + namespace AnalyzerProof; + internal static class Probe + { + internal static void Direct(string accessToken) => throw new System.Exception(accessToken); + internal static void Silenced(string accessToken) + { + #pragma warning disable LS0002 + throw new System.Exception(accessToken); + #pragma warning restore LS0002 + } + #if {{symbol}} + internal static void Conditional(string accessToken) => throw new System.Exception($"{accessToken}"); + #endif + internal static void Clean(string className) => throw new System.Exception(className); + internal static System.Exception Factory(string accessToken) => new System.Exception(accessToken); + } + """; + var project = Path.Combine(RepositoryPaths.BackendSrc(), "LearnStack.Api", "LearnStack.Api.csproj"); + var findings = (await AnalyzerReport.SensitiveAsync(project, configuration, source)) + .Where(finding => Path.GetFileName(finding.File) == "Planted0.cs").ToArray(); + + findings.Select(finding => finding.Member).Should().BeEquivalentTo(["Direct", "Silenced", "Conditional"]); + findings.Single(finding => finding.Member == "Silenced").Suppressed.Should().BeTrue(); + } + +} diff --git a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs index 92e9cfd9c..6cd9f07de 100644 --- a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs @@ -9,6 +9,7 @@ using LearnStack.Infrastructure.Messaging; using LearnStack.Infrastructure.Persistence; using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Hosting; using LearnStack.Tests.Integration.Database; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -30,6 +31,26 @@ public sealed class BackgroundJobProductionManifestTests [Fact] public async Task BackgroundJob_Runtime_Has_No_Production_Definitions_Or_Dashboard() { + // ASPNETCORE_ENVIRONMENT remains Development to avoid production adapters; + // the independently selected Deployment:Mode still reaches Program's early + // composition branch. Route absence must hold for every declared mode. + foreach (var mode in Enum.GetNames()) + { + await using var modeFactory = new ManifestFactory(mode: mode); + var modeServices = modeFactory.Services; + try + { + modeServices.GetRequiredService()["Deployment:Mode"].Should().Be(mode); + AssertRoot(modeServices, modeFactory.ProductionDescriptors); + ManifestOffenders(modeServices).Should().BeEmpty(); + AssertRoutes(modeServices); + using var client = modeFactory.CreateClient(); + using var response = await client.GetAsync("/admin/hangfire"); + response.StatusCode.Should().Be(System.Net.HttpStatusCode.NotFound); + } + finally { await CompleteUnstartedOwnersAsync(modeServices); } + } + await using var factory = new ManifestFactory(); var services = factory.Services; try @@ -205,12 +226,20 @@ private static async Task CompleteUnstartedOwnersAsync(IServiceProvider services await services.GetRequiredService().Completion.WaitAsync(TimeSpan.FromSeconds(5)); } - private sealed class ManifestFactory(Action? configure = null) : ConstructionOnlyApiFactory + private sealed class ManifestFactory(Action? configure = null, + string mode = nameof(DeploymentMode.Development)) : ConstructionOnlyApiFactory { + private readonly string _errorDirectory = Path.Combine(Path.GetTempPath(), "learnstack-manifest-" + Guid.NewGuid().ToString("N")); internal ServiceDescriptor[] ProductionDescriptors { get; private set; } = []; protected override void ConfigureTestHost(IWebHostBuilder builder) { builder.UseEnvironment(Environments.Development); + // UseSetting is required before Program reads the minimal-host builder; + // deferred ConfigureAppConfiguration is too late for deployment selection. + builder.UseSetting("Deployment:Mode", mode); + builder.UseSetting("ErrorTracking:Sentry:Dsn", "https://0123456789abcdef@example.invalid/1"); + builder.UseSetting("Authentication:Tenant:Issuer", "https://issuer.invalid/realms/learnstack"); + builder.UseSetting("ErrorTracking:LocalFile:Directory", _errorDirectory); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(new Dictionary { ["ConnectionStrings:Default"] = "Host=localhost;Port=1;Database=learnstack;Username=learnstack_app;Maximum Pool Size=32", @@ -222,6 +251,12 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) ProductionDescriptors = collection.ToArray(); }); } + + public override async ValueTask DisposeAsync() + { + await base.DisposeAsync(); + if (Directory.Exists(_errorDirectory)) Directory.Delete(_errorDirectory, recursive: true); + } } private sealed class ExtraEndpoint(string path) : IStartupFilter diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditCaptureWiringTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditCaptureWiringTests.cs index b51f7b293..4999af7bb 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/AuditCaptureWiringTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditCaptureWiringTests.cs @@ -204,6 +204,22 @@ public async Task The_real_composition_root_keeps_the_audit_interceptor_behind_a scope.ServiceProvider.GetServices() .Should().ContainSingle(interceptor => interceptor is AuditChangeTrackerInterceptor, "the audit capture survives a second interceptor registered ahead of it"); + + var capture = scope.ServiceProvider.GetRequiredService(); + scope.ServiceProvider.GetRequiredService().Should().BeSameAs(capture); + scope.ServiceProvider.GetRequiredService().Should().BeSameAs(capture, + "designation and EF capture must address the same real scoped buffer"); + capture.OpenFrame(); + capture.HasOpenFrame.Should().BeTrue(); + + await using var other = provider.CreateAsyncScope(); + var otherCapture = other.ServiceProvider.GetRequiredService(); + other.ServiceProvider.GetRequiredService().Should().BeSameAs(otherCapture); + other.ServiceProvider.GetRequiredService().Should().BeSameAs(otherCapture); + otherCapture.Should().NotBeSameAs(capture, "a second execution needs its own capture"); + otherCapture.HasOpenFrame.Should().BeFalse("one scope cannot inherit another scope's audit owner"); + capture.HasOpenFrame.Should().BeTrue("resolving another scope cannot close the first owner's frame"); + capture.CloseFrame(AuditIntentResult.Succeeded); } /// An interceptor that does nothing, registered only to get in the way. diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs index 4f6cf60ee..73702fa79 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.Business.cs @@ -1,10 +1,14 @@ +using System.Collections.Concurrent; using System.Diagnostics; using FluentAssertions; using LearnStack.Infrastructure.Jobs; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; using MediatR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -38,17 +42,28 @@ await SchemaQueries.ExecuteAsync(owner, setup, """ // still runs as learnstack_app with its real MUST writer available. await SchemaQueries.ExecuteAsync(owner, null, "REVOKE INSERT ON audit_log FROM learnstack_outbox_admin"); } - var organizations = new List(); + var bodyEntries = new ConcurrentDictionary(); + var controlledRefusals = new ConcurrentDictionary(); var probe = new BackgroundJobFixtureProbe { Body = async (request, services, token) => { request.Should().Be("TenantRoot"); - var organization = Guid.CreateVersion7(); - organizations.Add(organization); + var context = services.GetRequiredService().Should().BeOfType().Subject; + var job = context.JobId ?? throw new InvalidOperationException("The actual business job identity is missing."); + var organization = job.Value; + var entries = bodyEntries.AddOrUpdate(job.Value, 1, (_, previous) => previous + 1); + if (entries > 1) + (await BackgroundJobRuntimeRows.CountOrganizationAsync(database.AppConnectionString, organization)).Should().Be(0, + "a new attempt must not see its predecessor's rolled-back business write"); var written = await services.GetRequiredService().Send(new CreateOrganizationCommand( OrganizationId.From(organization), "job-fair-" + organization.ToString("N")[..12], "Job fairness"), token); written.IsSuccess.Should().BeTrue(); + // The real nested write succeeds before this one controlled refusal. + // Handler entries include rolled-back attempts; the logical job's + // stable organization and successful MUST audit witness its effect. + if (controlledRefusals.TryAdd(job.Value, 0)) + return Result.Fail(new Error(LocalizedMessage.Of("lockey_dependency_unavailable"))); return Result.Ok(None.Value); }, }; @@ -70,14 +85,14 @@ await SchemaQueries.ExecuteAsync(owner, setup, """ var firstFailure = await TerminalBacklogAsync(database); var elapsed = Stopwatch.StartNew(); var first = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); - await EventuallyQualificationAsync(async () => (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, first))!.Phase == "completed", deadline.Token); + await EnsureQualificationCompletionAsync(runtime, source, first, deadline.Token); // A one-row or sub-lease happy case cannot expose priority starvation. // Keep the real permission fault and all 100 records for two full // leases, then demand another actual native business completion. await Task.Delay(bounds.LeaseDuration + bounds.LeaseDuration + TimeSpan.FromSeconds(1), deadline.Token); var second = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); - await EventuallyQualificationAsync(async () => (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, second))!.Phase == "completed", deadline.Token); + await EnsureQualificationCompletionAsync(runtime, source, second, deadline.Token); elapsed.Elapsed.Should().BeGreaterThan(bounds.LeaseDuration + bounds.LeaseDuration); var after = await TerminalBacklogAsync(database); after.Total.Should().Be(100); @@ -86,11 +101,20 @@ await SchemaQueries.ExecuteAsync(owner, setup, """ after.LatestBackoff.Should().BeAfter(firstFailure.LatestBackoff + bounds.LeaseDuration, "actual terminal retries and their audit failure continued during healthy work"); after.AuditPermitted.Should().BeFalse(); - organizations.Should().HaveCount(2); - foreach (var organization in organizations) - (await BackgroundJobRuntimeRows.CountOrganizationAsync(database.AppConnectionString, organization)).Should().Be(1); + bodyEntries.Keys.Should().BeEquivalentTo([first.Value, second.Value]); + controlledRefusals.Keys.Should().BeEquivalentTo([first.Value, second.Value]); foreach (var job in new[] { first, second }) - (await BackgroundJobRuntimeRows.CountAttemptsAsync(database.AppConnectionString, job)).Should().Be(1); + { + (await BackgroundJobRuntimeRows.CountOrganizationAsync(database.AppConnectionString, job.Value)).Should().Be(1); + (await SuccessfulBacklogBusinessAuditsAsync(database, job)).Should().Be(1); + var completed = (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, job))!; + completed.Phase.Should().Be("completed"); + completed.NormalAttempts.Should().BeInRange(2, BackgroundJobRuntimeOptions.MaxNormalAttempts); + (await BackgroundJobRuntimeRows.CountAttemptsAsync(database.AppConnectionString, job)).Should().Be(completed.NormalAttempts, + "the durable attempt ledger and completed job summary must agree"); + bodyEntries[job.Value].Should().BeInRange(2, completed.NormalAttempts, + "each job retries its controlled rollback, and every body entry needs a committed admission"); + } await AssertGuardedPoolAsync(source, physical); } finally @@ -105,6 +129,20 @@ await SchemaQueries.ExecuteAsync(owner, setup, """ } } + private static async Task SuccessfulBacklogBusinessAuditsAsync(DisposableSchemaDatabase database, BackgroundJobId job) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await EducationSchemaSeed.AnnounceAsync(connection, transaction, SchemaFixture.TenantA, null); + await using var command = new NpgsqlCommand(""" + SELECT count(*) FROM audit_log + WHERE entity_id=@id AND operation='tenancy.organization.create' AND operation_class='Must' + AND outcome='success' AND metadata->>'job_id'=@id + """, connection, transaction); + command.Parameters.AddWithValue("id", job.Value.ToString()); + return (long)(await command.ExecuteScalarAsync())!; + } + [Fact] public async Task Admitted_native_business_renews_across_local_drain_and_commits_after_two_initial_leases() { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HandoffQualification.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HandoffQualification.cs index 58417aeb1..449beb010 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HandoffQualification.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HandoffQualification.cs @@ -1,8 +1,14 @@ using FluentAssertions; using LearnStack.Infrastructure.Jobs; using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; +using Microsoft.Extensions.DependencyInjection; using Npgsql; using Xunit; @@ -56,10 +62,12 @@ await EventuallyQualificationAsync(() => Task.FromResult(runtime.Snapshot.IsHeal (await VendorAsync(source, job)).Should().Be(skipped); (await bridge.TryClaimAsync([], deadline.Token)).Should().BeNull("the accepted repair grace is still live"); - var resent = await EnsureQualificationStartAsync(runtime, source, job, entered.Task, deadline.Token); - resent.Should().NotBeNull().And.NotBe(skipped); + var hints = await EnsureQualificationCompletionAsync(runtime, source, job, deadline.Token); + hints.Should().ContainSingle().Which.Generation.Should().Be(1); + var resent = hints[0].Vendor; + resent.Should().NotBe(skipped); await entered.Task.WaitAsync(deadline.Token); - await EventuallyQualificationAsync(async () => await StateAsync(source, resent!) == "Succeeded", deadline.Token); + await EventuallyQualificationAsync(async () => await StateAsync(source, resent) == "Succeeded", deadline.Token); while (runtime.Snapshot.Control is not { Executions: 0, PendingOutcomes: 0 }) { time.Advance(bounds.ControlPoll); @@ -78,6 +86,157 @@ await EventuallyQualificationAsync(() => Task.FromResult(runtime.Snapshot.IsHeal } } + [Fact] + public async Task Native_completion_qualification_resends_the_locked_retry_generation_after_actual_rollback() + { + await using var database = await DatabaseAsync(); + var calls = 0; + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var probe = new BackgroundJobFixtureProbe + { + Body = async (_, services, token) => + { + var context = services.GetRequiredService().Should().BeOfType().Subject; + var job = context.JobId ?? throw new InvalidOperationException("The actual business job identity is missing."); + var entry = Interlocked.Increment(ref calls); + entered.TrySetResult(); + (await BackgroundJobRuntimeRows.CountOrganizationAsync(database.AppConnectionString, job.Value)).Should().Be(0); + var written = await services.GetRequiredService().Send(new CreateOrganizationCommand( + OrganizationId.From(job.Value), "job-handoff-" + job.Value.ToString("N")[..12], "Job handoff"), token); + written.IsSuccess.Should().BeTrue(); + return entry == 1 + ? Result.Fail(new Error(LocalizedMessage.Of("lockey_dependency_unavailable"))) + : Result.Ok(None.Value); + }, + }; + await using var host = Fixture.Host(database, probe); + await using var source = Source(database); + using var globals = new GlobalFilterSnapshot(); + using var deadline = new CancellationTokenSource(TestWait); + var time = new HangfirePoolOwnerTests.ManualTimeProvider(); + var bounds = NativeCommitFaultBounds(); + var runtime = Runtime(host.Services, source, bounds, timeProvider: time); + await using var locker = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.OutboxConnectionString); + NpgsqlTransaction? held = null; + SemaphoreSlim? bridgeQuantum = null; + var quantumHeld = false; + try + { + await runtime.StartAsync(deadline.Token); + await EventuallyQualificationAsync(() => Task.FromResult(runtime.Snapshot.IsHealthy + && time.DelayCount(bounds.ControlPoll) == 3), deadline.Token); + // This fixture qualifies native handoff, not bridge fairness. Hold + // automatic bridge issuance while real control polling creates the + // retry; the explicit store still commits each genuine bridge ACK. + var actualBridge = (BackgroundJobBridge)typeof(BackgroundJobRuntime).GetField("_bridge", PrivateInstance)!.GetValue(runtime)!; + bridgeQuantum = (SemaphoreSlim)typeof(BackgroundJobBridge).GetField("_quantum", PrivateInstance)!.GetValue(actualBridge)!; + await bridgeQuantum.WaitAsync(deadline.Token); + quantumHeld = true; + var job = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString); + var bridge = new PostgresBackgroundJobBridgeStore(source, Fixture.Registry, bounds, new SystemGuidFactory()); + var initial = (await bridge.TryClaimAsync([], deadline.Token))!; + initial.WakeGeneration.Should().Be(1); + var original = CreateQualificationWakeup(ActualProvider(runtime), Fixture.Registry.Infrastructure.Pools["transactional"], job); + await entered.Task.WaitAsync(deadline.Token); + (await bridge.AcknowledgeAsync(initial, original, deadline.Token)).Should().BeTrue(); + await EventuallyQualificationAsync(async () => + { + time.Advance(bounds.ControlPoll); + return (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, job)) is { Phase: "pending", NormalAttempts: 1 } + && runtime.Snapshot.Control is { Executions: 0, PendingOutcomes: 0 }; + }, deadline.Token); + await EventuallyQualificationAsync(async () => await StateAsync(source, original) == "Succeeded" + && QualificationPoolOwners(runtime)["transactional"].Snapshot.Work is { Running: 0, Retained: 0, Closed: false } + && (await ReadQualificationHandoffAsync(source, job, deadline.Token)).Eligible, deadline.Token); + (await BackgroundJobRuntimeRows.CountOrganizationAsync(database.AppConnectionString, job.Value)).Should().Be(0, + "the first genuine business write rolled back before control created its retry"); + + var retry = (await bridge.TryClaimAsync([], deadline.Token))!; + retry.WakeGeneration.Should().Be(2, "only the real rollback control transition creates this eligibility cycle"); + held = await locker.BeginTransactionAsync(deadline.Token); + await LockNativeJobAsync(locker, held, job, deadline.Token); + var skipped = CreateQualificationWakeup(ActualProvider(runtime), Fixture.Registry.Infrastructure.Pools["transactional"], job, + retry.WakeGeneration); + await EventuallyQualificationAsync(async () => await StateAsync(source, skipped) == "Succeeded", deadline.Token); + calls.Should().Be(1, "the current-generation stock hint skipped the actual row lock"); + (await BackgroundJobRuntimeRows.CountAttemptsAsync(database.AppConnectionString, job)).Should().Be(1); + await held.RollbackAsync(deadline.Token); + await held.DisposeAsync(); + held = null; + (await bridge.AcknowledgeAsync(retry, skipped, deadline.Token)).Should().BeTrue(); + (await bridge.TryClaimAsync([], deadline.Token)).Should().BeNull("the acknowledged retry hint still has its full repair grace"); + + var hints = await EnsureQualificationCompletionAsync(runtime, source, job, deadline.Token); + hints.Should().ContainSingle().Which.Generation.Should().Be(2); + await EventuallyQualificationAsync(async () => await StateAsync(source, hints[0].Vendor) == "Succeeded", deadline.Token); + calls.Should().Be(2); + (await BackgroundJobRuntimeRows.ReadAsync(database.AppConnectionString, job)).Should().Match( + row => row.Phase == "completed" && row.NormalAttempts == 2); + (await BackgroundJobRuntimeRows.CountAttemptsAsync(database.AppConnectionString, job)).Should().Be(2); + (await BackgroundJobRuntimeRows.CountOrganizationAsync(database.AppConnectionString, job.Value)).Should().Be(1); + (await SuccessfulBacklogBusinessAuditsAsync(database, job)).Should().Be(1); + } + finally + { + if (held is not null) { await held.RollbackAsync(); await held.DisposeAsync(); } + if (quantumHeld) bridgeQuantum!.Release(); + using var cleanup = new CancellationTokenSource(TestWait); + await runtime.StopAsync(cleanup.Token); + await runtime.Completion.WaitAsync(cleanup.Token); + await DisposePinnedSourceAsync(source); + } + } + + private static async Task> EnsureQualificationCompletionAsync( + BackgroundJobRuntime runtime, PrivilegedDataSource source, BackgroundJobId job, CancellationToken cancellationToken) + { + // Completion fixtures do not measure repair grace. A successfully + // consumed hint may have skipped ACK's row lock or old local cleanup. + // Require the real bridge and native worker first, then supplement at + // most once for each control-created generation, including retries. + var hints = new List<(long Generation, string Vendor)>(); + var control = (BackgroundJobControl)typeof(BackgroundJobRuntime).GetField("_jobs", PrivateInstance)!.GetValue(runtime)!; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + var row = await ReadQualificationHandoffAsync(source, job, cancellationToken); + if (row.Phase == "completed") return hints.AsReadOnly(); + if (row.Eligible && row.Vendor is { } vendor && hints.All(hint => hint.Generation != row.Generation) + && await StateAsync(source, vendor) == "Succeeded" + && QualificationPoolOwners(runtime)["transactional"].Snapshot is + { State: HangfirePoolOwnerState.Running, Work: { Running: 0, Retained: 0, Closed: false } } + && control.CanRoute(job)) + { + hints.Count.Should().BeLessThan(BackgroundJobRuntimeOptions.MaxNormalAttempts, + "fixture hints never create an unbounded retry policy"); + cancellationToken.ThrowIfCancellationRequested(); + hints.Add((row.Generation, CreateQualificationWakeup(ActualProvider(runtime), + Fixture.Registry.Infrastructure.Pools["transactional"], job, row.Generation))); + } + await Task.Delay(TimeSpan.FromMilliseconds(25), cancellationToken); + } + } + + private static async Task ReadQualificationHandoffAsync(PrivilegedDataSource source, + BackgroundJobId job, CancellationToken cancellationToken) + { + await using var connection = await source.OpenConnectionAsync(cancellationToken); + await using var command = new NpgsqlCommand(""" + SELECT phase, wake_generation, vendor_job_id, + phase='pending' AND profile='transactional' AND normal_attempts<6 + AND ownership_token IS NULL AND bridge_token IS NULL + AND processed_at IS NULL AND dead_lettered_at IS NULL AND terminal_reason IS NULL + AND available_after <= clock_timestamp() AND original_due_at <= clock_timestamp() + FROM background_jobs WHERE id=@id + """, connection) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("id", job.Value); + await using var row = await command.ExecuteReaderAsync(cancellationToken); + (await row.ReadAsync(cancellationToken)).Should().BeTrue(); + return new(row.GetString(0), row.GetInt64(1), row.IsDBNull(2) ? null : row.GetString(2), row.GetBoolean(3)); + } + + private sealed record QualificationHandoff(string Phase, long Generation, string? Vendor, bool Eligible); + private static async Task EnsureQualificationStartAsync(BackgroundJobRuntime runtime, PrivilegedDataSource source, LearnStack.SharedKernel.Jobs.BackgroundJobId job, Task started, CancellationToken cancellationToken = default) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs index 3374eea1a..3ee6f5af5 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.HeartbeatCutoff.cs @@ -341,7 +341,8 @@ private static async Task LockQualificationServerAsync(NpgsqlConnection connecti (await command.ExecuteScalarAsync(cancellationToken)).Should().Be(server); } - private static string CreateQualificationWakeup(PostgreSqlStorage provider, BackgroundJobWorkerPoolRegistration pool, BackgroundJobId id) + private static string CreateQualificationWakeup(PostgreSqlStorage provider, BackgroundJobWorkerPoolRegistration pool, BackgroundJobId id, + long generation = 1) { var culture = CultureInfo.CurrentCulture; var uiCulture = CultureInfo.CurrentUICulture; @@ -349,7 +350,7 @@ private static string CreateQualificationWakeup(PostgreSqlStorage provider, Back { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; - var job = new Job(typeof(HangfireJobWakeup), HangfireInvocationContract.JobMethod, [id, 1L], pool.Queues[0]); + var job = new Job(typeof(HangfireJobWakeup), HangfireInvocationContract.JobMethod, [id, generation], pool.Queues[0]); return new BackgroundJobClient(provider, HangfireRuntimeFilters.Create()) { RetryAttempts = 0 } .Create(job, new EnqueuedState(pool.Queues[0])) ?? throw new InvalidOperationException("The real qualification wakeup was not created."); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryExecutionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryExecutionTests.cs index 8472b569c..b63a88097 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryExecutionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryExecutionTests.cs @@ -71,6 +71,7 @@ public async Task Integration_Event_Handler_Restores_Tenant_Context() var result = await fixture.Executor.ExecuteAsync(claim, gate, cancellation.Token); result.Should().Be(new DeliveryExecutionResult(DeliveryExecutionOutcome.Completed, true, false)); + AssertCaptureCleared(fixture.Observation.Captures.Should().ContainSingle().Subject); gate.CommitAcknowledged.Should().BeTrue(); fixture.Observation.Constructions.Should().Be(1); fixture.Observation.Executions.Should().Be(1); @@ -84,6 +85,7 @@ public async Task Integration_Event_Handler_Restores_Tenant_Context() state.Inbox.Should().Be(1); state.Outbox.Should().Be(1); state.SuccessAudit.Should().Be(1); + state.IndeterminateAudit.Should().Be(0, "an acknowledged commit has no indeterminate reconcile row"); state.Processed.Should().BeTrue(); state.OutboxCausation.Should().Be(fact.EventId); state.OutboxActor.Should().Be(CausalActor); @@ -173,6 +175,8 @@ public async Task Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_sc result.CommitAcknowledged.Should().BeFalse(); result.Outcome.Should().Be(DeliveryExecutionOutcome.Failed); + var firstCapture = fixture.Observation.Captures.Should().ContainSingle().Subject; + AssertCaptureCleared(firstCapture); fixture.Accessor.Current.Should().BeSameAs(previous); fixture.Logs.Text.Should().NotContain(SensitiveCanary).And.NotContain(PayloadCanary.ToString()).And.NotContain(typeof(Handler).FullName!); (await fixture.StateAsync(fact)).Should().Match(state => @@ -188,6 +192,10 @@ public async Task Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_sc var retry = await fixture.Executor.ExecuteAsync(claim, new DeliveryCommitGate()); retry.Outcome.Should().Be(DeliveryExecutionOutcome.Completed); retry.CommitAcknowledged.Should().BeTrue(); + fixture.Observation.Captures.Should().HaveCount(2); + var retryCapture = fixture.Observation.Captures.Last(); + retryCapture.Should().NotBeSameAs(firstCapture, "a retry owns a fresh DI scope"); + AssertCaptureCleared(retryCapture); (await fixture.StateAsync(fact)).Business.Should().Be(1); fixture.Accessor.Current.Should().BeSameAs(previous); fixture.Accessor.Current = null; @@ -403,15 +411,19 @@ public async Task Lost_COMMIT_acknowledgement_retains_atomic_completion_and_neve gate.CommitStarted.Should().BeTrue(); proxy.DroppedCommitResponses.Should().Be(1); uncertain.Observation.ObservedSavedWork.Should().BeTrue(); + AssertCaptureCleared(uncertain.Observation.Captures.Should().ContainSingle().Subject); var state = await fixture.StateAsync(fact); state.Business.Should().Be(1); state.Inbox.Should().Be(1); state.Outbox.Should().Be(1); state.SuccessAudit.Should().Be(1); + state.IndeterminateAudit.Should().Be(1); state.Processed.Should().BeTrue(); var retry = await fixture.Executor.ExecuteAsync(claim, new DeliveryCommitGate()); retry.Outcome.Should().Be(DeliveryExecutionOutcome.LostClaim); + fixture.Observation.Captures.Should().BeEmpty( + "durable completion refuses the retry before another business audit frame opens"); fixture.Observation.Constructions.Should().Be(0, "durable completion excludes every subsequent execution"); (await fixture.StateAsync(fact)).Should().BeEquivalentTo(state); uncertain.Logs.Text.Should().NotContain(SensitiveCanary).And.NotContain(PayloadCanary.ToString()); @@ -672,7 +684,13 @@ public Handler(IServiceProvider services, Observation observation) inbox.ExecuteScalar().Should().Be(1L, "the transport claimed inbox before entering the business constructor"); observation.InboxObservedAtConstruction = true; } - services.GetRequiredService().HasOpenFrame.Should().BeTrue(); + var capture = services.GetRequiredService(); + services.GetRequiredService().Should().BeSameAs(capture); + services.GetRequiredService().Should().BeSameAs(capture); + capture.HasOpenFrame.Should().BeTrue(); + capture.Intents.Should().ContainSingle(intent => intent.Operation == Operation, + "the actual delivery audit frame declared its intent before handler construction"); + observation.Captures.Enqueue(capture); services.GetRequiredService().RequireAnnouncement().TenantId.Value.Should().Be(SchemaFixture.TenantA); if (observation.Fault == "constructor") throw new InvalidOperationException(SensitiveCanary); } @@ -695,6 +713,7 @@ private async Task WorkAsync(ProofEvent fact, CancellationToken cancellationToke LocalizedText.From(("en", "Delivery execution proof")), """{"type":"object"}""", "default-card", _services.GetRequiredService(), UserId.SystemActor); _observation.Source = source; + _services.GetRequiredService().Designate(source); if (_observation.EmitDomainEvent) { typeof(Entity).GetMethod("RaiseDomainEvent", BindingFlags.Instance | BindingFlags.NonPublic)! @@ -705,6 +724,12 @@ private async Task WorkAsync(ProofEvent fact, CancellationToken cancellationToke } db.Add(source); await db.SaveChangesAsync(cancellationToken); + var capture = _services.GetRequiredService(); + var intent = capture.Intents.Single(intent => intent.Operation == Operation); + intent.SubjectId.Should().Be(fact.SubjectId.ToString()); + capture.ChangesOf(intent).Should().Contain(change => + change.EntityType == nameof(TenantContentType) && change.EntityId == fact.SubjectId.ToString(), + "the real module interceptor filled the same capture and frame the delivery owner reconciles"); _observation.OutgoingActivity = Activity.Current?.Id; _observation.OutgoingAnnouncement = unit.GetTenantContextAnnouncement(unit.Transaction); await _services.GetRequiredService().EnqueueAsync(fact with { EventId = Guid.CreateVersion7() }, cancellationToken); @@ -745,6 +770,7 @@ private static void AssertContext(IServiceProvider services) public sealed class Observation { public int Constructions { get; set; } + public ConcurrentQueue Captures { get; } = new(); public bool InboxObservedAtConstruction { get; set; } public bool ObserveBareUnit { get; set; } public bool BareUnitObserved { get; set; } @@ -855,6 +881,15 @@ public void Describe(IAuditCatalogBuilder builder) => builder.MustAudit(Operation, OperationType.Create, typeof(TenantContentType)); } + private static void AssertCaptureCleared(AuditStateCapture capture) + { + capture.State.Should().Be(AuditIntentState.None); + capture.Intents.Should().BeEmpty(); + capture.Changes.Should().BeEmpty(); + capture.HasOpenFrame.Should().BeFalse(); + capture.IndeterminateCause.Should().BeNull(); + } + private sealed class ProbeContext(Guid tenant, Guid? organization) : ITenantContext { public bool IsResolved => true; @@ -869,7 +904,7 @@ private sealed record DurableState(long Business, long Inbox, long Outbox, long bool Processed, Guid? OutboxCausation, Guid? OutboxActor, Guid? AuditActor, string? AuditCorrelation, Guid? AuditOrganization, string? LockedBy, Guid? AuditCausation, Guid? AuditCausalActor, string? OutboxCorrelation, - Guid? OutboxTenant, Guid? OutboxOrganization, string? OutboxPartition); + Guid? OutboxTenant, Guid? OutboxOrganization, string? OutboxPartition, long IndeterminateAudit); private sealed class Fixture : IAsyncDisposable { @@ -1117,7 +1152,9 @@ public async Task StateAsync(ProofEvent fact, string subscription (SELECT correlation_id FROM outbox_messages WHERE payload ->> 'SubjectId' = @subject_text LIMIT 1), (SELECT tenant_id FROM outbox_messages WHERE payload ->> 'SubjectId' = @subject_text LIMIT 1), (SELECT organization_id FROM outbox_messages WHERE payload ->> 'SubjectId' = @subject_text LIMIT 1), - (SELECT partition_key FROM outbox_messages WHERE payload ->> 'SubjectId' = @subject_text LIMIT 1) + (SELECT partition_key FROM outbox_messages WHERE payload ->> 'SubjectId' = @subject_text LIMIT 1), + (SELECT count(*) FROM audit_log WHERE operation = @operation AND outcome = 'indeterminate' + AND entity_id = @subject_text AND (metadata ->> 'causation_id')::uuid = @event) """, connection, transaction); command.Parameters.AddWithValue("subject", fact.SubjectId); command.Parameters.AddWithValue("subject_text", fact.SubjectId.ToString()); @@ -1133,7 +1170,7 @@ public async Task StateAsync(ProofEvent fact, string subscription read.IsDBNull(10) ? null : read.GetString(10), read.IsDBNull(11) ? null : read.GetGuid(11), read.IsDBNull(12) ? null : read.GetGuid(12), read.IsDBNull(13) ? null : read.GetString(13), read.IsDBNull(14) ? null : read.GetGuid(14), read.IsDBNull(15) ? null : read.GetGuid(15), - read.IsDBNull(16) ? null : read.GetString(16)); + read.IsDBNull(16) ? null : read.GetString(16), read.GetInt64(17)); } public async ValueTask DisposeAsync() { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs b/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs index c4b2a31e8..6c0705d21 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs @@ -33,12 +33,15 @@ internal static class SchemaTableClasses public static readonly string[] Data = [.. Existing, .. JobTenant, .. Control, .. Vendor]; public static bool AppSelectDenied(string table) => Control.Contains(table) || Vendor.Contains(table); - public static async Task AssertCompleteAsync(DbConnection connection, DbTransaction? transaction = null) - { - var discovered = await SchemaQueries.ReadStringsAsync(connection, """ + internal static Task> ReadAsync(DbConnection connection, DbTransaction? transaction = null) => + SchemaQueries.ReadStringsAsync(connection, """ SELECT relname FROM pg_class - WHERE relnamespace = 'public'::regnamespace AND relkind = 'r' ORDER BY relname + WHERE relnamespace = 'public'::regnamespace AND relkind IN ('r', 'p', 'm') ORDER BY relname """, transaction); + + public static async Task AssertCompleteAsync(DbConnection connection, DbTransaction? transaction = null) + { + var discovered = await ReadAsync(connection, transaction); discovered.Should().BeEquivalentTo(Data.Concat(MigrationChains.HistoryTables), "every public table must have an exact reviewed class, including the five history tables; " + "Fix: classify a new table under Standards 05 rather than excluding it from discovery"); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/StorageRelationCensusTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/StorageRelationCensusTests.cs new file mode 100644 index 000000000..a54815c94 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/StorageRelationCensusTests.cs @@ -0,0 +1,33 @@ +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// Catalogue discovery controls; no application migrations or isolation claim. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class StorageRelationCensusTests : IClassFixture +{ + private readonly PostgresFixture _postgres; + + public StorageRelationCensusTests(PostgresFixture postgres) => _postgres = postgres; + + [Theory] + [InlineData("CREATE TABLE census_probe (id integer)", "DROP TABLE census_probe")] + [InlineData("SET LOCAL \"SEARCH_PATH\" TO public; CREATE TABLE census_probe (id integer)", "DROP TABLE census_probe")] + [InlineData("CREATE TABLE census_probe (id integer) PARTITION BY RANGE (id)", "DROP TABLE census_probe")] + [InlineData("CREATE MATERIALIZED VIEW census_probe AS SELECT 1 AS id", "DROP MATERIALIZED VIEW census_probe")] + [InlineData("SELECT E'\\''; SELECT 1 INTO census_probe; SELECT 'tail';", "DROP TABLE census_probe")] + [InlineData("SELECT E'prefix'\n'\\''; SELECT 1 INTO census_probe; SELECT 'tail';", "DROP TABLE census_probe")] + [InlineData("CREATE FUNCTION public.census_creator() RETURNS void LANGUAGE plpgsql AS 'BEGIN EXECUTE ''CRE'' || ''ATE TABLE public.census_probe(id int)''; END;'; SELECT public.census_creator();", + "DROP TABLE census_probe; DROP FUNCTION public.census_creator()")] + public async Task Catalogue_discovers_each_persistent_relation_kind(string create, string drop) + { + await using var owner = await PostgresFixture.OpenAsync(_postgres.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + (await SchemaTableClasses.ReadAsync(owner, transaction)).Should().BeEmpty(); + await SchemaQueries.ExecuteAsync(owner, transaction, create); + (await SchemaTableClasses.ReadAsync(owner, transaction)).Should().Equal("census_probe"); + await SchemaQueries.ExecuteAsync(owner, transaction, drop); + (await SchemaTableClasses.ReadAsync(owner, transaction)).Should().BeEmpty(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerBuildSandbox.cs b/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerBuildSandbox.cs new file mode 100644 index 000000000..e0abdebae --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerBuildSandbox.cs @@ -0,0 +1,249 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Xml.Linq; + +namespace LearnStack.Tests.Unit.Analyzers; + +/// +/// Copies the real build hierarchy outside the repository, including the analyzer project +/// and its linked matcher. Local package archives supply an isolated restore; the proof +/// does not make a production restore or vulnerability-audit claim. +/// +internal sealed class AnalyzerBuildSandbox : IDisposable +{ + private const string ProbeSource = """ + namespace BuildProof; + + internal static class Probe + { + internal static void SensitiveMessage(string refreshToken) => + throw new System.InvalidOperationException(refreshToken); + + internal static void Invariant() => + throw new LearnStack.SharedKernel.Errors.DomainException("Fixed invariant."); + } + """; + + private const string DomainExceptionSource = """ + // + namespace LearnStack.SharedKernel.Errors; + + public sealed class DomainException : System.Exception + { + public DomainException(string message) : base(message) { } + } + """; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "learnstack-analyzer-build-" + Guid.NewGuid().ToString("N")); + private readonly string _backend; + private readonly string _nugetConfig; + + public AnalyzerBuildSandbox() + { + _backend = Path.Combine(_root, "backend"); + _nugetConfig = Path.Combine(_root, "NuGet.Config"); + Directory.CreateDirectory(_backend); + + try + { + var repository = FindRepository(); + foreach (var relative in new[] + { + "backend/Directory.Build.props", + "backend/Directory.Packages.props", + "backend/.editorconfig", + "backend/global.json", + "backend/src/Directory.Build.props", + "backend/src/Modules/Directory.Build.props", + "backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenMatcher.cs", + }) + { + CopyFile(repository, relative); + } + + var analyzer = Path.Combine(repository, "backend", "analyzers", "LearnStack.Analyzers"); + foreach (var file in Directory.EnumerateFiles(analyzer, "*", SearchOption.AllDirectories) + .Where(file => Path.GetExtension(file) is ".cs" or ".csproj" or ".md") + .Where(file => !Path.GetRelativePath(analyzer, file).Split(Path.DirectorySeparatorChar) + .Any(segment => segment is "bin" or "obj"))) + { + CopyFile(repository, Path.GetRelativePath(repository, file)); + } + + WriteLocalPackageSources(Path.Combine(analyzer, "obj", "project.assets.json")); + } + catch + { + Dispose(); + throw; + } + } + + public string CreateProductionProject(string layer, bool violation = true) + { + var name = "LearnStack.BuildProof." + layer; + var parent = layer is "Domain" or "Application" + ? Path.Combine(_backend, "src", "Modules", "BuildProof") + : Path.Combine(_backend, "src", "Future", "Deeply", "Nested"); + var directory = Path.Combine(parent, name); + Directory.CreateDirectory(directory); + + // No TargetFramework, warning policy, scope property or analyzer reference is + // restated here: the copied production hierarchy must supply all of them. + var project = Path.Combine(directory, name + ".csproj"); + File.WriteAllText(project, ""); + File.WriteAllText(Path.Combine(directory, "Probe.cs"), violation ? ProbeSource : """ + namespace BuildProof; + internal static class Probe + { + internal static void FixedMessage(string className) => throw new System.InvalidOperationException(className); + } + """); + File.WriteAllText(Path.Combine(directory, "DomainException.g.cs"), DomainExceptionSource); + return project; + } + + public string CreateExcludedProject(string tree) + { + var directory = Path.Combine(_backend, tree, "LearnStack.BuildProof." + tree); + Directory.CreateDirectory(directory); + var project = Path.Combine(directory, "LearnStack.BuildProof." + tree + ".csproj"); + File.WriteAllText(project, ""); + File.WriteAllText(Path.Combine(directory, "Probe.cs"), ProbeSource); + File.WriteAllText(Path.Combine(directory, "DomainException.g.cs"), DomainExceptionSource); + return project; + } + + public async Task RestoreAsync(string project) + { + var result = await RunAsync("restore", project, "--configfile", _nugetConfig, + "--packages", Path.Combine(_root, "packages"), + "--nologo", "--verbosity", "quiet", "--disable-parallel"); + + if (result.ExitCode != 0) + { + throw new InvalidOperationException("The disposable local-package restore failed. " + result.Summary); + } + } + + public Task BuildAsync(string project) => RunAsync( + "build", project, "--no-restore", "--nologo", "--verbosity", "quiet", + "--disable-build-servers", "-maxcpucount:1"); + + public static void AddOrdinaryCompilerWarning(string project) => File.AppendAllText( + Path.Combine(Path.GetDirectoryName(project)!, "Probe.cs"), + """ + + + internal static class OrdinaryCompilerWarning + { + internal static void Warn() + { + int unused = 0; + } + } + """); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + private void CopyFile(string repository, string relative) + { + var destination = Path.Combine(_root, relative); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Copy(Path.Combine(repository, relative), destination); + } + + private void WriteLocalPackageSources(string assetsFile) + { + using var assets = JsonDocument.Parse(File.ReadAllText(assetsFile)); + var folders = assets.RootElement.GetProperty("packageFolders") + .EnumerateObject().Select(folder => folder.Name).ToArray(); + + if (folders.Length == 0 || folders.Any(folder => !Directory.Exists(folder))) + { + throw new InvalidOperationException("The built analyzer has no usable local package archive cache."); + } + + new XDocument(new XElement("configuration", + new XElement("packageSources", + new XElement("clear"), + folders.Select((folder, index) => new XElement("add", + new XAttribute("key", "cache-" + index.ToString(CultureInfo.InvariantCulture)), + new XAttribute("value", folder)))), + new XElement("auditSources", new XElement("clear")))) + .Save(_nugetConfig); + } + + private async Task RunAsync(params string[] arguments) + { + var start = new ProcessStartInfo("dotnet") + { + WorkingDirectory = _backend, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + start.Environment["CI"] = "true"; + start.Environment["DOTNET_CLI_HOME"] = Path.Combine(_root, "cli-home"); + start.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + start.Environment["DOTNET_CLI_WORKLOAD_UPDATE_NOTIFY_DISABLE"] = "true"; + start.Environment["DOTNET_NOLOGO"] = "1"; + start.Environment["MSBUILDDISABLENODEREUSE"] = "1"; + start.Environment["MSBUILDTERMINALLOGGER"] = "off"; + + using var process = Process.Start(start) + ?? throw new InvalidOperationException("The disposable dotnet process did not start."); + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + + try + { + await process.WaitForExitAsync(timeout.Token); + } + catch (OperationCanceledException) when (timeout.IsCancellationRequested) + { + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(); + await Task.WhenAll(stdout, stderr); + throw new InvalidOperationException("The disposable dotnet process exceeded its time limit."); + } + + var output = await stdout + Environment.NewLine + await stderr; + // Keep failures useful without echoing restored cache paths, source expressions, + // environment values or arbitrary package/SDK messages into test output. + var diagnostics = Regex.Matches(output, @"\b(warning|error) ([A-Z]+[0-9]+)\b", RegexOptions.CultureInvariant) + .Select(match => (Severity: match.Groups[1].Value, Id: match.Groups[2].Value)) + .Distinct().ToArray(); + return new AnalyzerBuildResult(process.ExitCode, diagnostics); + } + + private static string FindRepository() + { + for (var current = new DirectoryInfo(AppContext.BaseDirectory); current is not null; current = current.Parent) + { + if (File.Exists(Path.Combine(current.FullName, "CLAUDE.md")) + && File.Exists(Path.Combine(current.FullName, "backend", "Directory.Build.props"))) + { + return current.FullName; + } + } + + throw new InvalidOperationException("The analyzer build proof could not locate the repository."); + } +} + +internal sealed record AnalyzerBuildResult(int ExitCode, (string Severity, string Id)[] Diagnostics) +{ + public bool HasDiagnostic(string severity, string id) => Diagnostics.Contains((severity, id)); + + public string Summary => string.Create(CultureInfo.InvariantCulture, + $"Exit code {ExitCode}; diagnostics: {string.Join(", ", Diagnostics.Select(item => item.Severity + " " + item.Id))}."); +} diff --git a/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerBuildTests.cs b/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerBuildTests.cs new file mode 100644 index 000000000..66a00deec --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerBuildTests.cs @@ -0,0 +1,87 @@ +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Unit.Analyzers; + +/// +/// Exercises the actual production props and compiler-visible LS0001 scope in disposable +/// builds. Every probe is a new project with no handwritten analyzer reference. +/// +public sealed class AnalyzerBuildTests +{ + private static readonly (string Layer, bool DomainDiagnostic)[] Layers = + [ + ("Domain", true), + ("Application", true), + ("Api", false), + ("Infrastructure", false), + ("Application.Contracts", false), + ("SharedKernel", false), + ("Seeder", false), + ]; + + [Fact] + public async Task New_Production_Projects_Receive_LS0002_And_Preserve_LS0001_Scope() + { + using var build = new AnalyzerBuildSandbox(); + + foreach (var (layer, domainDiagnostic) in Layers) + { + var project = build.CreateProductionProject(layer); + await build.RestoreAsync(project); + + var result = await build.BuildAsync(project); + + result.ExitCode.Should().Be(0, "the real CI build of {0} must succeed: {1}", layer, result.Summary); + result.HasDiagnostic("warning", "LS0002").Should().BeTrue( + "the new {0} project must automatically receive the analyzer: {1}", layer, result.Summary); + result.HasDiagnostic("warning", "LS0001").Should().Be(domainDiagnostic, + "the compiler-visible production scope must govern {0}: {1}", layer, result.Summary); + result.HasDiagnostic("error", "LS0001").Should().BeFalse(result.Summary); + result.HasDiagnostic("error", "LS0002").Should().BeFalse(result.Summary); + result.HasDiagnostic("warning", "AD0001").Should().BeFalse(result.Summary); + result.HasDiagnostic("error", "AD0001").Should().BeFalse(result.Summary); + } + } + + [Fact] + public async Task CI_Build_Allows_LS0002_Warning_But_Rejects_An_Unrelated_Compiler_Warning() + { + using var build = new AnalyzerBuildSandbox(); + var project = build.CreateProductionProject("Api"); + await build.RestoreAsync(project); + + var baseline = await build.BuildAsync(project); + + baseline.ExitCode.Should().Be(0, "LS0002 must remain a Warning with CI=true: {0}", baseline.Summary); + baseline.HasDiagnostic("warning", "LS0002").Should().BeTrue(baseline.Summary); + + AnalyzerBuildSandbox.AddOrdinaryCompilerWarning(project); + var control = await build.BuildAsync(project); + + control.ExitCode.Should().NotBe(0, "an unrelated compiler warning must still fail CI: {0}", control.Summary); + control.HasDiagnostic("error", "CS0219").Should().BeTrue( + "the unused-local warning must be promoted by the actual CI props: {0}", control.Summary); + control.HasDiagnostic("warning", "LS0002").Should().BeTrue(control.Summary); + control.HasDiagnostic("error", "LS0002").Should().BeFalse(control.Summary); + } + + [Fact] + public async Task Clean_Production_And_Excluded_Project_Trees_Stay_Diagnostic_Free() + { + using var build = new AnalyzerBuildSandbox(); + var projects = new[] + { + build.CreateProductionProject("Api", violation: false), + build.CreateExcludedProject("tests"), + build.CreateExcludedProject("analyzers"), + }; + foreach (var project in projects) + { + await build.RestoreAsync(project); + var result = await build.BuildAsync(project); + result.ExitCode.Should().Be(0, result.Summary); + result.Diagnostics.Should().BeEmpty("clean production code and excluded trees must stay clean: {0}", result.Summary); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerCompilation.cs b/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerCompilation.cs new file mode 100644 index 000000000..bbfd3095d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Analyzers/AnalyzerCompilation.cs @@ -0,0 +1,152 @@ +using System.Collections.Immutable; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.Loader; +using System.Text.Json; +using FluentAssertions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace LearnStack.Tests.Unit.Analyzers; + +/// Compiler-clean samples and isolated source recompilation for analyzer proofs. +internal static class AnalyzerCompilation +{ + private static readonly Lazy> References = new(() => + { + var platform = ((string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") + ?? throw new InvalidOperationException("The test host has no platform assembly references.")) + .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + var roslyn = new[] + { + typeof(DiagnosticAnalyzer).Assembly.Location, + typeof(CSharpCompilation).Assembly.Location, + }; + var runtimeDirectory = Path.GetDirectoryName(typeof(object).Assembly.Location); + + return [.. platform.Where(path => Path.GetDirectoryName(path) == runtimeDirectory) + .Concat(roslyn).Distinct(StringComparer.OrdinalIgnoreCase) + .Select(path => MetadataReference.CreateFromFile(path))]; + }); + + internal static CSharpCompilation Create(params (string Source, string Path)[] sources) + => CreateWithSettings(References.Value, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, + nullableContextOptions: NullableContextOptions.Enable), sources); + + internal static CSharpCompilation CreateWithSettings( + IEnumerable references, + CSharpCompilationOptions options, + params (string Source, string Path)[] sources) + { + var compilation = CSharpCompilation.Create( + "AnalyzerProof_" + Guid.NewGuid().ToString("N"), + sources.Select(source => CSharpSyntaxTree.ParseText( + source.Source, new CSharpParseOptions(LanguageVersion.Latest), source.Path)), + references, + options); + + compilation.GetDiagnostics() + .Where(diagnostic => diagnostic.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning) + .Should().BeEmpty("an analyzer proof must compile cleanly before its diagnostic is trusted"); + return compilation; + } + + internal static (MetadataReference[] References, CSharpCompilationOptions Options) EvaluatedAnalyzerSettings(string project) + { + using var process = new Process + { + StartInfo = new ProcessStartInfo("dotnet") + { + ArgumentList = + { + "msbuild", project, "-target:ResolveReferences,CoreCompile", "-getItem:ReferencePath", + "-getProperty:NoWarn", + "-property:SkipCompilerExecution=true", + "-property:Configuration=Release", "-nologo", "-verbosity:quiet", + }, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = Path.GetDirectoryName(project)!, + }, + }; + process.StartInfo.Environment["MSBUILDTERMINALLOGGER"] = "off"; + process.Start(); + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(60_000)) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(); + throw new InvalidOperationException("Resolving the analyzer's actual reference framework timed out."); + } + + Task.WaitAll(output, error); + process.ExitCode.Should().Be(0, "the analyzer's real references must resolve: {0}", error.Result); + using var result = JsonDocument.Parse(output.Result); + var references = result.RootElement.GetProperty("Items").GetProperty("ReferencePath").EnumerateArray() + .Select(item => (MetadataReference)MetadataReference.CreateFromFile(item.GetProperty("FullPath").GetString()!)) + .ToArray(); + references.Should().NotBeEmpty(); + // Clone compilation follows the actual analyzer project's SDK binding + // policy. Behavioral samples above retain their unsuppressed compiler gate. + var noWarn = result.RootElement.GetProperty("Properties").GetProperty("NoWarn").GetString()! + .Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) + .Select(id => int.TryParse(id, out var number) ? "CS" + number.ToString("D4", System.Globalization.CultureInfo.InvariantCulture) : id) + .Distinct(StringComparer.Ordinal) + .ToDictionary(id => id, _ => ReportDiagnostic.Suppress, StringComparer.Ordinal); + return (references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, + nullableContextOptions: NullableContextOptions.Enable, specificDiagnosticOptions: noWarn)); + } + + internal static async Task> RunAsync( + string source, + DiagnosticAnalyzer analyzer, + AnalyzerOptions? options = null, + string path = "Sample.cs") + { + var diagnostics = await Create((source, path)) + .WithAnalyzers(ImmutableArray.Create(analyzer), options ?? new AnalyzerOptions([])) + .GetAnalyzerDiagnosticsAsync(); + diagnostics.Should().NotContain(diagnostic => diagnostic.Id == "AD0001"); + return diagnostics; + } + + internal static Assembly Load(CSharpCompilation compilation, AssemblyLoadContext context) + { + using var stream = new MemoryStream(); + var emitted = compilation.Emit(stream); + emitted.Diagnostics.Where(diagnostic => diagnostic.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning) + .Should().BeEmpty("the source mutation must emit a clean assembly"); + emitted.Success.Should().BeTrue(); + stream.Position = 0; + return context.LoadFromStream(stream); + } + + internal static string RepositoryRoot() + { + for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent) + { + if (File.Exists(Path.Combine(directory.FullName, "CLAUDE.md"))) return directory.FullName; + } + + throw new InvalidOperationException("Could not locate the repository for the source propagation proof."); + } + + internal sealed class DomainScopeOptions(string value) : AnalyzerConfigOptionsProvider + { + public override AnalyzerConfigOptions GlobalOptions { get; } = new ScopeOption(value); + public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => GlobalOptions; + public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) => GlobalOptions; + + private sealed class ScopeOption(string value) : AnalyzerConfigOptions + { + public override bool TryGetValue(string key, out string result) + { + result = key == "build_property.LearnStackAnalyzeDomainExceptionThrow" ? value : string.Empty; + return key == "build_property.LearnStackAnalyzeDomainExceptionThrow"; + } + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Analyzers/DomainExceptionThrowAnalyzerTests.cs b/backend/tests/LearnStack.Tests.Unit/Analyzers/DomainExceptionThrowAnalyzerTests.cs index 54010b521..46682e56d 100644 --- a/backend/tests/LearnStack.Tests.Unit/Analyzers/DomainExceptionThrowAnalyzerTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Analyzers/DomainExceptionThrowAnalyzerTests.cs @@ -2,8 +2,6 @@ using FluentAssertions; using LearnStack.Analyzers; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace LearnStack.Tests.Unit.Analyzers; @@ -77,17 +75,28 @@ public sealed class Handler diagnostics.Should().NotContain(d => d.Id == "AD0001"); } - private static async Task> RunAnalyzerAsync(string source) + [Theory] + [InlineData("public void Run() { throw new LearnStack.SharedKernel.Errors.DomainException(\"fixed\"); }", 1)] + [InlineData("public void Run() => throw new Derived(\"fixed\");", 1)] + [InlineData("public void Run() => throw new Unrelated.DomainException(\"fixed\");", 0)] + [InlineData("public System.Exception Run() => new LearnStack.SharedKernel.Errors.DomainException(\"fixed\");", 0)] + public async Task Preserves_Direct_Throw_Inheritance_And_Namespace_Identity(string member, int expected) { - var compilation = CSharpCompilation.Create( - assemblyName: "AnalyzerSample", - syntaxTrees: [CSharpSyntaxTree.ParseText(source)], - references: [MetadataReference.CreateFromFile(typeof(object).Assembly.Location)], - options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); - - var withAnalyzers = compilation.WithAnalyzers( - ImmutableArray.Create(new DomainExceptionThrowAnalyzer())); + var source = DomainExceptionShim + """ + namespace Unrelated + { + public sealed class DomainException(string message) : System.Exception(message) { } + } + public sealed class Derived(string message) : LearnStack.SharedKernel.Errors.DomainException(message) { } + public sealed class Sample + { + """ + member + "\n}"; + var diagnostics = await RunAnalyzerAsync(source); + diagnostics.Count(diagnostic => diagnostic.Id == "LS0001").Should().Be(expected); + } - return await withAnalyzers.GetAnalyzerDiagnosticsAsync(); + private static async Task> RunAnalyzerAsync(string source) + { + return await AnalyzerCompilation.RunAsync(source, new DomainExceptionThrowAnalyzer()); } } diff --git a/backend/tests/LearnStack.Tests.Unit/Analyzers/SensitiveExceptionMessageAnalyzerTests.cs b/backend/tests/LearnStack.Tests.Unit/Analyzers/SensitiveExceptionMessageAnalyzerTests.cs new file mode 100644 index 000000000..ddef362a0 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Analyzers/SensitiveExceptionMessageAnalyzerTests.cs @@ -0,0 +1,287 @@ +using System.Globalization; +using System.Reflection; +using System.Runtime.Loader; +using System.Xml.Linq; +using FluentAssertions; +using LearnStack.Analyzers; +using LearnStack.SharedKernel.Secrets; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; +using Xunit; + +namespace LearnStack.Tests.Unit.Analyzers; + +public sealed class SensitiveExceptionMessageAnalyzerTests +{ + private const string FixedMessage = + "Use a fixed exception message without sensitive values; keep sensitive data out of exception constructor strings"; + + private const string Preamble = """ + using System; + using Failure = System.InvalidOperationException; + + public sealed class ProviderFailure : Exception + { + public ProviderFailure(string provider, string message, bool client = false) : base(message) { } + } + + public sealed class Sample + { + public string ClientSecret = "example"; + public string AuthHeader { get; } = "example"; + public const string SigningKey = "example"; + public const string Ordinary = "example"; + public string PasswordMethod() => "example"; + public static string Format(string value) => value; + + """; + + [Theory] + [InlineData("public void Run(string accessToken) { throw new Exception(accessToken); }")] + [InlineData("public void Run(string accessToken) => throw new InvalidOperationException(accessToken);")] + [InlineData("public string Run(string accessToken) => accessToken ?? throw new Exception(accessToken);")] + [InlineData("public void Run(string accessToken) => throw new Failure(accessToken);")] + [InlineData("public void Run(string accessToken) => throw (Exception)new(accessToken);")] + [InlineData("public void Run(string accessToken) => throw ((Exception)(object)new Failure((string)(object)accessToken));")] + [InlineData("public void Run(object accessToken) => throw new Exception((string)accessToken);")] + [InlineData("public void Run(string accessToken) => throw new Exception($\"Failure: {accessToken}\");")] + [InlineData("public void Run(string accessToken) => throw new Exception(\"Failure: \" + accessToken);")] + [InlineData("public void Run(string accessToken) => throw new Exception(accessToken + 42);")] + [InlineData("public void Run(string accessToken) => throw new Exception(accessToken, (dynamic)null!);")] + [InlineData("public void Run(string accessToken) => throw new Exception((dynamic)accessToken);")] + [InlineData("public void Run(dynamic accessToken) => throw new Exception((string)accessToken, (dynamic)null!);")] + [InlineData("public void Run(string accessToken) => throw new Exception($\"Length: {accessToken.Length}\");")] + [InlineData("public void Run(string accessToken) => throw new Exception($\"{Format(accessToken)}\");")] + [InlineData("public void Run() => throw new Exception(ClientSecret);")] + [InlineData("public void Run() => throw new Exception(AuthHeader);")] + [InlineData("public void Run() => throw new Exception(SigningKey);")] + [InlineData("public void Run() { const string apiKey = \"example\"; throw new Exception(apiKey); }")] + [InlineData("public void Run() { string setCookie = \"example\"; throw new Exception(setCookie); }")] + [InlineData("public void Run(string accessToken) => throw new ProviderFailure(\"provider\", accessToken);")] + [InlineData("public void Run(string accessToken) => throw new ProviderFailure(message: accessToken, provider: \"provider\");")] + [InlineData("public void Run(string accessToken) => throw new ProviderFailure((dynamic)\"provider\", accessToken);")] + [InlineData("public void Run(string accessToken) => throw new ProviderFailure(accessToken, \"fixed\");")] + [InlineData("public void Run(string accessToken) => throw new ProviderFailure(accessToken, $\"{ClientSecret}\");")] + public async Task Reports_One_Fixed_Warning_At_The_Thrown_Creation(string member) + { + var source = Preamble + member + "\n}"; + var diagnostics = await AnalyzerCompilation.RunAsync(source, new SensitiveExceptionMessageAnalyzer()); + var diagnostic = diagnostics.Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LS0002"); + diagnostic.Severity.Should().Be(DiagnosticSeverity.Warning); + diagnostic.Descriptor.Category.Should().Be("Security"); + diagnostic.Descriptor.IsEnabledByDefault.Should().BeTrue(); + diagnostic.Descriptor.Title.ToString(CultureInfo.InvariantCulture) + .Should().Contain("LearnStackException-SensitiveExceptionMessage"); + diagnostic.GetMessage(CultureInfo.InvariantCulture).Should().Be(FixedMessage); + + var creation = diagnostic.Location.SourceTree!.GetRoot().DescendantNodes() + .Single(node => node is ObjectCreationExpressionSyntax or ImplicitObjectCreationExpressionSyntax); + diagnostic.Location.SourceSpan.Should().Be(creation.Span); + diagnostic.Location.GetLineSpan().Path.Should().Be("Sample.cs"); + } + + [Theory] + [InlineData("public void Run(string className) => throw new Exception(className);")] + [InlineData("public void Run(string className) => throw new Exception(className, (dynamic)null!);")] + [InlineData("public void Run(string panel) => throw new Exception($\"{panel}\");")] + [InlineData("public void Run() => throw new Exception(\"password: secret\");")] + [InlineData("public void Run() => throw new Exception(Ordinary);")] + [InlineData("public void Run() { const string ordinary = \"password\"; throw new Exception(ordinary); }")] + [InlineData("public void Run(string accessToken) => throw new Exception(nameof(accessToken));")] + [InlineData("public void Run(string accessToken) => throw new Exception($\"{nameof(accessToken)} {typeof(Sample)}\");")] + [InlineData("public void Run() => throw new Exception($\"{PasswordMethod()}\");")] + [InlineData("public void Run(string accessToken) => throw new Exception(Format(accessToken));")] + [InlineData("public void Run(string accessToken, bool choose) => throw new Exception(choose ? accessToken : \"fixed\");")] + [InlineData("public Exception Run(string accessToken) => new Exception($\"{accessToken}\");")] + [InlineData("public void Run(string accessToken) { var failure = new Exception(accessToken); throw failure; }")] + [InlineData("public void Run(string accessToken) => throw new Exception($\"{(Func)(() => accessToken)}\");")] + [InlineData("public void Run(string accessToken) => throw new Exception(\"fixed\" + (Func)(() => accessToken));")] + [InlineData("public void Run(string accessToken) => throw new Exception($\"{((Func)(() => accessToken))()}\");")] + [InlineData("public void Run(System.Threading.CancellationToken accessToken) => throw new OperationCanceledException(\"fixed\", accessToken);")] + [InlineData("public void Run(System.Collections.Generic.Dictionary values) => throw new Exception($\"{values[\"token\"]}\");")] + [InlineData("public void Run() { try { throw new Exception(\"fixed\"); } catch { throw; } }")] + public async Task Keeps_Excluded_Forms_And_Ordinary_References_Clean(string member) + { + var diagnostics = await AnalyzerCompilation.RunAsync(Preamble + member + "\n}", new SensitiveExceptionMessageAnalyzer()); + diagnostics.Should().BeEmpty(); + } + + [Fact] + public void Descriptor_And_Null_Context_Keep_The_Public_Contract() + { + var analyzer = new SensitiveExceptionMessageAnalyzer(); + var descriptor = analyzer.SupportedDiagnostics.Should().ContainSingle().Subject; + descriptor.Id.Should().Be("LS0002"); + descriptor.DefaultSeverity.Should().Be(DiagnosticSeverity.Warning); + descriptor.IsEnabledByDefault.Should().BeTrue(); + descriptor.Category.Should().Be("Security"); + descriptor.MessageFormat.ToString(CultureInfo.InvariantCulture).Should().Be(FixedMessage); + descriptor.Description.ToString(CultureInfo.InvariantCulture).Should().Contain("ADR-0032 Amendment 6"); + descriptor.HelpLinkUri.Should().EndWith("#amendment-6--sensitive-exception-message-diagnostic-2026-10-25"); + Action initialize = () => analyzer.Initialize(null!); + initialize.Should().Throw().WithParameterName("context"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Walks_Deep_Concatenation_Without_An_Analyzer_Crash(bool sensitive) + { + // Bounded so the compiler's own parser/binder remains a safe prerequisite. + var expression = (sensitive ? "accessToken" : "ordinary") + + string.Concat(Enumerable.Repeat(" + ordinary", 1024)); + var source = $$""" + public static class Sample + { + public static void Run(string accessToken, string ordinary) => + throw new System.Exception({{expression}}); + } + """; + var diagnostics = await AnalyzerCompilation.RunAsync(source, new SensitiveExceptionMessageAnalyzer()); + diagnostics.Count(diagnostic => diagnostic.Id == "LS0002").Should().Be(sensitive ? 1 : 0); + } + + [Fact] + public async Task User_Defined_String_Addition_Is_Outside_The_Initial_Root_Forms() + { + const string source = """ + using System; + public sealed class SecretException + { + public static string operator +(SecretException left, string right) => right; + } + public static class Sample + { + public static void Run(SecretException secret, string value) => + throw new Exception(secret + value); + } + """; + + (await AnalyzerCompilation.RunAsync(source, new SensitiveExceptionMessageAnalyzer())).Should().BeEmpty(); + } + + [Theory] + [InlineData("Sample.g.cs", "")] + [InlineData("Sample.cs", "// \n")] + public async Task Generated_Code_Is_Excluded(string path, string header) + { + var source = header + Preamble + "public void Run(string token) => throw new Exception(token);\n}"; + (await AnalyzerCompilation.RunAsync(source, new SensitiveExceptionMessageAnalyzer(), path: path)).Should().BeEmpty(); + } + + [Theory] + [InlineData("true", 1)] + [InlineData("false", 0)] + [InlineData("FALSE", 0)] + public async Task LS0001_Preserves_Its_Explicit_Project_Scope(string scope, int expected) + { + const string source = """ + namespace LearnStack.SharedKernel.Errors + { + public class DomainException : System.Exception { } + } + public static class Sample + { + public static void Run() => throw new LearnStack.SharedKernel.Errors.DomainException(); + } + """; + var options = new AnalyzerOptions([], new AnalyzerCompilation.DomainScopeOptions(scope)); + var diagnostics = await AnalyzerCompilation.RunAsync(source, new DomainExceptionThrowAnalyzer(), options); + diagnostics.Count(diagnostic => diagnostic.Id == "LS0001").Should().Be(expected); + } + + [Fact] + public async Task Loaded_Analyzer_Uses_The_Complete_Runtime_Token_Union() + { + var matcher = typeof(SensitiveExceptionMessageAnalyzer).Assembly.GetType( + "LearnStack.SharedKernel.Secrets.SensitiveTokenMatcher", throwOnError: true)!; + var analyzerTokens = (IReadOnlyCollection)matcher.GetProperty( + "DefaultTokens", BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; + var runtimeTokens = SensitiveTokenCatalog.DefaultTokens; + analyzerTokens.Should().BeEquivalentTo(runtimeTokens); + analyzerTokens.Should().BeAssignableTo>().Subject.IsReadOnly.Should().BeTrue(); + + foreach (var token in runtimeTokens) + { + var identifier = "probe_" + token; + var source = $$""" + public static class Sample + { + public static void Run(string {{identifier}}) => throw new System.Exception({{identifier}}); + } + """; + var diagnostic = (await AnalyzerCompilation.RunAsync(source, new SensitiveExceptionMessageAnalyzer())) + .Should().ContainSingle("the loaded analyzer must recognize runtime token '{0}'", token).Subject; + diagnostic.Id.Should().Be("LS0002"); + diagnostic.Severity.Should().Be(DiagnosticSeverity.Warning); + diagnostic.GetMessage(CultureInfo.InvariantCulture).Should().Be(FixedMessage); + } + } + + [Fact] + public async Task Two_Word_Only_Source_Addition_Reaches_Runtime_And_The_Compiled_Analyzer() + { + const string token = "boundaryprobe"; + const string identifier = "BoundaryProbe"; + SensitiveTokenCatalog.IsSensitive(identifier).Should().BeFalse(); + const string sample = """ + public static class Sample + { + public static void Run(string BoundaryProbe) => throw new System.Exception(BoundaryProbe); + } + """; + (await AnalyzerCompilation.RunAsync(sample, new SensitiveExceptionMessageAnalyzer())).Should().BeEmpty(); + + var root = AnalyzerCompilation.RepositoryRoot(); + var matcherPath = Path.Combine(root, "backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenMatcher.cs"); + var matcher = File.ReadAllText(matcherPath); + matcher.Should().NotContain('"' + token + '"'); + var secondSet = matcher.IndexOf("TwoWordTokens =", StringComparison.Ordinal); + secondSet.Should().BeGreaterThan(0); + var initializer = matcher.IndexOf('{', secondSet); + initializer.Should().BeGreaterThan(secondSet); + var mutated = matcher.Insert(initializer + 1, "\n \"" + token + "\","); + + var runtimeSources = new[] + { + (mutated, matcherPath), + (File.ReadAllText(Path.Combine(root, "backend/src/LearnStack.SharedKernel/Secrets/SensitiveTokenCatalog.cs")), "SensitiveTokenCatalog.cs"), + }; + var directory = Path.Combine(root, "backend/analyzers/LearnStack.Analyzers"); + var project = XDocument.Load(Path.Combine(directory, "LearnStack.Analyzers.csproj")); + var linked = project.Descendants("Compile") + .Select(element => (string?)element.Attribute("Include")) + .OfType() + .Select(path => Path.GetFullPath(path.Replace('\\', Path.DirectorySeparatorChar), directory)).ToArray(); + linked.Should().ContainSingle(path => path == matcherPath, + "the actual analyzer project must compile the canonical matcher source"); + var analyzerSources = Directory.EnumerateFiles(directory, "*.cs") + .Concat(linked) + .Select(path => (path == matcherPath ? mutated : File.ReadAllText(path), path)).ToArray(); + + var context = new AssemblyLoadContext("SensitiveTokenPropagation_" + Guid.NewGuid().ToString("N"), isCollectible: true); + try + { + var runtime = AnalyzerCompilation.Load(AnalyzerCompilation.Create(runtimeSources), context); + var facade = runtime.GetType("LearnStack.SharedKernel.Secrets.SensitiveTokenCatalog", throwOnError: true)!; + facade.GetMethod("IsSensitive", BindingFlags.Static | BindingFlags.Public)! + .Invoke(null, [identifier]).Should().Be(true); + ((IReadOnlyCollection)facade.GetProperty("DefaultTokens")!.GetValue(null)!).Should().Contain(token); + + var settings = AnalyzerCompilation.EvaluatedAnalyzerSettings(Path.Combine(directory, "LearnStack.Analyzers.csproj")); + var assembly = AnalyzerCompilation.Load( + AnalyzerCompilation.CreateWithSettings(settings.References, settings.Options, analyzerSources), context); + var analyzer = (DiagnosticAnalyzer)Activator.CreateInstance( + assembly.GetType(typeof(SensitiveExceptionMessageAnalyzer).FullName!, throwOnError: true)!)!; + var diagnostic = (await AnalyzerCompilation.RunAsync(sample, analyzer)).Should().ContainSingle().Subject; + diagnostic.Id.Should().Be("LS0002"); + diagnostic.GetMessage(CultureInfo.InvariantCulture).Should().Be(FixedMessage); + } + finally + { + context.Unload(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditStateCaptureTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditStateCaptureTests.cs index bafe5810a..b829de37c 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditStateCaptureTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditStateCaptureTests.cs @@ -108,16 +108,41 @@ public void Clear_returns_it_to_the_state_a_fresh_request_starts_in() // Called once, by the outermost behavior, in its finally. Anything left behind is // one request's snapshot arriving in the next request's audit row. var capture = new AuditStateCapture(); + capture.OpenFrame(); capture.DeclareIntent(Intent("tenancy.tenant.create")); capture.Add(new CapturedEntityChange("Tenant", "t-1", "{}", "{}", [])); + capture.OpenFrame(); + capture.DeclareIntent(Intent("tenancy.organization.create")); + capture.Add(new CapturedEntityChange("Organization", "o-1", "{}", "{}", [])); capture.MarkIndeterminate(new InvalidOperationException("boom")); + capture.HasOpenFrame.Should().BeTrue(); + capture.Intents.Should().HaveCount(2); + capture.Changes.Should().HaveCount(2); + capture.IndeterminateCause.Should().NotBeNull(); + capture.Clear(); capture.State.Should().Be(AuditIntentState.None); capture.Intents.Should().BeEmpty(); capture.Changes.Should().BeEmpty(); capture.IndeterminateCause.Should().BeNull(); + capture.HasOpenFrame.Should().BeFalse(); + + // Reuse the cleared object through real frame operations: stale parallel + // bookkeeping lists must not attach these writes to the discarded frames. + capture.OpenFrame(); + capture.OpenFrame(); + var intent = Intent("tenancy.tenant.create"); + var change = new CapturedEntityChange("Tenant", "t-2", null, "{}", []); + capture.DeclareIntent(intent); + capture.Add(change); + capture.ChangesOf(intent).Should().ContainSingle().Which.Should().BeSameAs(change); + capture.CloseFrame(AuditIntentResult.Succeeded); + capture.Intents.Should().ContainSingle().Which.Result.Should().BeSameAs(AuditIntentResult.Succeeded); + capture.HasOpenFrame.Should().BeTrue("the new outer frame still owns its inner invocation"); + capture.CloseFrame(AuditIntentResult.Succeeded); + capture.HasOpenFrame.Should().BeFalse(); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Observability/RedactSensitiveFieldsEnricherTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Observability/RedactSensitiveFieldsEnricherTests.cs index 8e2ba18ad..b20931655 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Observability/RedactSensitiveFieldsEnricherTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Observability/RedactSensitiveFieldsEnricherTests.cs @@ -74,6 +74,102 @@ public void Leaves_Clean_Event_Unchanged_By_Reference() logEvent.Properties["UserName"].Should().BeSameAs(inner); } + [Fact] + public void Redacts_Dictionary_Keys_And_Preserves_Ordinary_And_Non_String_Keys() + { + var ordinary = new ScalarValue("public"); + var numeric = new ScalarValue("numeric-key-value"); + var dictionary = new DictionaryValue(new Dictionary + { + [new ScalarValue("AuthenticationHeader")] = new ScalarValue("private-header-canary"), + [new ScalarValue("ClassName")] = ordinary, + [new ScalarValue(7)] = numeric, + }); + var logEvent = CreateEvent(new LogEventProperty("Context", dictionary)); + + Enrich(logEvent); + + var redacted = (DictionaryValue)logEvent.Properties["Context"]; + redacted.Elements.Keys.Should().BeEquivalentTo(dictionary.Elements.Keys); + ((ScalarValue)redacted.Elements[new ScalarValue("AuthenticationHeader")]).Value.Should().Be(Redacted); + redacted.Elements[new ScalarValue("ClassName")].Should().BeSameAs(ordinary); + redacted.Elements[new ScalarValue(7)].Should().BeSameAs(numeric); + ((ScalarValue)dictionary.Elements[new ScalarValue("AuthenticationHeader")]).Value + .Should().Be("private-header-canary", "redaction reconstructs the value without mutating its input"); + } + + [Fact] + public void Redacts_Sequence_Descendants_Without_Dropping_Clean_Items_Before_Or_After_Them() + { + var first = new ScalarValue("first"); + var last = new ScalarValue("last"); + var account = new StructureValue( + [ + new LogEventProperty("Password", new ScalarValue("private-sequence-canary")), + new LogEventProperty("Name", new ScalarValue("public")), + ], "Account"); + var sequence = new SequenceValue([first, account, last]); + var logEvent = CreateEvent(new LogEventProperty("Accounts", sequence)); + + Enrich(logEvent); + + var redacted = (SequenceValue)logEvent.Properties["Accounts"]; + redacted.Elements.Should().HaveCount(3); + redacted.Elements[0].Should().BeSameAs(first); + redacted.Elements[2].Should().BeSameAs(last); + var redactedAccount = (StructureValue)redacted.Elements[1]; + redactedAccount.TypeTag.Should().Be("Account"); + ScalarOf(redactedAccount, "Password").Should().Be(Redacted); + ScalarOf(redactedAccount, "Name").Should().Be("public"); + ScalarOf(account, "Password").Should().Be("private-sequence-canary"); + } + + [Fact] + public void Redacts_Deeply_Mixed_Structures_Dictionaries_And_Sequences() + { + var leaf = new StructureValue( + [new LogEventProperty("ApiKey", new ScalarValue("private-deep-canary"))]); + var dictionary = new DictionaryValue(new Dictionary + { + [new ScalarValue("Items")] = new SequenceValue([leaf]), + }); + var root = new StructureValue( + [new LogEventProperty("Groups", new SequenceValue([dictionary]))], "Root"); + var logEvent = CreateEvent(new LogEventProperty("Context", root)); + + Enrich(logEvent); + + var redactedRoot = (StructureValue)logEvent.Properties["Context"]; + var groups = (SequenceValue)redactedRoot.Properties.Single().Value; + var redactedDictionary = (DictionaryValue)groups.Elements.Single(); + var items = (SequenceValue)redactedDictionary.Elements[new ScalarValue("Items")]; + var redactedLeaf = (StructureValue)items.Elements.Single(); + redactedRoot.TypeTag.Should().Be("Root"); + ScalarOf(redactedLeaf, "ApiKey").Should().Be(Redacted); + redactedRoot.ToString().Should().NotContain("private-deep-canary"); + } + + [Fact] + public void Leaves_Clean_Composite_Values_Unchanged_By_Reference() + { + var leaf = new StructureValue([new LogEventProperty("Name", new ScalarValue("public"))]); + var dictionary = new DictionaryValue(new Dictionary + { + [new ScalarValue("ClassName")] = leaf, + }); + var sequence = new SequenceValue([dictionary]); + var logEvent = CreateEvent( + new LogEventProperty("Details", leaf), + new LogEventProperty("Groups", dictionary), + new LogEventProperty("Items", sequence)); + + Enrich(logEvent); + + logEvent.Properties["Details"].Should().BeSameAs(leaf); + logEvent.Properties["Groups"].Should().BeSameAs(dictionary); + logEvent.Properties["Items"].Should().BeSameAs(sequence); + } + private static void Enrich(LogEvent logEvent) => new RedactSensitiveFieldsEnricher().Enrich(logEvent, new SimplePropertyFactory()); diff --git a/backend/tests/LearnStack.Tests.Unit/SharedKernel/Secrets/SensitiveTokenCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/SharedKernel/Secrets/SensitiveTokenCatalogTests.cs index 0d18e888b..dfa3e3fa0 100644 --- a/backend/tests/LearnStack.Tests.Unit/SharedKernel/Secrets/SensitiveTokenCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/SharedKernel/Secrets/SensitiveTokenCatalogTests.cs @@ -1,3 +1,4 @@ +using System.Globalization; using FluentAssertions; using LearnStack.SharedKernel.Secrets; using Xunit; @@ -11,6 +12,30 @@ namespace LearnStack.Tests.Unit.SharedKernel.Secrets; /// public sealed class SensitiveTokenCatalogTests { + [Fact] + public void DefaultTokens_Is_The_Complete_Immutable_Union() + { + string[] expected = + [ + "apikey", "authenticationheader", "authorization", "authheader", "cardnumber", + "connectionstring", "cookie", "credential", "creditcard", "cvc", "cvv", "dsn", + "encryptionkey", "hmac", "iban", "jwt", "otp", "pan", "passwd", "password", "pin", + "privatekey", "pwd", "secret", "setcookie", "signature", "signingkey", "ssn", "tckn", + "token", "vkn", + ]; + + var snapshot = SensitiveTokenCatalog.DefaultTokens; + snapshot.Should().BeEquivalentTo(expected); + snapshot.Should().OnlyHaveUniqueItems(); + snapshot.Should().BeSameAs(SensitiveTokenCatalog.DefaultTokens, "the complete union is cached"); + snapshot.Should().NotBeOfType(); + var collection = snapshot.Should().BeAssignableTo>().Subject; + collection.IsReadOnly.Should().BeTrue(); + Action mutate = () => collection.Add("invented"); + mutate.Should().Throw(); + SensitiveTokenCatalog.DefaultTokens.Should().BeEquivalentTo(expected); + } + [Theory] [InlineData("Password")] [InlineData("UserPassword")] @@ -92,4 +117,38 @@ public void IsSensitive_False_For_Ordinary_Names(string name) { SensitiveTokenCatalog.IsSensitive(name).Should().BeFalse(); } + + [Theory] + [InlineData("api.key")] + [InlineData("api-key")] + [InlineData("api/key")] + [InlineData("api key")] + [InlineData("api::key")] + [InlineData("__auth..header--")] + [InlineData("request2Token")] + [InlineData("HTTPAuthorization")] + public void IsSensitive_Preserves_Separator_And_Acronym_Boundaries(string name) => + SensitiveTokenCatalog.IsSensitive(name).Should().BeTrue(); + + [Fact] + public void IsSensitive_Is_Ordinal_Under_Turkish_Culture_And_Handles_Null() + { + var previous = CultureInfo.CurrentCulture; + var previousUi = CultureInfo.CurrentUICulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR"); + CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture; + SensitiveTokenCatalog.IsSensitive("SIGNING_KEY").Should().BeTrue(); + SensitiveTokenCatalog.IsSensitive("PRIVATE_KEY").Should().BeTrue(); + SensitiveTokenCatalog.IsSensitive("ClassName").Should().BeFalse(); + SensitiveTokenCatalog.IsSensitive("---").Should().BeFalse(); + SensitiveTokenCatalog.IsSensitive(null!).Should().BeFalse(); + } + finally + { + CultureInfo.CurrentCulture = previous; + CultureInfo.CurrentUICulture = previousUi; + } + } } diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index b1a1883ce..fe3cb3139 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -14,9 +14,11 @@ Every aggregate that may hold personal data must declare its PII category at des | **PII-Behaviour** | Learning progress, lesson views, assessment attempts, classroom attendance | Exportable as part of the user's data; anonymisable on deletion (replaced with a pseudonymous id). | | **PII-Sensitive** | Recording audio / video, transcripts, medical accommodation notes (post-MVP) | Stored only when consent is captured; deletable with the recording itself; never logged. | | **Payment** | Billing addresses, last-four card digits, invoice records | Retained 7 years for tax compliance (cannot be deleted on request); separate retention from other PII. | -| **Audit** | Audit log entries referencing the user | Retained per [18-audit-coverage.md](../standards/18-audit-coverage.md); deletion request anonymises the actor field but keeps the action record. | +| **Audit** | Audit log entries referencing the user | Retained per [18-audit-coverage.md](../standards/18-audit-coverage.md); bounded redaction preserves the action record and immutable identifiers. See [erasure prerequisites](#erasure-authority-and-first-writer-prerequisites). | -Every aggregate's domain spec records its PII categories; a CI check ensures every entity with an email / phone / address column is annotated. +Every aggregate's domain spec must record its PII categories. Phase 03 owns the +classification census and planted missing-annotation control before its first +DSAR writer; no current CI check discovers every email/phone/address column. ## Rights We Support @@ -54,7 +56,9 @@ Per category: - PII-Behaviour → anonymisation (progress / attempts retained for cohort statistics; actor field is replaced). - PII-Sensitive → hard delete (recordings deleted from storage; metadata anonymised). - Payment → retained for legal period; user notified of the exception. -- Audit → actor field anonymised; action record retained. +- Audit → redact the six permitted human-facing columns; retain the action record. + Immutable identifiers and metadata require the bounded decision below before the + first erasure writer can claim complete anonymisation. Deletion is a workflow, not a single SQL statement — and there are **two** of them, separated by authority. Conflating them lets a tenant admin close a person's account @@ -65,8 +69,8 @@ that tenant. 1. Eligibility is validated (no active payment dispute, no legal hold). 2. The `Membership` and its `MembershipProfile` are removed. -3. That tenant's behaviour rows are anonymised; that tenant's audit entries keep the - action record with the actor field anonymised. +3. That tenant's behaviour rows are anonymised; its audit entries keep the action + record, with redaction subject to the [first-writer prerequisites](#erasure-authority-and-first-writer-prerequisites). 4. The `users` row survives for as long as any membership remains anywhere. Nothing in this flow touches Keycloak. @@ -83,6 +87,141 @@ endpoint for it. 5. A final reconciliation job confirms every module reported completion within 30 days. Failures escalate to platform admin. +### Durable asynchronous store inventory + +This is the canonical inventory for the durable asynchronous copies introduced by +Phase 02b, including references added to existing audit storage. Identifier-only +values can still identify a person; absence of free text is no erasure exemption. +The inventory records subject locators and existing constraints. It grants no +erasure authority and selects no retention period or deletion order. + +The ten first-party tables are in LearnStack's database. Canonical DDL and grants +remain in Database Standards: [Outbox](../standards/05-database.md#outbox), +[Inbox and delivery ledger](../standards/05-database.md#inbox), and +[Background jobs](../standards/05-database.md#background-jobs). + + +| 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 | +| `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 | +| `background_job_attempts` | `job_id`, identifier-only `outcome`, operation/quiescence IDs, fingerprint, selected-outcome link and finite `failure_policy` | Write-once retry/effect/cleanup facts are not a mutable person profile | +| `background_job_capacity` | `tenant_id`, finite capacity-group key and timestamp | Coordination metadata; no person content or person-erasure target | +| `background_job_reservations` | Tenant/job/attempt linkage, finite group and reservation/release facts | Erasure does not prove quiescence and cannot free unresolved occupancy | +| `background_job_recurrences` | Finite definition/revision/manifest/target/schedule/recipient-policy metadata; no user or arbitrary parameters | Infrastructure control; no ordinary app access | +| `background_job_occurrences` | Manifest/slot identity and frozen tenant/org sweep bounds/checkpoints; no person column or arbitrary payload | Preserve occurrence history and monotonic progress | +| `background_job_recipients` | Immutable tenant/org route, occurrence/manifest/target and accepted child-job receipt | Recipient is a tenant/org route, not a person; reciprocal job links constrain future purge order | + + +The complete Platform migration census also includes this explicit scope exclusion. +Exclusion from this asynchronous inventory is not an erasure exemption. + + +| Excluded table | Scope boundary | +|---|---| +| `idempotency_keys` | Synchronous HTTP request replay, outside asynchronous transport scope; cached body/headers can still contain personal data | + + +Other module tables remain explicit scope exclusions, so a new table cannot +silently escape the five-chain migration census. Their own module specifications +govern personal data; exclusion here grants no erasure exemption. + + +| Excluded table | Scope boundary | +|---|---| +| `tenants` | Tenancy aggregate | +| `organizations` | Tenancy aggregate | +| `tenant_domains` | Tenancy host configuration | +| `tenant_locales` | Tenancy locale configuration | +| `tenant_settings` | Tenancy configuration | +| `tenant_feature_flags` | Tenancy feature configuration | +| `platform_entitlement_cache` | Entitlement projection | +| `platform_host_to_tenant` | Host-resolution projection | +| `platform_killswitches` | Platform feature configuration | +| `customization_generations` | Customization publication metadata | +| `tenant_content_types` | Customization definitions | +| `tenant_level_taxonomies` | Customization definitions | +| `tenant_level_taxonomy_items` | Customization definition items | +| `courses` | Education aggregate | +| `lessons` | Education aggregate | +| `course_translations` | Education localized content | +| `lesson_translations` | Education localized content | +| `audit_config` | Audit coverage configuration | + + +LearnStack job-table no-delete triggers also bind the owner; BYPASSRLS is not +an exemption. Restrictive job/attempt/recipient foreign keys constrain deletion +order. No ordinary erasure operation can remove those facts under current DDL. + +All twelve guarded Hangfire schema-23 tables are in `public`, in the same database. +The pinned table/column census is `HangfireStorageContract.Columns`; canonical +[vendor storage definitions and guards](../standards/05-database.md#p02b-4-stock-hangfire-control-storage) +forbid business payloads and credentials. Opaque identifiers remain linkable. +Vendor maintenance grants are confined transport authority, not a person-erasure +API or a generic Platform grant. + + +| Vendor table | Copy or control classification | +|---|---| +| `schema` | Schema-version bookkeeping; no person content | +| `counter` | Finite control counters and expiry; no person content | +| `aggregatedcounter` | Aggregated control counters and expiry; no person content | +| `hash` | Guarded recurrence/control fields and values; opaque job references can link to authoritative rows | +| `job` | Guarded invocation/argument wakeup references and state linkage; no business parameters | +| `state` | Job/state linkage, finite state metadata and redacted reason/data | +| `jobqueue` | Opaque job reference, finite queue and fetch metadata | +| `list` | Guarded control keys/values; opaque references remain linkable | +| `server` | Guarded server identity, queue/worker and heartbeat metadata | +| `set` | Guarded control/recurrence keys and opaque job references | +| `jobparameter` | Job-linked guarded parameter name/value metadata | +| `lock` | Guarded resource, acquisition and update-control metadata | + + +The inventory also covers these distinct copies and custody boundaries: + + +| Store or custody boundary | Subject linkage and limit | +|---|---| +| Existing `audit_log` | Asynchronous terminal/causal `metadata`, including `causal_actor_user_id`, beside immutable actor/entity/causation identifiers. Redacting human-facing fields leaves references; see [Audit data model](31-audit-subsystem.md#7-data-model) | +| Development Keycloak user events, `EVENT_ENTITY` | Provider `USER_ID`, `SESSION_ID`, `IP_ADDRESS`, client/realm and event-detail JSON. Separate provider storage and identity namespace; account invalidation does not erase prior events. Selection and qualified finite retention remain under [ADR-0070](../decisions/0070-owned-tenant-bff-sessions.md#reads-and-durable-event-ownership) | +| External diagnostics and local error files | Log, trace, Sentry and `LocalFileErrorTracker` JSON archives can retain linkable exception/context copies; source-row deletion does not erase them | +| Database, WAL and backups | Retained copies need backup and post-restore reconciliation; source-row deletion alone does not remove them | +| Native BFF session custody | `InMemoryBffSessionStore` is volatile process-local custody under ADR-0070, not a durable ledger. Local invalidation does not erase provider events or diagnostic archives | + + +### Erasure authority and first-writer prerequisites + +- [Phase 03](../roadmap/phase-03-identity-admin.md#tenant-data-ownership-dsar-boundary-and-pii-classification) + implements tenant-scoped DSAR export/erasure, separate global account closure, + subject/actor mapping, request authority and audit redaction. Its first writer + must account for every applicable reference in this inventory. This does not + transfer those deliverables to Phase 11. +- [Phase 11](../roadmap/phase-11-production-hardening.md#data-operations) extends + those workflows across later modules and retained copies, and owns purge, + retention, backup, provider/diagnostic and operational reconciliation. +- Before either phase's first affected writer, its bounded decision names the + subject mapping, permissible transformations, exact principal and minimum + 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. +- 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 + reset replay or release capacity. +- Audit redaction currently permits only `actor_email`, `ip_address`, + `user_agent`, `before_state`, `after_state` and `changes`. + `actor_user_id` remains immutable and `metadata` is outside that grant + ([Audit append-only enforcement](31-audit-subsystem.md#append-only-enforcement)). + Phase 03 must decide the surviving actor/entity/causation references and new + causal metadata before its redaction/erasure handler lands; this inventory + does not claim that complete anonymisation already works. + ### Right to Restriction of Processing A learner can request that processing be paused while a dispute is resolved. Implementation: a tenant-scoped flag on the user that gates analytics ingestion and notifications. Reads continue (the user can still log in and see their own data) but no new events are processed. @@ -201,27 +340,52 @@ For tenants subject to KVKK / GDPR, LearnStack acts as a **data processor** whil ## Operational Requirements -- **PII redaction in logs.** Configured at the logging pipeline; the `[PiiSensitive]` attribute on a property excludes it from log emission ([10-observability.md](../standards/10-observability.md)). -- **PII redaction in error reports.** Sentry receives redacted payloads; integration tests assert the redaction layer cannot be bypassed. +- **PII redaction in logs.** The Serilog enricher redacts structured properties + whose names match the shared token matcher. `[PiiSensitive]` controls audit + snapshots, not arbitrary log values or exception text; see + [Observability](../standards/10-observability.md#errors). +- **PII redaction in error reports.** Sentry and local-file adapters redact + matching `AdditionalTags` names. They retain exception messages and stacks; + no whole-payload redaction or bypass-proof integration test is claimed. + Callers must use fixed messages/closed descriptors. Phase 03 owns category + handling at its first PII writer; Phase 11 qualifies diagnostic egress and + retention before production use. - **Encryption at rest.** Storage provider (S3 / SeaweedFS) + PostgreSQL volumes use the provider's at-rest encryption; specific configuration documented in [12-infrastructure.md](../standards/12-infrastructure.md). - **TLS in transit.** [11-security.md](../standards/11-security.md) § Transport. -- **Backups.** Per-tenant deletion must propagate to backups within the platform's RPO + 1 backup cycle; the `delete-from-backups` job runs nightly. +- **Backups.** Phase 11 owns retained backup/WAL handling and post-restore + reconciliation against the [inventory](#durable-asynchronous-store-inventory). + The existing propagation target remains the platform's RPO + one backup cycle; + Phase 11 qualifies the mechanism. Source-row deletion does not prove removal + from backups; Phase 02b delivers no nightly `delete-from-backups` job. - **Subject-access timeline.** GDPR Article 12 requires response within 30 days. Engineering target: export bundle ready within 7 days of request; deletion completed within 30 days. ## Roadmap Touchpoints +- **Phase 03** — Tenant-scoped DSAR export/erasure, separate global closure and + audit redaction, subject to the [first-writer prerequisites](#erasure-authority-and-first-writer-prerequisites). - **Phase 04** — First content holding PII (page metadata, content entries with author fields). Categories declared. -- **Phase 07** — Learner portal stores PII-Behaviour. Export skeleton lands. +- **Phase 07** — Learner portal adds PII-Behaviour. Its first such writer must + integrate with Phase 03's export/erasure workflows. - **Phase 08c** — Recordings (PII-Sensitive). Consent flow + retention. - **Phase 09** — Billing payment data. 7-year retention. -- **Phase 11** — Full data-export pipeline, anonymisation workflow, sub-processor list, incident-notification runbook, KVKK / GDPR compliance review. +- **Phase 11** — Complete the Phase 03 workflows across later modules and retained + copies; decide purge/retention operations, backup reconciliation, sub-processor + list, incident-notification runbook and KVKK / GDPR compliance review. A separate data-protection runbook (`docs/runbooks/data-protection.md`) lands in Phase 11 and links to this architecture document. ## Risks -- **Deletion incompleteness.** A module that doesn't subscribe to the anonymisation event leaks the user's data. Mitigation: architecture test asserts every tenant-owned aggregate either anonymises or hard-deletes on `UserAnonymisationRequestedV1`. -- **Backup re-introduction.** Restoring a backup re-introduces deleted PII. The post-restore job replays the deletion log against the restored state. Documented in the DR runbook. -- **Cross-tenant data in exports.** An export must never include another user's identifiable data. Cohort statistics are aggregated and anonymous; integration tests assert this. +- **Deletion incompleteness.** Phase 03 must implement and test every applicable + module's erasure response before its first writer; Phase 11 extends that + coverage to later modules and retained copies. The event and coverage control + described above are planned, not current implementations. +- **Backup re-introduction.** Phase 11 must qualify post-restore reconciliation + and document it in its DR runbook; no current replay job or runbook is claimed. +- **Cross-tenant data in exports.** Phase 03's DSAR integration tests must prove + that an export excludes another user's identifiable data before release. - **Sub-processor surprise.** Adding a new sub-processor without notice breaks the processor agreement. The Tenancy module tracks the sub-processor list and emits a notice 30 days before any change. -- **Audit-vs-erasure tension.** Audit entries must be retained for accountability but cannot identify a deleted user. Resolved by anonymising the actor field while keeping the action record. +- **Audit-vs-erasure tension.** Redacting the six permitted columns leaves immutable + actor/entity/causation identifiers and causal metadata. Phase 03's bounded + first-writer decision must reconcile those references with accountability; the + existing redaction grant does not establish complete anonymisation. diff --git a/docs/architecture/30-api-gateway.md b/docs/architecture/30-api-gateway.md index 6fed08a99..10e50fcbc 100644 --- a/docs/architecture/30-api-gateway.md +++ b/docs/architecture/30-api-gateway.md @@ -294,7 +294,7 @@ routes: # a per-environment decision here; the application serves both everywhere, # because the document is the contract the SDK generates from. - # Hangfire dashboard — defense-in-depth: gateway BasicAuth + backend role check + # Hangfire dashboard — gateway BasicAuth + backend Platform-scope permission - id: 3 uri: /admin/hangfire* priority: 400 @@ -392,8 +392,9 @@ routes: ``` The corrections in Rules 1–3 land in the shipped `infra/apisix/apisix.yaml` in -[Phase 03](../roadmap/phase-03-identity-admin.md), alongside uncommenting the -`openid-connect` block against the realm that exists by then. APISIX becomes a real +[Phase 03](../roadmap/phase-03-identity-admin.md). The `openid-connect` block stays +disabled until its qualification and gateway activation in Phase 11. APISIX +becomes a real gateway — TLS termination, consumer-keyed limits, WAF — in [Phase 11](../roadmap/phase-11-production-hardening.md). @@ -535,7 +536,9 @@ 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 both BasicAuth (gateway) and `IsInRole("platform-admin")` +- [ ] 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). - [ ] Production CORS allow-list (no `localhost`). - [ ] OpenAPI dev route gated by environment (404 in prod). diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index bf56f4920..86659b70d 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -1396,12 +1396,13 @@ CREATE TRIGGER tg_audit_log_no_truncate Four properties worth stating, because a careless copy loses each of them: -- **`actor_user_id` is deliberately immutable.** Once the `users` row is erased it is an - orphan surrogate key with no path back to a natural person, which is what keeps the - audit row's existence auditable after erasure. Redacting it would collapse every erased - user's history into one indistinguishable bucket and make the probe-detection queries - [Audit Coverage Standards](../standards/18-audit-coverage.md) justifies the whole - `denied` class with unanswerable. +- **`actor_user_id` is deliberately immutable.** It preserves distinct actor + histories after a user row is erased; removing it would collapse those histories + and prevent the probe-detection queries in + [Audit Coverage Standards](../standards/18-audit-coverage.md). An orphan identifier + does not prove that a person cannot be reidentified through other retained copies. + The [durable-copy inventory](23-data-protection.md#durable-asynchronous-store-inventory) + and Phase 03's first-writer decision cover the surviving references. - **`BEFORE` row triggers on partitioned tables are supported from PostgreSQL 13**, and LearnStack runs 18+ ([ADR-0031](../decisions/0031-postgresql-major-version.md)). The row trigger is inherited by partitions created later, so Phase 11 partitioning remains @@ -1570,9 +1571,11 @@ Phase 11 owns retention purge, not redaction. `actor_user_id`, `module`, `operation`, `operation_type`, `operation_class`, `outcome`, `correlation_id` and `timestamp` are **never** redacted; the trigger rejects an `UPDATE` -that changes any of them. What survives erasure is a pseudonymous record that a regulator -can still reconstruct "who did what, when, with what outcome" from — which is the point of -redacting in place rather than deleting. +that changes any of them. `metadata` is also outside the six-column redaction +grant and can retain causal actor references. Preserving an attributable history +is not proof of complete anonymisation. Phase 03 settles those references under +the [erasure first-writer prerequisites](23-data-protection.md#erasure-authority-and-first-writer-prerequisites) +before its redaction handler ships. Every module that stores user references in audit payloads registers an `IUserReferenceLocator`. It lands in [Phase 03](../roadmap/phase-03-identity-admin.md) diff --git a/docs/architecture/33-cross-cutting-concerns.md b/docs/architecture/33-cross-cutting-concerns.md index b4787bbd7..6245b4cd0 100644 --- a/docs/architecture/33-cross-cutting-concerns.md +++ b/docs/architecture/33-cross-cutting-concerns.md @@ -154,8 +154,8 @@ Request [4] TenantContextBehavior ← assert ITenantContext.IsResolved; preserve context; public requests require host ceiling ▼ -[5] AuthorizationBehavior ← IAuthorizationService.AuthorizeAsync; - Result.Fail(forbidden) on deny +[5] AuthorizationBehavior ← current pass-through shell; + Phase 03 owns permission enforcement ▼ [6] TransactionBehavior ← IUnitOfWork.BeginTransactionAsync(); announce mode setup, then tenant announcement before data; @@ -163,8 +163,8 @@ Request commit on success-Result, rollback on fail-Result or exception ▼ -[7] OutboxFlushBehavior ← enrol IOutbox messages in current tx; - they ship via DaprEventBus on commit +[7] OutboxFlushBehavior ← producer enrollment/invariant guard; + enqueue inserts immediately in the current tx ▼ [8] Handler ← domain logic; returns Result ``` @@ -240,11 +240,12 @@ Why this order: fires at connection open, not at transaction start. See [Security Standards § Tenant Context](../standards/11-security.md), the single authority for this placement. -- **Authorization after tenant.** A permission decision usually keys on - `(tenant_id, user_id, resource)` — those must be ambient first. -- **Transaction after authorization.** No transaction is opened for a - forbidden request; the `denied` MUST-class row for that request is written - standalone, in its own short transaction. +- **Authorization after tenant.** Phase 03's permission decision needs ambient + `(tenant_id, user_id, resource)`. The current behavior passes requests through; + the closed HTTP boundary above does not implement those permissions. +- **Transaction after authorization.** This position lets Phase 03 refuse a + permission-sensitive request before opening a business transaction; its + `denied` MUST-class row uses the standalone audit path. - **The MUST-class audit row is written inside the transaction, not after it.** `TransactionBehavior` calls `IAuditStore.WritePendingAsync` immediately before `COMMIT`, so the row commits with the state change it describes or not at all @@ -252,10 +253,13 @@ Why this order: unit-of-work frame (`IUnitOfWorkScope.IsOwner`) writes and reports the commit boundary, and it flushes every intent in the scope; a joiner writes nothing, signals nothing, and does not clear the capture. -- **Outbox flush inside the transaction.** Per - [15-event-and-outbox.md](15-event-and-outbox.md), outbox rows write in the - same transaction as the originating domain change; the behavior is the - enrollment seam. +- **Producer guard inside the transaction.** Under + [ADR-0032 Amendment 4](../decisions/0032-exception-handling-logging-and-observability.md#amendment-4--bounded-producer-supersession-by-adr-0057-2026-10-12), + `IOutbox.EnqueueAsync` inserts immediately in the announced ambient transaction. + Step 7 checks producer enrollment and invariants; it buffers and publishes + nothing. The transaction owner drains domain events before MUST audit and + commit. A separate dispatcher later publishes through `IEventBus`, whose + current implementation is `InProcessEventBus`. - **Handler at the innermost layer.** Pure domain + application logic; everything ambient (tenant, logger, transaction, audit context) is set up before it runs. @@ -376,9 +380,11 @@ is "scope inherits" — the `LoggingBehavior` opens the scope once at the start of the request; nested calls (handlers, EF interceptor logs, Dapr-emitted logs through the auto-instrumentation) inherit it without per-call work. -Redaction (passwords, tokens, full PII payloads) happens in an enricher -**before** the formatter so neither console nor OTLP sink ever sees the -plaintext. +The enricher redacts structured properties whose names match the shared token +matcher before formatting. It does not inspect arbitrary values, literal message +text or exception messages/stacks. Error trackers redact matching additional-tag +names only. Fixed messages and closed descriptors remain necessary; the exact +boundary is [Sensitive Exception Messages](../standards/09-error-handling.md#sensitive-exception-messages). ## 6. Tracing Stack @@ -566,13 +572,14 @@ Two integration points |---|---|---| | `Result` + `Error` shape | Phase 01 (scaffolded) | Code already exists in `LearnStack.SharedKernel` | | `LearnStackException` hierarchy | Phase 02a | Day-1 foundation | -| MediatR pipeline (8 behaviors) | Phase 02a | Order frozen by ADR-0032 | +| MediatR pipeline (7 behaviors plus handler) | Phase 02a | Eight-stage order frozen by ADR-0032 | | `LearnStackExceptionHandler : IExceptionHandler` | Phase 02a | L1 catch site | | Serilog + OTel SDK wiring | Phase 02a | Hosts wire it once | | `TenantContextSpanProcessor` | Phase 02a | OTel span enrichment | | `IErrorTrackingProvider` socket | Phase 02a | Three implementations registered per `DeploymentMode` | | `IProviderResilience` collaborator | Phase 02a | Foundation for every adapter | | Roslyn analyzer for `DomainException` | Phase 02a | Compile-time enforcement of "bug only" | +| Sensitive exception-message analyzer | P02b-8 | `LS0002` covers bounded sensitive-name expressions across production C#; ADR-0032 Amendment 6 | | MUST-class audit write path (`IAuditStore`, `IAuditStateCapture`) | Phase 02a Packet 9 | Shape fixed by ADR-0033 + ADR-0044; `audit_log` ships plain, unpartitioned | | Public read-only transaction mode and host ceiling | P02d-4 | ADR-0052 Accepted; P02d-4 Step 1 delivers host admission, transaction modes and app-role write-refusal proofs; Step 2 adds site endpoints and structural dispatch/Off/persistence guards; Steps 3–4 deliver Education reads and contract/SDK/CI proofs | | Outbox / background-job correlation propagation | Phase 02b | Trusted outbox/job rows and delivery/`JobExecutor` restoration; Hangfire hints remain opaque | diff --git a/docs/decisions/0032-exception-handling-logging-and-observability.md b/docs/decisions/0032-exception-handling-logging-and-observability.md index fbf4f076e..827f5a789 100644 --- a/docs/decisions/0032-exception-handling-logging-and-observability.md +++ b/docs/decisions/0032-exception-handling-logging-and-observability.md @@ -858,3 +858,92 @@ uses fixed bounded descriptors, below-filter vendor guards and a bounded log provider. Pipeline order, HTTP/event origins and the full W3C traceparent contract remain. P02b-4 supplies implementation and dirty/clean proof controls; none is claimed delivered by acceptance. + +### Amendment 6 — Sensitive exception-message diagnostic (2026-10-25) + +**Status: Accepted.** The maintainer approved the revised +[P02b-8 package](../roadmap/phase-02b-delivery-log.md#p02b-8-decision-package-2026-10-25) +at `486588d9`. This additive diagnostic leaves the original Decision, acceptance +metadata, pipeline and `LS0001` contract intact. Acceptance precedes code and +claims no analyzer implementation or phase-exit qualification. + +- **Identity:** `LS0002`, rule name + `LearnStackException-SensitiveExceptionMessage`, category `Security`, enabled + by default. Diagnostic text is fixed remediation, without a secret value or + rendered expression. +- **Scope:** all production C# projects recursively under `backend/src`, + including API, SharedKernel, module layers, infrastructure and Seeder, with + automatic coverage for new production projects. Analyzer/test projects and + generated code are excluded. Loading the shared analyzer assembly outside + Domain/Application must not broaden `LS0001`'s existing scope. +- **Thrown forms:** direct construction of `System.Exception` itself or a + transitively derived type in a throw statement/expression; aliases, + target-typed construction, parentheses and conversions are covered. Exception + identity is semantic, not a type-name suffix. +- **Expressions:** inspect string-valued constructor arguments, regardless of + argument position, for direct sensitive references, interpolation holes and + built-in string concatenation, after unwrapping parentheses/conversions. + Within those forms, evaluated local/parameter/field/property names use the + canonical word matcher; named constants are not exempt. Literal text, + `nameof`, `typeof` and method/type names are not sensitive value references. + Other root expression forms are outside this initial contract. +- **One token source:** an internal framework-compatible helper under + SharedKernel/Secrets owns both token sets and the existing word matcher; its + source is compiled into runtime and analyzer. The public runtime facade keeps + its matching behavior and exposes an immutable complete union snapshot. + The analyzer acquires neither a net10 runtime dependency nor a duplicate + public type. +- **Severity:** Warning, including `CI=true`, through Phase 02b. `LS0002` joins + `WarningsNotAsErrors`, never `NoWarn`. At Phase 03 exit both `LS0001` and + `LS0002` become Errors and leave that exemption after their scoped call sites + and the solution build satisfy that exit gate. + +This name-based guard is not taint analysis: prior assignments, exception +factories, rethrows of existing objects, formatting helpers, literal secrets and +dictionary string keys are outside coverage. Renaming a value can evade it; +derived metadata such as `token.Length` inside interpolation may warn. It +covers no TypeScript/JavaScript tooling or BFF code. Existing runtime redaction, +closed diagnostics and bounded durable descriptors remain necessary. + +Acceptance registers the catalogue and analyzer release row before code. +Compiler-clean positive/negative cases, diagnostic severity/location and no +`AD0001`, complete single/two-word union and a two-word-only mutation, evaluated production/new +project wiring, preserved `LS0001` scope, and an actual CI-warning build with an +unrelated-warning failure control are required proofs. The package specifies +the four implementation steps and their independent review rounds. Standards +09/11/21, Phase 03's escalation reference and the analyzer comments carry this +contract; no existing Accepted body or earlier amendment is rewritten. + +### Amendment 7 — Diagnostic wiring and proof clarifications (2026-10-25) + +This clarification preserves the maintainer-approved +[G16 package](../roadmap/phase-02b-delivery-log.md#g16-proposal--additive-adr-0032-amendment) +at `486588d9`; it selects no new diagnostic or redaction policy. + +- Amendment 6's “through Phase 02b” describes that packet's severity, not an + earlier promotion. Both diagnostics remain Warning until the Phase 03 exit + gate named in its next sentence. Standards 09/11/21, Phase 03 and compiler + wiring use that same gate. +- Automatic `backend/src/Directory.Build.props` wiring replaces Amendment 1's + per-project reference mechanism, while preserving its Domain/Application-only + `LS0001` scope. The reference and its importing item group are unconditional; + `ReferenceOutputAssembly="false"` keeps the analyzer out of runtime references. +- Inside supported message roots, inspect evaluated descendants but skip + `nameof`, `typeof`, literals and deferred lambda/local-function bodies. + A formatting-helper invocation as the root stays outside coverage; the same + evaluated reference inside an interpolation is within coverage. `params` + arrays, non-string inner exceptions, object initializers and constructor + `base(...)` initializers are not directly thrown string arguments. +- Production corpus checks include suppressed reports. A justified local + public-metadata exception must be reviewed at its exact site; project-wide + `NoWarn`, disabled analyzer execution or reduced editorconfig severity cannot + replace the rule. The current production corpus needs no local exception. +- Generated code keeps Amendment 6's exclusion. Roslyn generation conventions + are not a confidentiality boundary. Name matching remains conservative about + value types and does not expand plural, numeric-suffix or unsplit compound + matching. Runtime matching behavior is unchanged. Review must cover these + limits before Phase 03's Error promotion. + +The catalogue names the compiler, corpus, build-settings and planted controls. +Carrier corrections in Standards 02/09/11/17/21, the backend-module/foundation +skills and the phase-exit index make that unchanged contract discoverable. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index f5aa3c31f..47ec0bb51 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -38,9 +38,10 @@ claims no job runtime or enforcement. and supersedes only two ADR-0047 same-pool progress readings during generation draining. [ADR-0047 Amendment 2](0047-transactional-background-job-runtime.md#amendment-2--owned-server-lifecycle-and-bounded-availability-supersession-2026-10-16) discloses that bounded change; [ADR-0058 Amendment 2](0058-bounded-stock-hangfire-maintenance.md#amendment-2--independent-shared-component-ownership-2026-10-16) -adds shared-component ownership navigation only. Local implementation/reviews are -complete; the [P02b-4 closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-local-closeout-2026-10-18) -owns outstanding hosted CI/PR qualification. Phase 11 owns production qualification. +adds shared-component ownership navigation only. [Phase 02b](../roadmap/phase-02b-events-auth.md) +owns current packet state; the +[P02b-4 merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) +records hosted qualification. Phase 11 owns production qualification. ## Active ADRs @@ -75,7 +76,7 @@ owns outstanding hosted CI/PR qualification. Phase 11 owns production qualificat | 0029 | [Object Storage — SeaweedFS](0029-object-storage-seaweedfs.md) | Self-hosted SeaweedFS behind the existing `IStorageProvider` S3 contract; partially supersedes ADR-0002's MinIO row | | 0030 | [Redis-compatible Store — Valkey](0030-redis-compatible-store-valkey.md) | Valkey (Linux Foundation, BSD-3-Clause) for the cache + Dapr state-store backend; RESP-protocol drop-in; partially supersedes ADR-0002's Redis row | | 0031 | [PostgreSQL — Start on 18.x](0031-postgresql-major-version.md) | Pin primary RDBMS major version to PostgreSQL 18; native `uuidv7()` + async I/O + longest LTS runway; partially supersedes ADR-0002's PostgreSQL row | -| 0032 | [Exception Handling, Logging, and Observability](0032-exception-handling-logging-and-observability.md) | `IExceptionHandler` + 8-step MediatR pipeline + `Result.Fail`-only validation + `DomainException`-is-bug discipline + `IProviderResilience` (Polly v8) + Sentry vs OTel error capture boundary + Serilog primary + `TenantContextSpanProcessor` + `IErrorTrackingProvider` deployment-mode branching. [Amendment 4 (2026-10-12)](0032-exception-handling-logging-and-observability.md#amendment-4--bounded-producer-supersession-by-adr-0057-2026-10-12) discloses ADR-0057's bounded supersession of step-7 completion and the two separate `event_id` requirements; other clauses remain Accepted. | +| 0032 | [Exception Handling, Logging, and Observability](0032-exception-handling-logging-and-observability.md) | `IExceptionHandler` + 8-step MediatR pipeline + `Result.Fail`-only validation + `DomainException`-is-bug discipline + `IProviderResilience` (Polly v8) + Sentry vs OTel error capture boundary + Serilog primary + `TenantContextSpanProcessor` + `IErrorTrackingProvider` deployment-mode branching. [Amendment 4 (2026-10-12)](0032-exception-handling-logging-and-observability.md#amendment-4--bounded-producer-supersession-by-adr-0057-2026-10-12) discloses ADR-0057's bounded supersession of step-7 completion and the two separate `event_id` requirements; other clauses remain Accepted. [Amendment 5 (2026-10-15)](0032-exception-handling-logging-and-observability.md#amendment-5--trusted-job-origins-and-bounded-diagnostics-2026-10-15) adds trusted job origins and bounded diagnostics. [Amendment 6 (2026-10-25)](0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25) adds the bounded LS0002 contract and automatic production wiring; [Amendment 7](0032-exception-handling-logging-and-observability.md#amendment-7--diagnostic-wiring-and-proof-clarifications-2026-10-25) clarifies its unchanged escalation and proof boundaries. | | 0033 | [Audit Durability Model](0033-audit-durability-model.md) | **Supersedes ADR-0016.** MUST-class audit written as durable intent inside the business transaction (fails closed); SHOULD/MAY-class stays best-effort; corrected partitioned `audit_log` primary key; `AuditConfig` cannot remove baseline MUST coverage. **Amendment 1 (2026-08-18):** a standalone MUST write failure changes the response only when the operation would otherwise have succeeded. **Amendment 2 (2026-09-07)** meets the code that shipped after it: intents are **plural**, one per audited resource, because one command already writes two; only the **owning** unit-of-work frame writes them and reports the commit boundary, so a nested `Send` cannot claim durability nothing committed; `outcome` closes at four values and the writer supplies `timestamp`, which is what keeps the deliberate duplicate-id pair legal under `(id, timestamp)`; both standalone writers announce **two** session variables, measured — an org-scoped `denied` row is refused without the second; a fourth write method serves `EnterPlatformAdminScope`; and a read-sensitive query **does** reach step 6, since Packet 6's `TransactionBehavior` has no request-kind gate. Decided by [ADR-0044](0044-audit-write-path.md). **Amendment 3 (2026-09-08)** gives the audit health check an owner and demand-gates the deployment-level stop-serving backstop to Phase 11 with a written trigger: stopping a process is the one operational act the next request cannot undo, and Phase 02a has neither a readiness surface nor an operator to answer the page it would raise. **Amendment 4 (2026-09-08):** a tenant override narrows and never elevates, a cancelled `COMMIT` is `Indeterminate`, and the override loader runs on a cache miss. **Amendment 5 (2026-09-11):** `EnterPlatformAdminScope` never reaches `WriteStandaloneAsync`, and a nested request's refusal outlives the commit it joined. **Amendment 6 (2026-09-11):** the audit health check answers only whether a MUST-class row can be written; a tenant-override read failure is its `Error` line alone. **Amendment 7 (2026-09-11):** a request refused at step 1 writes no audit row — validation runs before the audit step classifies anything — so the standalone path is reached by a short-circuit at step 4 or 5, the assertion recorder and the reconcile. [Amendment 8 (2026-10-12)](0033-audit-durability-model.md#amendment-8--common-audit-ownership-outside-mediatr-2026-10-12) clarifies common audit ownership outside MediatR under ADR-0057; durability and classification contracts survive. [Amendment 10 (2026-10-15)](0033-audit-durability-model.md#amendment-10--same-transaction-job-terminal-audit-2026-10-15) adds same-transaction job-terminal audit under ADR-0047. | | 0034 | [Hub Contract Surface Invariant](0034-hub-contract-surface-invariant.md) | Replaces "closed at four endpoints" with two enforceable invariants (Hub stores no tenant content; every crossing goes through a named adapter); enumerates the real endpoint set; TLS key material leaves the entitlement payload; host resolution never calls the Hub | | 0035 | [Demand-Gated Infrastructure](0035-demand-gated-infrastructure.md) | The one-way-door test; ports + default implementations ship now, vendor adapters ship on a named trigger in a named phase; uncontracted deployment modes may not decide technical choices | diff --git a/docs/glossary.md b/docs/glossary.md index f1d5e5847..1778dfb52 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -245,6 +245,8 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | Term | Definition | |------|------------| +| **Durable asynchronous store** | Persisted event/job envelope, execution or completion history that outlives its request/process, including linkable control identifiers. The [canonical inventory](architecture/23-data-protection.md#durable-asynchronous-store-inventory) distinguishes those stores from ordinary module tables and volatile BFF custody. | +| **Retained copy** | A separate provider, diagnostic, database/WAL or backup copy whose removal is not established by deleting its source row or invalidating a local session. Its retention and completion evidence belong to the inventory's named owner. | | **PII Category** | One of `PII-Identity`, `PII-Behaviour`, `PII-Sensitive`, `Payment`, `Audit`. Each category has its own redaction, retention, and erasure rules. | | **Data Controller** | The tenant. Decides what personal data is collected and why. | | **Data Processor** | LearnStack. Processes personal data on the controller's instructions. | diff --git a/docs/modules/audit/audit.md b/docs/modules/audit/audit.md index c39cf94bc..0b476b252 100644 --- a/docs/modules/audit/audit.md +++ b/docs/modules/audit/audit.md @@ -56,7 +56,7 @@ each, rather than two more verbs on `event`, which is the resource a tenant read | `event_export` | `audit.event_export.read` `(planned)` | **MUST** | Collecting the file is a separate act from asking for it, often by a different principal and always at a different time. Two grants in [permissions.md](permissions.md), two rows here | | `config` | `audit.config.write` `(planned)` | **MUST** | A tenant narrowed its own SHOULD/MAY coverage. Recording it is what keeps the narrowing itself visible — an override that could be set without a trace would be the first move of anyone reducing what the log will show. The floor holds regardless: `ClassifyAsync` re-applies the catalogue's MUST after the override ([ADR-0033](../../decisions/0033-audit-durability-model.md)) | | `config` | `audit.config.delete` `(planned)` | **MUST** | The override removed, restoring baseline coverage. Recorded for the same reason and with the same weight as setting it: a reader of the log must be able to reconstruct what coverage was in force at any moment | -| `redaction` | `audit.redaction.apply` `(planned)` `(off-path)` | **MUST** (`security-event`) | The GDPR erasure path of [Audit Subsystem § 10](../../architecture/31-audit-subsystem.md), restricted by the column grant to `actor_email`, `ip_address`, `user_agent`, `before_state`, `after_state`, `changes`. `actor_user_id` is deliberately never redacted — after erasure it is an orphan surrogate with no path to a natural person, which is what keeps the row's existence auditable. `(off-path)`: it runs as `learnstack_platform` inside `EnterPlatformAdminScope(reason)`, so there is no request type to key a catalogue entry on | +| `redaction` | `audit.redaction.apply` `(planned)` `(off-path)` | **MUST** (`security-event`) | The GDPR erasure path of [Audit Subsystem § 10](../../architecture/31-audit-subsystem.md), restricted by the column grant to `actor_email`, `ip_address`, `user_agent`, `before_state`, `after_state`, `changes`. `actor_user_id` is deliberately never redacted — it remains a pseudonymous, potentially linkable identifier. Phase 03's bounded first-writer decision must address surviving references before claiming complete anonymisation. `(off-path)`: it runs as `learnstack_platform` inside `EnterPlatformAdminScope(reason)`, so there is no request type to key a catalogue entry on | | `purge` | `audit.purge.apply` `(planned)` `(off-path)` | **MUST** (`security-event`) | Retention removed rows. One row per purge run rather than per deleted row, carrying the range and the count — a per-row record of a per-row deletion is a log that grows faster than the purge shrinks it. It stays a row-level `DELETE` after [Phase 11](../../roadmap/phase-11-production-hardening.md) partitioning — one monthly partition holds many tenants and retention classes — and dropping a whole partition past the platform's maximum retention is [ADR-0028](../../decisions/0028-audit-log-partition-management.md)'s separate partition-management job. `(off-path)` for the same reason as redaction | ## What is deliberately not here diff --git a/docs/modules/tenancy/README.md b/docs/modules/tenancy/README.md index 43499b42d..5c0a23910 100644 --- a/docs/modules/tenancy/README.md +++ b/docs/modules/tenancy/README.md @@ -256,7 +256,9 @@ projection. The framework reads only the minimal columns allowed by tenantless orchestration constructs no Tenancy service and accepts no arbitrary tenant selector. The additive Tenancy migration owns this SELECT-only grant. The [Step 8 record](../../roadmap/phase-02b-delivery-log.md#p02b-4-step-8--durable-recurrence-and-restricted-fan-out-2026-10-18) -owns implementation and pending complete qualification. +records implementation; the +[merge closeout](../../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) +records its complete source-bound qualification. ## Entity-relationship diagram diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 47afc5c77..32dae7b23 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -154,7 +154,7 @@ unmarked row is one a shipped command already raises. | `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 | -| 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: `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 | +| 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 | 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/roadmap/README.md b/docs/roadmap/README.md index efb2db5e2..0b9d4caed 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -49,9 +49,8 @@ not deferred to the showcase phase. packet's merge closeout; the [individual exit evidence](phase-02d-exit-evidence.md) maps each exit criterion to its proof. - [Phase 02b: Events, Background Jobs, Identity, and Session](phase-02b-events-auth.md) - — **in progress**: P02b-0–5 complete and merged through PRs #29–#33; P02b-6's - implementation merged through PR #34. Its Status block owns remaining packet - state and current delivery. + — **in progress**. Its Status block owns packet state and links current + decisions, delivery evidence and the remaining exit work. - [Phase 03: Identity Domain, Authorization, and Admin Foundation](phase-03-identity-admin.md) - [Phase 04: Headless CMS, Page Builder, and Media Library](phase-04-cms-media-pages.md) - [Phase 05: Education Catalog and Learning Content](phase-05-education-learning-content.md) diff --git a/docs/roadmap/phase-02b-delivery-log.md b/docs/roadmap/phase-02b-delivery-log.md index 7071aa595..25abf4d43 100644 --- a/docs/roadmap/phase-02b-delivery-log.md +++ b/docs/roadmap/phase-02b-delivery-log.md @@ -196,7 +196,7 @@ each packet decided and delivered, as - [P02b-6 pending aggregate metadata acquisition (2026-10-22)](#p02b-6-pending-aggregate-metadata-acquisition-2026-10-22) — 110 lines - [P02b-6 hosted browser dependency removal (2026-10-23)](#p02b-6-hosted-browser-dependency-removal-2026-10-23) — 45 lines - [P02b-6 correction merge and closeout (2026-10-23)](#p02b-6-correction-merge-and-closeout-2026-10-23) — 19 lines -- [P02b-7 — BFF session](#p02b-7--bff-session) — 3,133 lines +- [P02b-7 — BFF session](#p02b-7--bff-session) — 3,179 lines - [P02b-7 decision package (2026-10-23)](#p02b-7-decision-package-2026-10-23) — 213 lines - [P02b-7 proposal review round 1 (2026-10-23)](#p02b-7-proposal-review-round-1-2026-10-23) — 35 lines - [P02b-7 proposal review round 2 (2026-10-23)](#p02b-7-proposal-review-round-2-2026-10-23) — 26 lines @@ -265,6 +265,37 @@ each packet decided and delivered, as - [P02b-7 observer correction review round 1 (2026-10-24)](#p02b-7-observer-correction-review-round-1-2026-10-24) — 24 lines - [P02b-7 observer correction review round 2 and source freeze (2026-10-24)](#p02b-7-observer-correction-review-round-2-and-source-freeze-2026-10-24) — 26 lines - [P02b-7 review correction qualification (2026-10-24)](#p02b-7-review-correction-qualification-2026-10-24) — 83 lines + - [P02b-7 merge and closeout (2026-10-25)](#p02b-7-merge-and-closeout-2026-10-25) — 46 lines +- [P02b-8 — Exit enforcement](#p02b-8--exit-enforcement) — 1,288 lines + - [P02b-8 decision package (2026-10-25)](#p02b-8-decision-package-2026-10-25) — 246 lines + - [P02b-8 proposal review round 1 (2026-10-25)](#p02b-8-proposal-review-round-1-2026-10-25) — 24 lines + - [P02b-8 proposal review round 2 (2026-10-25)](#p02b-8-proposal-review-round-2-2026-10-25) — 32 lines + - [Correction verification (2026-10-25)](#correction-verification-2026-10-25) — 10 lines + - [P02b-8 acceptance (2026-10-25)](#p02b-8-acceptance-2026-10-25) — 27 lines + - [P02b-8 Step 1 — Sensitive exception analysis and compiler scope (2026-10-25)](#p02b-8-step-1--sensitive-exception-analysis-and-compiler-scope-2026-10-25) — 43 lines + - [P02b-8 Step 1 review round 1 (2026-10-25)](#p02b-8-step-1-review-round-1-2026-10-25) — 26 lines + - [P02b-8 Step 1 review round 2 and closeout (2026-10-25)](#p02b-8-step-1-review-round-2-and-closeout-2026-10-25) — 21 lines + - [P02b-8 Step 2 — Independent asynchronous inventory coverage (2026-10-25)](#p02b-8-step-2--independent-asynchronous-inventory-coverage-2026-10-25) — 30 lines + - [P02b-8 Step 2 review round 1 (2026-10-25)](#p02b-8-step-2-review-round-1-2026-10-25) — 36 lines + - [P02b-8 Step 2 review round 2 (2026-10-25)](#p02b-8-step-2-review-round-2-2026-10-25) — 34 lines + - [P02b-8 Step 2 closeout (2026-10-25)](#p02b-8-step-2-closeout-2026-10-25) — 16 lines + - [P02b-8 Step 3 — Delivered carriers and catalogue reconciliation (2026-10-25)](#p02b-8-step-3--delivered-carriers-and-catalogue-reconciliation-2026-10-25) — 44 lines + - [P02b-8 Step 3 review round 1 (2026-10-25)](#p02b-8-step-3-review-round-1-2026-10-25) — 19 lines + - [P02b-8 Step 3 review round 2 and closeout (2026-10-25)](#p02b-8-step-3-review-round-2-and-closeout-2026-10-25) — 22 lines + - [P02b-8 Step 4 — Individual exit ownership and source freeze (2026-10-25)](#p02b-8-step-4--individual-exit-ownership-and-source-freeze-2026-10-25) — 42 lines + - [P02b-8 Step 4 review round 1 — source (2026-10-25)](#p02b-8-step-4-review-round-1--source-2026-10-25) — 22 lines + - [P02b-8 Step 4 review round 2 — source (2026-10-25)](#p02b-8-step-4-review-round-2--source-2026-10-25) — 31 lines + - [P02b-8 Step 4 — Completed-source qualification and review closeout (2026-10-25)](#p02b-8-step-4--completed-source-qualification-and-review-closeout-2026-10-25) — 109 lines + - [P02b-8 PR correction verification (2026-10-25)](#p02b-8-pr-correction-verification-2026-10-25) — 93 lines + - [P02b-8 correction review round 2 and source freeze (2026-10-25)](#p02b-8-correction-review-round-2-and-source-freeze-2026-10-25) — 44 lines + - [P02b-8 CI fixture-witness reconciliation (2026-10-25)](#p02b-8-ci-fixture-witness-reconciliation-2026-10-25) — 24 lines + - [P02b-8 CI witness and SQL-literal corrections, review round 1 (2026-10-25)](#p02b-8-ci-witness-and-sql-literal-corrections-review-round-1-2026-10-25) — 52 lines + - [P02b-8 CI corrections, review round 2 and source freeze (2026-10-25)](#p02b-8-ci-corrections-review-round-2-and-source-freeze-2026-10-25) — 21 lines + - [P02b-8 native completion qualification correction, review round 1 (2026-10-25)](#p02b-8-native-completion-qualification-correction-review-round-1-2026-10-25) — 43 lines + - [P02b-8 native completion correction, review round 2 and freeze (2026-10-25)](#p02b-8-native-completion-correction-review-round-2-and-freeze-2026-10-25) — 17 lines + - [P02b-8 browser artifact ownership correction, review round 1 (2026-10-25)](#p02b-8-browser-artifact-ownership-correction-review-round-1-2026-10-25) — 44 lines + - [P02b-8 browser ownership correction, review round 2 and freeze (2026-10-25)](#p02b-8-browser-ownership-correction-review-round-2-and-freeze-2026-10-25) — 19 lines + - [P02b-8 PR correction qualification and closeout (2026-10-25)](#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) — 105 lines - [Status archive](#status-archive) — 112 lines @@ -20900,6 +20931,1340 @@ that later documentation-only commit. PR #36 remains the maintainer review/merge gate; no merge is performed here. +### P02b-7 merge and closeout (2026-10-25) + +Read-only GitHub verification confirms +[PR #36](https://github.com/HodeTech/LearnStack/pull/36) merged at +`2026-10-24T22:16:17Z` (2026-10-25 in Europe/Istanbul), squash commit +`0dfade02a08fce6bd937fe0554f94f47c571ca8e`. Its source is +`6b6f0629eac05bd9fe6e63a3185dee1e9ba42c15`. Fetching the merge confirms both +commits have tree `99098202a0a687cd54d2848f0fcd438bc8862824`; their file contents +are identical. + +The [preceding qualification](#p02b-7-review-correction-qualification-2026-10-24) +owns the implementation source's complete A/1 and B/2 evidence in +[run 40120289765](https://github.com/HodeTech/LearnStack/actions/runs/40120289765). +The documentation-only final PR head additionally passes its complete current-head +assignment in +[run 40124028474](https://github.com/HodeTech/LearnStack/actions/runs/40124028474): +27 successful jobs and all seven required contexts. Retained-evidence verification +before merge confirms the same manifest, plan, captured toolchains and population: +5,931 .NET cases and 2,376 frontend cases, zero skips, all 20 natural producer +cleanups, nine demo navigations and 27 Lighthouse reports. This merge closeout +rechecks run metadata and tree equality; it does not rerun tests or claim a new +post-merge execution. + +All five implementation steps, their two independent review rounds, and the +subsequent verified correction bundles are closed. Accepted +[ADR-0070](../decisions/0070-owned-tenant-bff-sessions.md) and +[ADR-0071](../decisions/0071-uncertain-account-site-refusals.md) govern the shipped +native credential owner, host-only opaque cookies, guarded Studio/Portal +scaffolds, CSRF/Origin admission, refresh/logout and uncertain ordinary AccountSite +401 handling. Anonymous public rendering remains independent of sign-in. + +The actual warm Keycloak/BFF/application-role API proof and the separate +controlled-grant/API browser cookie/history proof retain their recorded scopes. +[Phase 06](phase-06-renderer-admin-studio.md) owns full browser-driven OIDC +journeys and Studio/Portal business functionality; +[Phase 03](phase-03-identity-admin.md) owns membership/authorization and the +identity-event ingress; [Phase 11](phase-11-production-hardening.md) owns +production/distributed session qualification. This merge does not broaden those +claims or erase earlier failed runs and evidence limits. + +P02b-7 is complete. The next packet is P02b-8: accept G16's `LS0002` contract +before its implementation, complete G18's erasure inventory, reconcile remaining +carriers and verify the catalogue, exact required-check names and phase exit +criteria. No P02b-8 decision is accepted or implementation started by this +documentation closeout; Phase 02b remains in progress. + +## P02b-8 — Exit enforcement + +### P02b-8 decision package (2026-10-25) + +**Accepted — 2026-10-25.** The maintainer approved the reviewed package at +`486588d9` and its four implementation steps. The +[acceptance record](#p02b-8-acceptance-2026-10-25) identifies the installed gate +vehicles; the re-verified baseline is +`0d0696acf06b35d45ba2456197dfc2dd2f4ff798` on `development`. Earlier review +receipts retain their pre-acceptance state. + +**Problem and scope.** Finish the compile-time secret-message guard, inventory +the durable copies this phase actually introduced, reconcile their carriers and +qualify the phase exit against the final source. No business feature, provider, +permission, persistence privilege or retention policy changes here. + +#### Re-verified premises + +- G16 is still Open; `backend/analyzers/LearnStack.Analyzers` contains only + `LS0001`. Its consuming projects cover Domain/Application, excluding the API, + SharedKernel, infrastructure and Seeder where credentials are handled. +- `SensitiveTokenCatalog.IsSensitive` consumes single-word and two-word sets; + `DefaultTokens` currently exposes only the first. `authheader`, + `authenticationheader` and `setcookie` demonstrate the omitted second-set + coverage. Runtime property redaction does not scrub exception messages. +- Current event/job failure stores persist closed bounded descriptors, rather + than arbitrary exception messages. `LS0002` complements those controls; it + does not replace them or certify that existing sinks contain raw messages. +- G18's historical four-store count is insufficient: three event stores, seven + LearnStack job tables and twelve guarded vendor tables now exist. Durable + provider events and new actor references in existing audit storage also need + explicit treatment. The BFF session store is volatile, not a durable ledger. +- All 62 existing Phase 02b catalogue obligations are marked Implemented: 43 + explicit Phase entries plus 19 inherited under the P02b-4 section. `LS0002` + has no entry, so checking only existing statuses would miss it entirely. +- A local Release run of `CorpusConsistencyTests` passes 5/5, with zero skips. + This baseline checks corpus mechanics, not P02b-8 implementation or exit. +- Three read-only audits cover analyzer/security, storage/erasure, and catalogue/ + CI/carrier obligations. Their verified corrections and limits are captured in + this package; implementation and its two review rounds per step remain pending. + +#### G16 proposal — additive ADR-0032 amendment + +G16 already names its vehicle: a dated amendment to +[ADR-0032](../decisions/0032-exception-handling-logging-and-observability.md), +plus the catalogue and release record. No new ADR number is needed. Acceptance +appends the following bounded contract as the next free amendment; the existing +body, acceptance metadata, pipeline and `LS0001` decision remain unchanged. + +**Proposed amendment: Sensitive exception-message diagnostic.** + +- **Identity:** `LS0002`, human-readable rule name + `LearnStackException-SensitiveExceptionMessage`, category `Security`, enabled + by default. A diagnostic uses fixed remediation text and never includes the + interpolated value or rendered expression. +- **Scope:** every production C# project recursively under `backend/src`, + including all module layers, API, SharedKernel, infrastructure and Seeder. + Analyzer/test projects and generated code are excluded. Wiring must reach + future production projects automatically. Broadening the assembly reference + must not broaden `LS0001` beyond its existing Domain/Application projects. +- **Thrown forms:** direct construction of `System.Exception` itself or a type + transitively derived from it in a throw statement or throw expression, + including aliases, target-typed construction, parentheses and conversions. + A type-name suffix does not establish exception identity. +- **Expressions:** inspect string-valued constructor arguments for direct + sensitive value references, interpolation holes and built-in string `+` + concatenation, after unwrapping parentheses/conversions. Other root expression + forms are outside the initial rule. Within these forms, inspect evaluated + local, parameter, field and property names through the canonical word matcher. + Named constant locals/fields are not exempt when their names match; literal + text is not inspected for secret contents. Argument position is irrelevant; the + provider exception's message is not its first parameter. `nameof`, `typeof`, + method/type names and literal text are not sensitive value references. +- **Token source:** extract the existing token sets and word matcher into one + internal framework-compatible source under SharedKernel/Secrets, compiled + into both SharedKernel and the netstandard2.0 analyzer. Keep the public runtime + facade and its matching behavior; expose an immutable complete union snapshot. + No runtime dependency or second public type is added to the analyzer. +- **Severity:** Warning throughout this packet; append `LS0002` to + `WarningsNotAsErrors`, never `NoWarn`. At + [Phase 03 exit](phase-03-identity-admin.md#cross-cutting-follow-up-at-phase-exit), + both `LS0001` and `LS0002` become Errors and leave `WarningsNotAsErrors`, after + their scoped call sites and the solution build satisfy that exit gate. + +This is a name-based source guard, not taint analysis or a secrecy guarantee. +Earlier assignments, exception factories, `throw existingException`, formatting +helpers, literal secrets and dictionary string keys are outside its initial +coverage. Renaming a value can evade it; metadata such as `token.Length` inside +an interpolation can conservatively warn. TypeScript/JavaScript BFF and realm +tooling remain under their existing closed diagnostic and runtime controls. + +**Options considered.** Domain/Application-only coverage misses actual credential +handlers. An independent analyzer token list invites drift. Referencing net10 +SharedKernel from its analyzer creates a framework/dependency problem. Full taint +analysis adds a materially different contract; it is not claimed by this rule. +Interpolation-only detection misses ordinary concatenation and direct string +arguments. The proposed bounded forms cover those without tracing prior values. + +**Required proofs:** compiler-clean positive/negative compilations, exact Warning +ID/name/location and no `AD0001`; throw statement/expression, aliases, argument +order, members, direct references, interpolation and string concatenation; +both `System.Exception` itself and a derived exception; sensitive and ordinary +named constants. Non-sensitive names, literal text/`nameof`/`typeof`, sensitive +expressions outside a throw and fixed messages with a cancellation-token argument +remain clean. Prove the complete single/two-word union independently. Include a +two-word-only addition exposing a stale or single-set-only analyzer view. Do not mutate +global static token sets during concurrent tests. Evaluated MSBuild wiring must +include API/infrastructure and a planted new project, while preserving `LS0001`. +A disposable real build with `CI=true` must report `LS0002` as a Warning and +succeed; an unrelated ordinary warning must still fail that build. + +#### G18 proposal — complete inventory, unchanged erasure authority + +[Data Protection § Right to Erasure](../architecture/23-data-protection.md#right-to-erasure-right-to-be-forgotten) +owns the inventory. The first acceptance commit installs the concrete matrix +below there and reconciles its Phase 03/11 handoffs and immutable/grant limits, +before either gate is marked Accepted or Step 1 writes code. Accepting a future +inventory scope alone does not close G18. Step 2 independently verifies that +carrier against storage and implements its drift control. Identifier-only data +can still identify a person; absence of free text is not an erasure exemption. + +| Store family | Copies and subject linkage the inventory must cover | +|---|---| +| `outbox_messages` | `actor_user_id`, identifier-only `payload`, tenant/org, partition/causation/event IDs and `correlation_id`; new producer `metadata` is SQL NULL. Platform may SELECT/DELETE, not rewrite envelope fields | +| `event_deliveries` | Independent per-subscription envelope/`payload` copy with `actor_user_id`, tenant/org, causation/trace/partition and replay state. Platform has no grant; producer cleanup cannot erase this copy | +| `inbox_messages` | `(tenant_id, subscription_id, event_id)` and `recorded_at`; indirect subject linkage without actor/payload/org columns. Immutable completion history; no generic Platform purge | +| `background_jobs` | `causal_actor_user_id`, identifier-only `parameters`/`plan`, trace/causation, parent/recipient/operation and final-attempt links. Envelope/prepared facts stay immutable; uncertain effects retain occupancy | +| `background_job_attempts` | `job_id`, identifier-only `outcome`, operation/quiescence IDs, fingerprint, selected-outcome link and finite `failure_policy`. Write-once retry/effect/cleanup facts are not a mutable person profile | +| `background_job_capacity` | `tenant_id`, finite capacity-group key and timestamp only. Coordination metadata, not person content or a person-erasure target | +| `background_job_reservations` | Tenant/job/attempt linkage, finite group and reservation/release facts. Erasure never proves quiescence or frees unresolved occupancy | +| `background_job_recurrences` | Finite definition/revision/manifest/target/schedule/recipient-policy metadata; no user or arbitrary parameters. Infrastructure control, no ordinary app access | +| `background_job_occurrences` | Manifest/slot identity and frozen tenant/org sweep bounds/checkpoints; no person column or arbitrary payload. Preserve occurrence history and monotonic progress | +| `background_job_recipients` | Immutable tenant/org route, occurrence/manifest/target and accepted child-job receipt. Recipient means a tenant/org route, not a person; restricted reciprocal job links affect future purge order | +| Guarded Hangfire schema-23 storage | All twelve tables from `HangfireStorageContract.Columns`; invocation/argument, parameter, state, queue, hash/list/set, server, counter and lock/control metadata; guards forbid business payload/credentials, but opaque identifiers remain linkable | +| Existing `audit_log` | New asynchronous terminal/causal metadata, including `causal_actor_user_id`, beside immutable actor/entity/causation identifiers; redacting human-facing fields alone does not remove every reference | +| Development Keycloak user events | Separate provider `EVENT_ENTITY`: subject `USER_ID`, `SESSION_ID`, `IP_ADDRESS`, client/realm and event-detail JSON. Selected events and qualified finite retention remain governed by ADR-0070; account invalidation does not erase past events | +| Diagnostics and backups | External log/trace/error archives and database/WAL/backup copies follow the existing data-protection and Phase 11 operational ownership; they are not silently erased by deleting a source row | + +The twelve vendor table names are `schema`, `counter`, `aggregatedcounter`, +`hash`, `job`, `state`, `jobqueue`, `list`, `server`, `set`, `jobparameter` and +`lock`, all in `public`. Schema bookkeeping and aggregate counters remain in the +inventory as explicit no-person-content/control classifications, rather than +disappearing from coverage. Provider storage is separate from LearnStack's DB. +The canonical definitions remain in +[Standards 05 § Outbox](../standards/05-database.md#outbox), +[Inbox](../standards/05-database.md#inbox), +[Background jobs](../standards/05-database.md#background-jobs) and +[guarded vendor storage](../standards/05-database.md#p02b-4-stock-hangfire-control-storage). +The inventory records references and constraints; it copies no SQL template. + +**Authority limits and handoff:** + +- P02b-8 implements no erasure, purge, payload rewrite or new storage grant. + It chooses no retention duration, principal, deletion order or replay reset. + Live/uncertain effects, immutable facts, deduplication floors, reservation + accounting and same-transaction MUST audit remain unchanged. +- Current inbox/delivery/job grants and guards do not give a generic platform + eraser permission to update/delete these records. BYPASSRLS does not bypass + SQL privileges, no-delete triggers or write-once facts. Phase 11's contrary + inbox-DELETE wording must be corrected, not implemented as an invented grant. +- The current audit redaction column grant excludes `metadata`. Phase 03's + first redaction/erasure writer must account for these surviving references and + obtain its own bounded decision before changing an immutable/audit boundary. + `actor_user_id` also remains immutable; the six currently redactable columns + are `actor_email`, `ip_address`, `user_agent`, `before_state`, `after_state` + and `changes`. Correct Architecture 23's broader actor-anonymisation wording + against this existing contract. This inventory does not declare that complete + anonymisation already works. +- Phase 03 retains its tenant-scoped DSAR export/erasure and separate global + account-closure implementation, identity mapping, request authority, and audit + redaction after its required bounded decision. This inventory transfers none + of those deliverables. Phase 11 completes the workflows across later modules + and retained copies, with purge/principal/retention, backup and operational + reconciliation. Both plans link this inventory and retain these preconditions + before a writer ships; ordinary SystemActor delivery or dispatcher credentials + are no substitute. +- Volatile BFF custody is explicitly distinguished from durable provider events. + Its local invalidation is not a claim to erase provider events or log archives. + +**Proof boundary:** register +`Durable_Async_Store_Inventory_Covers_The_Storage_Census` as structural coverage +under existing ADR-0046/0047/0057 obligations. Compare the documented LearnStack +table set and vendor classifications with their actual storage definitions; +missing or added tables and a removed inventory row must fail via planted +controls. This checks inventory coverage, not legal compliance, SQL erasure +correctness or arbitrary personal data hidden in values. Locator/mutability +accuracy remains independently reviewed against DDL and contracts. + +#### Current CI and inherited documentation checks + +Read-only GitHub checks on 2026-10-25 confirm `main` uses strict protection and +these seven exact required contexts, each bound to GitHub Actions app `15368`: + +1. `backend (build + unit + arch + contract)` +2. `frontend (typecheck + lint + build + test)` +3. `secret scan (leakwatch)` +4. `meta (compose + commit hygiene + link audit)` +5. `backend integration (Testcontainers)` +6. `openapi diff` +7. `public demo + lighthouse` + +The read-only paginated collaborator census finds one contributor with write +access. The inherited second-write-contributor trigger has not fired. Hand the +XML-documentation target-existence and changed-prose 88-column CI checks to +Phase 03 with that unchanged trigger; existing fragment lint is not a substitute. +No protection setting changes are proposed. + +#### Four implementation steps after acceptance + +Each step lands its implementation and commit, then two fresh independent review +rounds. Confirm findings against current code, fix and commit the verified ones, +and record the review scope, commit and validation. Continue automatically to +the next step unless a new decision or real blocker requires the maintainer. + +1. **Analyzer and compiler wiring.** After the acceptance commit, implement + `LS0002`, shared matching, release row, all-production wiring, + Warning posture and compiler/architecture/unit/mutation controls. Update + Standards 09/11/21, analyzer comments and Phase 03's severity reference. +2. **Inventory verification and drift proof.** Independently check the accepted + Architecture 23 matrix and Phase 03/11 handoffs against actual DDL, grants, + fields and copies; add the structural census and dirty controls. Preserve + schemas, grants, execution state and retention policy. G18's carrier is already + installed; this step supplies its implementation-level coverage control. +3. **Carrier and catalogue reconciliation.** Repair stale current-tense phase, + architecture, standard, skill, gateway and source-comment claims against + delivered code. Preserve Accepted bodies and append-only records. Audit every + Phase 02b obligation, including inherited P4 entries and frontend owners; + register/implement any verified missing proof before claiming exit. Keep the + provider-SDK rule with Phase 03's first real SDK subject. Transfer the unchanged + documentation-lint trigger and keep front doors as phase pointers. +4. **Source-bound qualification and exit evidence.** Run relevant local backend + and frontend suites, documentation/format/secret checks and applicable real + integration proofs. Qualify complete same-source A/B assignments under + ADR-0063; do not combine failed-only reruns or relabel P7 receipts as P8 runs. + Recheck exact live protection and zero skips, map every exit criterion to its + actual proof in a phase exit index, and prepare the review PR on development. + Keep actual warm-provider/BFF/API and controlled-browser proofs distinct from + Phase 06's full browser-driven OIDC suite. A failed or missing proof leaves the + packet/phase incomplete; user review and merge remain subsequent acts. + +The first acceptance commit appends ADR-0032's dated amendment, installs G18's +canonical Architecture 23 matrix, reconciles the Phase 03/11 prerequisites and +misleading purge/actor-anonymisation wording, and registers the diagnostic and +inventory rows. Only then does it record G16/G18 as Accepted and permit Step 1. +Every extension stays Registered until its owner and controls ship; existing +Implemented obligations do not become Registered merely because this packet +reviews them. No code has been changed by this proposal. + +### P02b-8 proposal review round 1 (2026-10-25) + +Two independent readers review `c0261cab` against `0d0696ac`: a +`gpt-6.1-sol`/xhigh analyzer/security reviewer and a `gpt-6-astra`/high +data/governance reviewer. Both inspect the proposed package and verify findings +against the governing code/DDL/records; neither modifies files or runs provider +tests. There is no runtime implementation to qualify yet. + +Three findings are verified and corrected before the next review: + +- Preserve Phase 03's existing DSAR export/erasure, global closure and audit + redaction implementation; Phase 11's retained-copy/operational work does not + acquire or defer those deliverables. +- Include `System.Exception` itself, not only derived types, in the proposed + diagnostic boundary and its positive tests. +- Distinguish clean literal text from named sensitive constants; named + const-local/field references remain subject to the same name matcher. + +The baseline Release checks additionally pass all 65 existing LS0001/token +catalogue unit cases and all five corpus cases, zero skips. Documentation +fragment/structure/index and whitespace checks pass. These are baseline and +proposal checks, not evidence that `LS0002` or an erasure workflow is implemented. +Acceptance and the fresh second proposal review remain pending. + +### P02b-8 proposal review round 2 (2026-10-25) + +Two new independent readers review `7e6e61ff` against `0d0696ac`: a +`gpt-6-astra`/high contract/data reviewer and a `gpt-6.1-sol`/xhigh +proof/execution reviewer. They recheck the proposed analyzer, inventory, +ownership, catalogue and qualification boundaries against current source and +Accepted records. The first finds no actionable issue; the second identifies +one verified acceptance-ordering gap. + +G18's vehicle is Architecture 23, not merely a future inventory promise in a +phase-doc package. The revised proposal requires its concrete canonical matrix, +the Phase 03/11 prerequisite corrections, ADR-0032 amendment and Registered rows +in the first acceptance commit, before either gate closes or Step 1 writes code. +Step 2 now supplies independent field/DDL/grant verification and the coverage +control. The proposed matrix also spells out each LearnStack job table and +distinguishes provider subject identity from LearnStack actor identity. + +Documentation fragment, structure, generated-index and whitespace checks pass. +Both reviewers' bounded recheck of this correction remains pending; no provider, +compiler-implementation or final hosted qualification is claimed. The package +and both gates remain Proposed/Open until maintainer acceptance. + +#### Correction verification (2026-10-25) + +Both second-round reviewers independently recheck `7e6e61ff..49b541c5` against +the current DDL and Accepted records. The acceptance-ordering finding is closed; +neither identifies a new actionable finding in the bounded correction. Table +classifications, preserved Phase 03 commitments and the absence of new erasure +authority remain explicit. This completes both proposal review rounds, not any +implementation review. Only maintainer acceptance of the proposed G16/G18 +answers and four-step plan remains before the acceptance commit and Step 1. + +### P02b-8 acceptance (2026-10-25) + +The maintainer explicitly approves the revised package at `486588d9` and directs +implementation. This acceptance installs the complete decision vehicles before +Step 1 changes any code: + +- [ADR-0032 Amendment 6](../decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25) + records `LS0002`'s identity, bounded forms, all-production C# scope, shared + tokens and Warning/Phase 03 escalation. The existing Decision, metadata and + `LS0001` Domain/Application contract are unchanged. +- [Architecture 23's canonical inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory) + covers the actual ten first-party event/job tables, twelve guarded vendor + tables, existing audit references, provider events and retained/external + copies. Phase 03/11 carriers preserve their respective DSAR/redaction and + retained-copy/purge operations, with immutable/grant preconditions explicit. +- Standards 21 registers the diagnostic and + `Durable_Async_Store_Inventory_Covers_The_Storage_Census`; the analyzer release + record registers `LS0002`. Both new catalogue obligations are Registered until + their implementation and controls ship. +- G16 and G18's inventory part are Accepted — 2026-10-25. Prior payload and + failure-descriptor decisions remain Accepted; this adds no erasure authority, + retention interval, grant or application permission. + +The four approved implementation steps follow on `development`, each with its +commit, two fresh independent review rounds and committed verified corrections. +No implementation or final-source CI/phase exit is claimed by this acceptance. + +### P02b-8 Step 1 — Sensitive exception analysis and compiler scope (2026-10-25) + +The acceptance commit is `4b29ea70`. This step implements `LS0002` under +ADR-0032 Amendment 6 without changing runtime exception handling or widening +`LS0001`'s Domain/Application scope. + +- An internal netstandard-compatible word matcher supplies runtime redaction and + analyzer source; the public facade retains matching behavior and returns the + cached immutable complete union. Loaded-assembly parity and all-token samples + complement an isolated two-word-only source propagation proof. +- Semantic throw analysis covers the accepted direct string, interpolation and + concatenation forms with fixed diagnostics. Compiler-clean positive/negative + cases exercise base/derived/aliased/target-typed exceptions, constants, + argument position, generated code and the declared exclusions. +- `backend/src/Directory.Build.props` supplies the analyzer automatically to all + production projects. Sixteen local references are removed. The compiler-visible + scope property keeps `LS0001` on its former project set; evaluated Debug/Release + wiring, a planted new nested project and actual builds verify both rules. +- Disposable builds use actual copied props, source and local package archives: + `CI=true` still allows `LS0002` Warning, while an unrelated CS0219 warning fails. + This local-cache restore is not a production vulnerability-audit claim. +- Behavioral samples reject unsuppressed compiler warnings/errors. Recompiling + the real analyzer for source propagation separately uses its evaluated SDK + references and NoWarn settings, including SDK assembly-version unification; + no new sample-warning exemption or runtime dependency is introduced. +- Five design-time factory sites suppress only the public environment-key-name + constant false positive, with a local explanation. Credential values are not + interpolated; the rule is never disabled for a project. Standards 09/11/21 and + the redactor comment now describe the bounded guard rather than a secrecy proof. + +Validation after formatting: full Release solution build with `CI=true`, zero +warnings/errors; all 2,665 Unit cases, 298 Docker-free integration cases and five +Contract cases pass, zero skips. Eleven relevant architecture cases pass, +including corpus, actual project wiring, domain-exception dirty controls and +the production compiler-input/genericity census. The new controls include real +SDK builds, not only synthetic compiler invocation. Documentation fragment, +structure/index and whitespace checks pass. + +The diagnostic catalogue row is Implemented; the inventory drift row remains +Registered for Step 2. Full final-source A/B/Docker/phase-exit qualification is +Step 4, not inferred from these local results. Both fresh implementation review +rounds remain pending before Step 2 begins. + +### P02b-8 Step 1 review round 1 (2026-10-25) + +Two fresh readers review `212ec0f4` against acceptance `4b29ea70`: a +`gpt-6.1-sol`/xhigh analyzer/security reviewer and a `gpt-6-astra`/high +wiring/proof reviewer. The latter independently runs the evaluated wiring cases +(3/3, zero skips); the former compares compiler diagnostics for ordinary and +dynamically bound exception construction without changing repository files. + +Two findings are verified and corrected: + +- An unrelated dynamic constructor argument changes the operation to + `IDynamicObjectCreationOperation`, bypassing the original static-creation-only + guard despite a known Exception type and direct string message. The guard now + applies the same accepted argument checks to both forms. Three positive and + one ordinary-message negative compiler-clean cases lock the distinction. +- The old XML-reference parser was called only by its own assertions after the + active check moved to evaluated MSBuild. That superseded helper and its + self-only assertions are removed; real compiler plants and evaluated metadata + dirty controls remain. + +After correction, the full `CI=true` Release build has zero warnings/errors; +all 2,669 Unit cases and ten affected architecture cases pass with zero skips. +The original HTTP/Contract and production-census results retain their recorded +scope. No new policy or diagnostic-coverage exclusion is introduced. Fresh +second-round review remains required before Step 2. + +### P02b-8 Step 1 review round 2 and closeout (2026-10-25) + +Two new reviewers independently inspect `4682e269` against acceptance +`4b29ea70`: a `gpt-6-astra`/high semantics reviewer and a +`gpt-6.1-sol`/xhigh proof/wiring reviewer. Both approve with no remaining +Blocker, Major or Minor finding in their reviewed scope. The dynamic-constructor +fix and removal of the superseded parser are included, not assumed from the +first-round receipt. + +The semantics reviewer independently runs 113 semantic/token cases, including +the source-propagation clone. The proof reviewer runs 115 Unit and eight +architecture cases, including current Debug/Release wiring and corpus counts. +All pass with zero skips. The second reviewer inspects the disposable real-build +and source-mutation machinery without claiming an independent rerun of it; +the root's full build/2,669-Unit and broader local receipts remain separate. + +Step 1 is complete with both fresh review rounds and committed verified fixes. +The next approved step independently verifies the canonical erasure inventory +against actual storage and adds its drift controls. No final hosted/Docker/A/B +or phase-exit result is inferred from this local closeout. + +### P02b-8 Step 2 — Independent asynchronous inventory coverage (2026-10-25) + +The structural control reads the ordered compiled `PlatformDbContext` and +`AuditDbContext` migration `UpOperations`, without opening a database or consulting +a design-time factory or private configuration. Evaluating those operations +expands the pinned vendor installer resources. A bounded table-declaration reader +tracks typed and literal SQL CREATE/DROP/RENAME operations and refuses unsupported +or ambiguous table DDL rather than silently omitting it. + +The complete Platform census contains 23 tables: the inventory's ten first-party +and twelve vendor rows, plus the explicitly documented `idempotency_keys` scope +exclusion. The vendor rows independently match `HangfireStorageContract.Columns`; +Audit's migration chain independently establishes `audit_log`. Required provider, +diagnostic, backup/WAL and volatile BFF entries remain distinct from that SQL +census. Marked canonical tables prevent incidental nearby prose from satisfying +a missing row. The existing live PostgreSQL schema census remains independent. + +Five new architecture facts cover the clean subject, added/dropped/renamed storage, +changed vendor contract, each removed or duplicated inventory/exclusion/custody +row, blank vendor classifications, malformed tables/markers and unsupported DDL. +All five pass in Release with zero failures/skips, as do the five corpus controls. +The catalogue now reports 270 methods and 237 Implemented rules, 134 in the +architecture assembly and 103 elsewhere. Documentation fragment/structure/index +and whitespace checks pass. + +This is structural coverage, not field-level erasure, legal compliance, provider +schema discovery or a new purge/grant/retention mechanism. Independent review of +subject locators and existing authority remains part of this step. Both fresh +implementation review rounds remain pending. + +### P02b-8 Step 2 review round 1 (2026-10-25) + +Two fresh independent reviewers inspect `b20ffaeb` against `fa56aac3`: a +`gpt-6.1-sol`/xhigh census/proof reviewer and a `gpt-6-astra`/high data/governance +reviewer. The latter independently checks migration fields/grants, immutable +inbox/job facts, causal audit metadata, the six-column redaction boundary, +pinned provider event fields and volatile BFF custody; no actionable finding is +identified and no provider test is claimed. + +The census reviewer reruns the five existing Release cases, zero skips, and +reproduces two omissions against the compiled internal parser/checker through +an owned temporary reflection harness: top-level `SELECT INTO` can create a +persisted copy without a CREATE token, and split-literal dynamic EXECUTE can +construct table DDL without a complete declaration inside any one literal. Both +leave the prior census unchanged and were therefore wrongly accepted. The fix +must refuse these unsupported paths without confusing PL/pgSQL variable +assignment or the pinned installer's non-table dynamic statements. + +The independent live PostgreSQL backstop also passes its table-class/RLS census +and both unknown-table/history-lookalike controls, 3/3 with zero skips. These +checks do not remove the new structural parser's obligation to reject its own +unsupported shapes. Correction verification and the second fresh review round +remain pending. + +#### Correction verification + +Both verified SQL omissions now refuse through the same complete inventory +checker. Dollar-body tracking preserves existing PL/pgSQL INTO assignments; +unresolved dynamic EXECUTE refuses, with bounded literal concatenation accepted +only for the pinned installer's non-table schema/sequence/index commands. +Additional format/variable EXECUTE negatives and the legitimate assignment/ +installer positives exercise that boundary. The five inventory and five corpus +Release cases pass together, zero warnings/failures/skips; scoped formatting, +documentation and whitespace checks pass. The fresh second review remains +pending. + +### P02b-8 Step 2 review round 2 (2026-10-25) + +Two new independent readers review `fa56aac3..c241301b`: a +`gpt-6-astra`/high contract/data reviewer and a `gpt-6.1-sol`/xhigh proof reviewer. +Each reruns the five Release inventory cases with zero skips. The first confirms +actual compiled migration/vendor discovery, independent contract reconciliation, +canonical row controls and authority limits without an actionable finding. + +The second confirms R1's corrections and independently reproduces three further +false passes through the compiled complete checker: SET LOCAL/SESSION search-path +and SET SCHEMA aliases can hide a colliding non-public table; a dynamic variable +named `function` or `procedure` is wrongly treated as trigger syntax; and SQL +RENAME loses the source schema, mistaking a non-public table for a public one. +The reviewer verifies the SQL semantics in rollback transactions on an owned, +unpublished `postgres:18.4-alpine` container and removes that exact container. +No production/developer database or private environment is used. + +These are bounded reader defects, not changes to storage or erasure authority. +They require supported name resolution or explicit refusal, genuine trigger-only +exemptions, and complete-checker controls. Correction and both second-round +reviewers' bounded rechecks remain pending before Step 2 closes. + +#### Correction verification + +The reader now explicitly refuses non-public table storage rather than inferring +schema-qualified renames. Search-path handling covers LOCAL/SESSION, quoted names, +SCHEMA aliases and DO-body statement starts; only the supported singleton public +path passes. Trigger EXECUTE exemptions require actual top-level trigger syntax; +GRANT/REVOKE clauses remain separate from dynamic commands. Nine complete-checker +regressions exercise these reviewed paths, with supported public-path/rename, +trigger and grant positives. Inventory 5/5 and corpus 5/5 pass in Release, zero +warnings/failures/skips. Scoped formatting and whitespace checks pass. Both +second-round reviewers' bounded correction rechecks remain pending. + +### P02b-8 Step 2 closeout (2026-10-25) + +Both second-round reviewers independently recheck `c241301b..bfa6ec89` and +approve the bounded corrections without a new actionable finding. The proof +reviewer reruns the original counterexamples through the compiled complete +checker; all now refuse. The contract reviewer reruns the five inventory cases; +the proof reviewer runs inventory/corpus together, 10/10, zero failures/skips. +No new provider, field-erasure or legal-compliance claim follows from these checks. + +Step 2 and both fresh implementation review rounds are complete. The canonical +inventory is installed, its structural drift control is Implemented, and the +independent existing live PostgreSQL census/control cases have passed. Step 3 +now reconciles remaining current-tense carriers, inherited catalogue obligations +and the unchanged documentation-lint handoff. Step 4 retains final-source local +and complete hosted A/B qualification; none is inferred from this closeout. + +### P02b-8 Step 3 — Delivered carriers and catalogue reconciliation (2026-10-25) + +The current phase plan now describes the delivered JWT/UUID/matrix/recorder, +realm reconciliation and bounded read-only surface. Assertion audit is subject +to ADR-0065 admission; the whole-chain quota control uses a reduced subject +budget below the unchanged ingress floors, not an end-to-end 600/minute promise. +Provider events and local BFF diagnostics remain separate from module audit +registration. Explicitly historical preparation and Accepted/delivered records +retain their original state. + +Architecture 31 preserves immutable actor identity and surviving causal metadata +without claiming complete anonymisation. Architecture 33, workflow skills and +source comments describe the actual seven behaviors plus handler, pass-through +permission shell, shared composition helper, immediate outbox INSERT, owner-side +domain completion and independent dispatch. Automatic in-tree analyzer wiring +and Warning posture replace the obsolete NuGet/manual-registration example. +The platform gate remains deny-all; only its stale fixed explanatory sentence +changes. Cache invalidation retains its TTL-bound race, without assigning a +nonexistent post-commit seam to the outbox. + +Adjacent database/audit/gateway/phase/contributor carriers now point to actual +schema classes, shipped job controls and their distinct Phase 03/11 owners. +Front doors remain phase pointers. Phase 03 inherits XML-documentation target +existence and changed-prose width CI checks on the unchanged second-write- +contributor trigger. The read-only live census still finds one writer and the +same seven strict required contexts; no repository setting is changed. + +The complete catalogue audit includes 45 entries whose Phase names 02b and the +nineteen inherited P02b-4 obligations: all 64 are Implemented, including frontend +and offline owners and the new analyzer/inventory controls. The provider-SDK +rule remains Phase 03 backfill at the first actual runtime SDK; direct HTTP +tooling does not manufacture that subject. Three development realm roles and +full scope remain real and inert application authority, so neither is removed +on the strength of a stale review premise. Production job registries remain +intentionally empty. + +Validation: `CI=true` Release solution build has zero warnings/errors; Unit +2,669/2,669, affected architecture 28/28, Docker-free HTTP 298/298 and Contract +5/5 pass, zero skips. Frontend typecheck/lint and guarded 2,376 cases pass; +offline shard/result controls pass 72/72 and 30/30. Documentation fragment, +structure/index, added-prose width and whitespace checks pass. Full-source +hosted A/B qualification remains Step 4, and both fresh Step 3 review rounds +remain pending. + +### P02b-8 Step 3 review round 1 (2026-10-25) + +Two fresh independent reviewers inspect all 24 files in +`3a564448..1231aedc`: a `gpt-6-astra`/high contract/authority reviewer and a +`gpt-6.1-sol`/xhigh corpus/proof reviewer. Both approve without an actionable +finding. They compare current identity/refusal/audit and owner-completion +claims with source, preserve the deny-all platform gate and erasure prerequisites, +and confirm that Accepted bodies and historical records remain intact. + +The corpus reviewer independently recounts 45 explicit Phase 02b entries plus +nineteen inherited job obligations, verifies the inherited canonical-owner +methods, and checks backend/frontend/offline ownership. Paginated read-only +GitHub checks again find one writer and the same seven strict contexts bound +to Actions app `15368`. Documentation lint resolves 2,328 fragments; corpus +5/5 and selected inventory/pipeline/authority/surface controls 29/29 pass from +existing Release binaries, zero skips. The contract reviewer performs source +review only. Neither claims fresh build, full suites, provider/browser or hosted +A/B execution. The fresh second review round remains pending. + +### P02b-8 Step 3 review round 2 and closeout (2026-10-25) + +Two new independent reviewers inspect `3a564448..4d242bc8`, including all +24 changed implementation files and the first review receipt: a +`gpt-6.1-sol`/xhigh semantics reviewer and a `gpt-6-astra`/high proof/governance +reviewer. Both approve without an actionable finding. They independently confirm +all 64 obligations and the nineteen inherited canonical owner methods, current +carrier/code agreement, actor/metadata limits, shared pipeline registration and +unchanged Phase 03/11 responsibilities. Neither edits files or changes settings. + +The proof reviewer runs existing Release corpus checks 5/5, zero skips, and +passes documentation lint (2,329 fragments, structure and indexes) and whitespace +checks. Its read-only live GitHub check again confirms one writer and seven +strict required contexts bound to app `15368`. The semantics review is source/ +corpus inspection only. Neither claims full suites, provider/browser or hosted +A/B execution. + +Step 3 and both fresh review rounds are complete. Step 4 now owns the individual +exit-evidence index, full-source local and hosted A/B qualification, final live +protection verification and the review PR. Until those proofs complete, P02b-8 +and Phase 02b remain in progress. + +### P02b-8 Step 4 — Individual exit ownership and source freeze (2026-10-25) + +The [individual exit index](phase-02b-exit-evidence.md) maps all 26 deliverables, +60 completion criteria and eleven exit obligations in canonical source order, +plus eleven explicit exclusions and the Dapr/Kafka boundaries. Named method +owners are checked against actual classes, including partial-file distinctions; +backend, real integration, frontend, browser, OpenAPI and offline/governance +lanes stay separate. This is an ownership index, not a passing CI receipt. + +Two formerly imprecise proof locators are resolved before hosted qualification: + +- C27's vague G6 reference is replaced by ADR-0044's existing declared-type/frame + composition contract. The actual app-role + `AuditStoreTests.A_capture_of_another_entity_type_does_not_reach_the_row` passes, + 1/1, zero skips. Frame controls remain separate; this creates no new policy or + claim that arbitrary undeclared roots are rejected by a runtime guard. +- `DeliveryExecutionTests` directly observes the real scoped capture's single + clear on success, failure and lost physical COMMIT, preserving the concrete + `IAuditSubject` binding. The lost-COMMIT theory counts exactly one standalone + indeterminate row by operation, subject and causal event as `learnstack_app` + under both tenant/organization GUCs. Completed retries clear no new frame and + change no durable count. All 35 existing cases pass with zero skips; no test + method/count, production path, schema, grant or retry policy changes. + +The Phase 02c owner now explicitly carries its already assigned queued/in-flight +status-transition decision before the first status/termination writer. It selects +no hold/drop/dead-letter policy here and preserves lease/quiescence/reservation +constraints. Its phone-home handoff distinguishes delivered runtime foundation +from future real Hub definitions and adapter proof. + +Before freezing, `c5847a9` joins current main's PR #36 squash ancestry. Main's +complete tree equals the already included `6b6f0629` source; the merge's complete +tree equals its development parent. No file content changes or prior qualification +relabeling occurs. Development remains the working branch. + +The integration-only build with existing project references has zero warnings/ +errors, and documentation fragment/structure/index and whitespace checks pass. +The full local Release architecture suite remains in progress. Earlier Step 3 +local receipts cover unchanged production/frontend source; final hosted complete +same-source A/B and all actual lanes remain pending. Both fresh Step 4 review +rounds and the review PR follow those receipts; this record claims no phase exit. + +### P02b-8 Step 4 review round 1 — source (2026-10-25) + +Two fresh independent readers review `63a4b523..6224bd9e`: a +`gpt-6.1-sol`/xhigh source/proof reviewer and a `gpt-6-astra`/high index/governance +reviewer. Both approve the source without an actionable finding. They verify +all 26/60/11 source-ordered requirement mappings and eleven/two exclusion +boundaries, exact method owners and partial-file distinctions, the real capture +observer/subject identity, row-bound app-role indeterminate count, existing C27 +composition rule and unchanged authority/retention boundaries. The index reviewer +also verifies the content-preserving merge ancestry and passes documentation/ +whitespace checks. + +This is source approval only. The frozen code/test source is +`6224bd9eba807b56b477ee57d6abba7b9caaa1b8`, tree +`274599e096854e8f0332e8f894596fc45e082fe9`. +[Run 40145581317](https://github.com/HodeTech/LearnStack/actions/runs/40145581317) +is the first complete assignment A, still in progress when this entry is made; +complete same-source B, final-head checks and the full local architecture receipt +remain pending. Both reviewers require the actual completed receipts before +qualification approval. Later documentation-only records do not relabel this +source or any earlier run as a later source's proof. + +### P02b-8 Step 4 review round 2 — source (2026-10-25) + +Two fresh independent readers review `63a4b523..7ae3d8f3`: a +`gpt-6-astra`/high semantics reviewer and a `gpt-6.1-sol`/xhigh evidence reviewer. +Both approve the source without an actionable finding. They verify the complete +26/60/11 requirement mapping, eleven exclusions and two transport boundaries, +all 94 explicit class/method locators, actual Docker lanes, concrete capture/ +`IAuditSubject` identity and row-bound app-role indeterminate audit counts. C27 +retains ADR-0044's existing composition policy. Documentation and whitespace +checks pass. No executable changes follow the frozen `6224bd9e` source. + +The full local Release architecture suite now passes 441/441 with zero skips; +the final solution build has zero warnings and errors. Unit 2,669/2,669, +non-Docker HTTP 298/298, contract 5/5, frontend 2,376 cases and the relevant real +PostgreSQL delivery/store proofs also pass. These receipts do not replace full +hosted qualification. + +[Run 40145581317 attempt 1](https://github.com/HodeTech/LearnStack/actions/runs/40145581317/attempts/1) +completes layout A on the frozen source with 27/27 successful jobs. Before the +full B rerun, all 25 artifact archives and complete attempt-1 API metadata are +retained and hash-verified. Independent readers recompute 5,992 unique Passed +cases, zero skips, backend 3,413 and integration 2,579, plus nine public pages +and 27 Lighthouse report/HTML pairs with natural cleanup. The largest producer +takes 984 whole-job seconds; the aggregates take 14/28 seconds. GitHub removes +A's remote artifacts during the full rerun; the retained authenticated metadata +and matching archives supply that evidence, not continued downloadability. + +This remains source and A-only approval. Full same-source B, the completed-pair +review follow-up and actual final PR-head qualification remain pending. No +earlier run, source-only approval or passing A result is counted as phase exit. + +### P02b-8 Step 4 — Completed-source qualification and review closeout (2026-10-25) + +All four implementation steps and both fresh independent review rounds per step +are complete. The Step 4 source reviews above are supplemented by completed-pair +reviews: the round-1 `gpt-6-astra`/high reviewer and both fresh round-2 reviewers +(`gpt-6-astra`/high and `gpt-6.1-sol`/xhigh) independently verify the actual A/B +receipts and approve frozen-source qualification without an actionable finding. +They keep the later receipt-only commit and its actual PR-head result separate. + +**Qualified implementation source:** +`6224bd9eba807b56b477ee57d6abba7b9caaa1b8`, tree +`274599e096854e8f0332e8f894596fc45e082fe9`. +[Run 40145581317](https://github.com/HodeTech/LearnStack/actions/runs/40145581317) +uses two complete attempts: [A/1](https://github.com/HodeTech/LearnStack/actions/runs/40145581317/attempts/1) +and [B/2](https://github.com/HodeTech/LearnStack/actions/runs/40145581317/attempts/2). +Both use that exact source and unchanged plan. Neither is a failed-only rerun, +an older P7 receipt or a union of successful siblings from different attempts. + +| Completed proof | A / attempt 1 | B / attempt 2 | +|---|---:|---:| +| Successful jobs / required contexts | 27 / 7 | 27 / 7 | +| Unique Passed .NET cases; skipped cases | 5,992; 0 | 5,992; 0 | +| Non-Docker / Docker cases | 3,413 / 2,579 | 3,413 / 2,579 | +| Unit / Architecture / HTTP / Contract | 2,669 / 441 / 298 / 5 | 2,669 / 441 / 298 / 5 | +| Ordinary / native Docker cases | 2,548 / 31 | 2,548 / 31 | +| Natural producer ownership and cleanup | 20 / 20 | 20 / 20 | +| Verified artifact archive digests | 25 / 25 | 25 / 25 | +| Frontend cases; skips/todos | 2,376; 0/0 | 2,376; 0/0 | +| Maximum producer whole-job seconds | 984 | 852 | +| Backend / integration aggregate seconds | 14 / 28 | 17 / 35 | +| Meta whole-job seconds | 108 | 84 | +| Public pages / Lighthouse report pairs | 9 / 27 | 9 / 27 | +| Natural demo cleanup milliseconds | 12,298 | 10,545 | + +Independent checks hash every archive against authenticated API metadata, match +the extracted bytes and source identity, recompute selector assignments from +the full discovery and reviewed plan, and validate exact case IDs/raw TRX +unions, zero skips, toolchain/resources and natural cleanup. The 35 delivery +cases include both lost-COMMIT variants; the actual C27 store proof also passes. +Frontend job logs independently state 2,376 passes in two packages with zero +skips/todos. Public receipts match source/tree, all nine URLs and 27 JSON/HTML +digests, passed budgets and confirmed process/Compose/private-file cleanup. + +Before starting B, all A archives and complete attempt-1 API metadata are +retained and their hashes verified. A's remote artifacts were unavailable on +readback after B started. This corrects the round-2 source receipt's causal +wording: the observed timing does not establish the cause of removal. A's +artifact IDs identify the captured provenance; this record promises no continued +remote downloadability. B is independently verified against its completed API +snapshot and all 25 archives. + +Actual co-membership changes, rather than renamed bins: Architecture moves 221 +methods / 359 cases; ordinary moves 1,074 / 2,256. Across the declared +fixture-bearing classes, 1,071 methods / 2,253 cases move. Both grouping sets +differ under the independent shared-fixture check. Two assignments do not prove +absence of every possible ordering dependency. + +Both attempts capture the same .NET SDK `10.0.402`, console +`18.7.0-release-26505-111`, console/dependency hashes and xUnit adapter `2.8.2.0` +hashes. Runner receipts identify Ubuntu 24.04 image `20261023.334.3`, kernel +`6.17.0-1022-azure` and four CPUs. Both demos record Node `v22.23.1`, Playwright +`1.64.0`, Chromium revision `1248`, Lighthouse `13.5.0` and the same configuration +digest. These are observed identities, not claims that moving runner labels or +the SDK roll-forward policy pin those binaries indefinitely. + +- Manifest digest: + `a3244565e6b1842821760e919e1c3e6e1eeec3ed151d8ed9f6981199288cd7e4`. +- Plan digest: + `69bbbf02314096983765b4fda1ded636c3698903d4b714393b4280c5e504016b`. +- A assignment digest: + `8933afb7ec87353cecdeed094abdd6ba2c691ae515a6a13c48c7a45a9c927374`. +- B assignment digest: + `1a90b01a179388c0e4509a71928ede67b490c3acaabfb5961ecfb42773b36075`. +- Independent pair audit SHA-256: + `bed7f4cb97bfba59cd60473cb85a3cc0e4f733899ff74ff81c60d1c43912f64f`. +- A/B supplementary audit SHA-256: + `996c10658fa9880c4f8d978513ee39f65411ce02c0093b20e6516db0baefe68e` / + `833338062f12b8f40baadc0324d209c053ca83112770a45bb7561f3d09f73b4b`. + +**Live protection, read back 2026-10-25:** strict up-to-date protection retains +all seven exact contexts, each bound to GitHub Actions app `15368`: backend, +frontend, secret scan, meta, backend integration, OpenAPI diff and public demo + +Lighthouse. Their complete names remain canonical in +[Contributing](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main). +Only `cemililik` has write access; `hodesis` is read-only. The documentation-lint +trigger requiring a second collaborator with write access has not fired; Phase +03 retains its unchanged named owner. Required reviews remain zero and admin +enforcement is false under the documented single-contributor deferral; no +settings change is made by this packet. + +The [individual exit index](phase-02b-exit-evidence.md) maps all 26 deliverables, +60 completion criteria and eleven exit obligations, plus exclusions and +transport boundaries. All 45 explicit Phase 02b catalogue obligations and +nineteen inherited job obligations are Implemented with real proof owners. +No erasure, legal-compliance or full browser-driven OIDC guarantee follows from +this index or the structural store census. Phase 03 retains the accepted +severity/authorization/privileged erasure work; Phase 11 retains production +operations; Phase 06 retains its full browser journeys. Phase 02c starts on its +own billing/plan-gating trigger and does not gate Phase 02b exit. + +This closeout changes only the delivery receipt/generated index, phase Status +and exit-index qualification notes. No executable, plan, toolchain or fixture +lifetime changes. Under ADR-0063's normal-future-push rule it still requires one +complete current-head assignment before PR readiness, including the PR-only +meta gates omitted by `workflow_dispatch`. The review PR's live checks record +that result. A/B remains attributed to the frozen implementation above, never +to this later receipt-only commit. Maintainer review and merge remain separate +acts; Phase 02b stays in progress until that merge closeout. + +### P02b-8 PR correction verification (2026-10-25) + +This pass starts from PR #37 head `141592fa`. Its historical qualification stays +attributed to that source and the earlier frozen implementation; none of those +receipts qualifies the corrections below. + +**Verified corrections.** + +- Add the LS0002 Debug/Release production corpus guard, including suppressed + diagnostics; prove unconditional analyzer-reference ancestry and evaluated + execution/severity settings. Target-time ProjectReference removal/update and + editorconfig/targets suppression have planted controls. An explicit operation + stack replaces recursive analyzer traversal without changing its expression, + token, type or generated-code scope. +- Remove the five broad LS0002 factory pragmas through accurate constant names, + preserving their environment keys and messages. Add compiler-clean descriptor, + dynamic-argument, rethrow, culture and clean-build controls. +- Reconcile all five compiled migration chains with inventory classifications + and explicit synchronous/module exclusions. Unsupported stored projections, + opaque procedural DDL, adjacent dollar terminators, search-path manipulation + and schema mutation fail closed with origin-specific reasons. A separate + PostgreSQL control discovers ordinary/partitioned/materialized relations. +- Observe the unmodified production audit capture and its subject alias, real + population and empty terminal state; prove cross-scope isolation and no + indeterminate row after acknowledged success. Retained call-count behavior + tests and real delivery state tests cover different aspects of cleanup. +- Correct stale purge grants, pending job-runtime wording, owner omissions, + pseudonymity and whole-payload redaction claims. Phase 03 owns application + recovery/dashboard and first-writer authority; Phase 11 owns gateway/purge + qualification. The exit index names the actual row-8 and Contract-lane proofs. + Its mode-boundary test now composes every DeploymentMode value in a Development + test host; it does not qualify production deployments. +- ADR-0032 Amendment 7 clarifies the already-approved severity/wiring/scope + contract. It leaves Amendment 6 and earlier Accepted text unchanged. + +**Bounded dispositions.** + +- Runtime matcher plural/digit/compound expansion, type-based analyzer + exclusions and non-thrown/factory coverage would change the approved contract; + they are not introduced by a regression fix. The documented name-based limits + remain mandatory review considerations at Phase 03's Error gate. A proposed + EF-only generated-source/no-throw restriction was rejected and removed; + Roslyn's general generated-code exclusion remains explicit. +- C27's historical criterion delegates its outcome to G6. ADR-0044 Amendment 5 + selects captures matching declared EntityType, while ADR-0057 separately + refuses unregistered mutating handlers. The index proves that existing filter; + it does not select arbitrary extra-root rejection or certify every possible + direct write. No new erasure, purge, privilege or retention decision is made. +- Exact vendor columns already have the independent applied-schema + `HangfireSchemaShape.Verify` proof. The structural inventory does not duplicate + it or claim to discover personal data hidden in values. +- Foreign worktrees and existing history are untouched. In particular, the + append-only earlier artifact-removal sentence is superseded by the explicit + observed-timing correction in the Step 4 closeout, not silently rewritten. + +**First correction review round.** Three fresh automated sessions inspect +bounded, disjoint primary surfaces against this baseline working tree: + +| Session | Model / effort | Scope and verified result | +|---|---|---| +| `pr37_fix_r1_storage` | GPT-6-astra / high | Inventory, live census and real capture proof; approve with stated structural/runtime limits | +| `pr37_fix_r1_analyzer` | GPT-6.1-sol / xhigh | Analyzer/build/corpus/suppression; real MSBuild-only probes expose target-time reference mutation; corrected controls pass review; unsupported generated restriction removed | +| `pr37_fix_r1_docs` | GPT-6-astra / high | Accepted scope, carriers and exit ownership; no Blocker/Major; missing Contract executor labels corrected | + +“Independent” here means separate fresh-context automated review sessions with +shared repository access, not human approval or separately administered hosts. +These records preserve scope, model, finding and disposition; full provider +transcripts are not committed or claimed as a permanent audit archive. + +**Local validation.** Release solution build: zero warnings/errors. All 2,692 +unit cases pass, zero skips. Focused architecture validates 94/95 initially; +the single catalogue-owner classification error is corrected, and the complete +five-case CorpusConsistency group then passes. The published census is 279 test +methods and 237 Implemented rules (134 architecture, 103 other owners). +Inventory controls pass 40/40, live relation-kind PostgreSQL controls 3/3, and +final capture/delivery/all-mode integration controls 40/40, all without skips. +Removing the owner Clear kills all seven targeted delivery paths; changing its +capture to singleton kills the scoped-root control. Both mutations are restored +byte-for-byte and the normal binaries rebuilt before the final passing run. +Documentation fragment/structure/index checks and seven ADR parser controls pass. + +Second-round review and current correction-source hosted qualification remain +pending. GitHub's required conversation resolution is a separate merge gate, +alongside the seven required checks and maintainer review. The two corrected +threads must be resolved after their changes are published and verified. + +**Evidence lifetime.** Existing workflow artifacts have finite seven-day +retention. The earlier archive hashes and supplementary audit hashes identify +the evidence read at qualification time; they do not promise permanent remote +availability or committed copies of those audit aids. Retained local receipts +are not a substitute for source attribution or a public permanent archive. +Future operational retention remains Phase 11's responsibility. + +### P02b-8 correction review round 2 and source freeze (2026-10-25) + +The completed code correction source is +`5da6bab383d77a9d43f6ab310a03b49a13ccaf02`, tree +`75862d496ea54940b0ded95f6d3a5cb7cebdb9a9`, after commits `60a9721c` and +`b4b85dea`. This receipt and prose-only wrapping add no executable change. + +Two new fresh-context automated reviewers independently inspect the committed +correction and its bounded fixes: + +| Session | Model / effort | Final source and result | +|---|---|---| +| `pr37_fix_r2_code` | GPT-6-astra / high | `5da6bab3`; approve across changed C# and direct contracts after the opaque-routine finding and header/path variants are corrected | +| `pr37_fix_r2_contracts` | GPT-6.1-sol / xhigh | `5da6bab3`; documentation approval after two remaining adjacent carrier comments are synchronized | + +These source reviews execute no builds or PostgreSQL tests themselves. Their +approval verifies implementation and proof design; the execution below is the +implementing agent's evidence, not an attributed independent rerun. + +**Verified second-round finding.** A quoted FUNCTION/PROCEDURE body can hide +split dynamic table DDL, just as a quoted DO body can. All four initial planted +routine cases fail before the fix for the intended missing-refusal reason. +The bounded reader now requires a dollar-quoted routine body, scans the complete +declaration through its terminator, and separates default-string dollars and +parenthesis depth from the body AS. Search-path options before and after the +body admit the current explicit public/pg_catalog forms and refuse unresolved +or foreign paths. Quoted setting names do not broaden quoted schema identity. +The actual five migration chains and pinned installer remain clean. + +Final inventory/CorpusConsistency selection passes **58/58**, zero skips. A +separate owned PostgreSQL selection passes **5/5**, including actual table +creation through the quoted dynamic routine and quoted setting-name behavior. +The earlier complete Unit and capture/delivery/all-mode runs remain applicable: +only the inventory test reader, its controls and these isolated PostgreSQL cases +change after their passing source. Test-method/catalogue counts remain +279 / 237 / 134 / 103; additional theory rows are not new methods or rules. +Whitespace, fragment/structure/index and commit-hook format/leak checks pass. + +The unchanged CI plan, algorithm and seven required context names are retained. +Current correction-source hosted qualification is still pending. Freeze the +code here before collecting its complete assignments; never relabel earlier +5992-case receipts as proof of the new population. Conversation resolution, +maintainer review and merge remain separate release gates. + +### P02b-8 CI fixture-witness reconciliation (2026-10-25) + +[Run 40174825328](https://github.com/HodeTech/LearnStack/actions/runs/40174825328), +head `0d9dea4f`, fails the meta job's +`test_shared_fixture_witness_matches_actual_source_classes`. The newly added +`StorageRelationCensusTests : IClassFixture` is absent from +`ci-test-shards-plan.json`'s fixture witness list. The local pre-push selection +omitted this relevant offline control; a passing Unit/database run did not +establish plan consistency. This is an implementation bookkeeping omission, +not a passing qualification or an unexplained infrastructure incident. + +Add exactly that sorted class entry. Counts, weights, algorithm, salt, bounds +and job topology remain unchanged; the list changes the fixture witness +population, not assignment membership. The plan digest changes. The fresh +`pr37_fix_r2_contracts` reviewer independently verifies this single-line delta +against the actual fixture declaration and approves it without selecting new +policy. Both offline selections pass: 72 plan controls and 30 result controls. + +The reviewed application/test code remains at `5da6bab3`. Collect fresh complete +A/B attempts for the corrected plan, with exact current test identities and +actual cleanup; the failed run and all earlier receipts remain source-bound +history. No omitted case, disabled control or increased ceiling is used to +recover the result. + +### P02b-8 CI witness and SQL-literal corrections, review round 1 (2026-10-25) + +The complete `c399ba52` attempt in +[run 40175295858](https://github.com/HodeTech/LearnStack/actions/runs/40175295858) +finishes 25/27 jobs successfully. `ordinary-3` contains one failed case, +`Terminal_audit_backlog_remains_faulted_beyond_two_leases_while_native_business_commits`; +the integration aggregate consequently refuses the attempt. Authenticated API +metadata and the failing artifact ZIP digest match. Its finite failure location +is `facade_business:89`: the handler-entry list is expected to contain two IDs. +The manifest contains 6096 test identities; this failed attempt is not a passing +qualification. Backend, frontend, meta and public-demo successes do not override +the failed integration population. + +**Business witness defect.** The list adds a fresh organization ID before the +business transaction commits, while the accepted transactional runtime permits +rolled-back attempts and bounded retries. A controlled transient refusal after +the original first successful nested write reproduces the same line-89 failure: +three entries rather than two. The original bytes are restored before the final +repair. This proves an invalid test witness; it does not establish the specific +historical CI retry trigger. + +The repaired test derives stable organization identity from the authoritative +JobTenantContext.JobId, deliberately rolls back one successful nested write per +logical job, and verifies absence on re-entry. Each completed job must have one +durable organization and one successful MUST audit, with ledger/summary admission +agreement and bounded body entries. All hundred terminal rows, revoked audit +permission, native bridge, two-lease hold and original deadlines remain intact. +The target and two business/renewal siblings pass 3/3, zero skips; the Docker +trait guard passes. No production retry or timeout policy changes. + +**SQL literal defect.** A newly verified inline finding shows escaped E/e +strings can hide subsequent SELECT INTO from the old ordinary-quote tokenizer. +Three negative plants reproduce missing refusals before the fix. E/e boundaries +are recognized without evaluating their values; configuration names and pinned +EXECUTE retain ordinary-only literal requirements. A fresh reviewer also exposes +newline escape-string continuations; three further red plants reproduce that +gap. Adjacent continuations now fail closed, including conservatively refused +comment-separated forms; operator/terminator-separated values remain supported. +Actual PostgreSQL cases prove direct and continued escaped strings can precede +table creation. Current five-chain/installer definitions still pass. + +**Fresh first-round source review:** `pr37_ci_r1_backlog` (GPT-6-astra/high) +approves the one-file witness repair against ADR-0047. `pr37_ci_r1_lexer` +(GPT-6.1-sol/xhigh) finds the continuation gap, verifies its correction and +approves the final three-file reader/test scope. Both are read-only source +reviews; executed negative/positive results above belong to the implementing +agents. Final census/Corpus selection passes 81/81 and owned PostgreSQL cases +7/7, zero skips. The published test-method census becomes 282; rule counts +remain 237/134/103. The fixture declaration, plan, bounds and algorithm do not +change in this follow-up. Second-round source review and hosted qualification +remain pending. + +### P02b-8 CI corrections, review round 2 and source freeze (2026-10-25) + +**Reviewed source:** `93ef4b1881c439a150bb1a8164422e168e4199f7`, tree +`837daab732414e7840d265e8084ac49eba615786`, against `c399ba52`. +The failed hosted attempt and first-round correction record above remain the +owners of the reproduced defects and their bounded claims. + +Two fresh, read-only second-round reviewers approve without verified findings: +`pr37_ci_r2_witness` (GPT-6.1-sol/xhigh) checks the transactional retry and durable +audit witness against ADR-0047; `pr37_ci_r2_sql` (GPT-6-astra/high) checks escaped +literal boundaries, conservative continuation refusal, PostgreSQL controls and +catalogue counts. Neither reviewer claims independent test execution. + +The parent independently rebuilds the committed source and runs all 76 census +cases plus five Corpus controls: 81/81 pass, zero skips. The implementing +agents' seven PostgreSQL cases and three backlog/business siblings retain their +separate execution receipts. Both required source-review rounds are complete. +Production retry policy, timeout bounds, fixture ownership and shard plan are +unchanged by these corrections. A fresh complete hosted A/B qualification on the +same source remains required; the earlier failed attempts do not satisfy it. + +### P02b-8 native completion qualification correction, review round 1 (2026-10-25) + +[Run 40178360488](https://github.com/HodeTech/LearnStack/actions/runs/40178360488), +attempt 1 at `ec038610`, completes 25/27 jobs successfully. The same backlog case +now cancels at its second completion wait after 102.719 seconds; integration's +aggregate consequently fails. Its discovered population is 6,121 cases, not a +passing qualification. The finite failure receipt establishes cancellation and +source locations, but not the job's durable phase, native state or retry cause. + +**Verified fixture timing gap.** The unchanged 100-second deadline includes a +31-second hold and two jobs, each deliberately requiring a rollback and retry. +Native scheduled retries poll at 15 seconds. A callback may harmlessly consume +its hint before ACK while the application row is locked; ACK then retains the +accepted 60-second repair grace. The existing owned-lock proof demonstrates +this legal state. A local four-CPU rerun still passes in 62.679 seconds; neither +that pass nor the source counterexample proves the historical hosted trigger. + +The completion fixture now supplements at most one actual stock hint per +current durable generation. It first requires the real bridge ACK, database +eligibility, the original hint's Succeeded state, joined local work and open +routing authority. A broken bridge, retry control or native scheduler still +prevents success. This qualifies native completion rather than repair timing; +the production runtime, grace, retry policy, original deadlines, terminal fault, +hundred-row backlog and durable business/MUST-audit witnesses are unchanged. + +A new real regression rolls back a successful nested write, obtains generation +2 from actual control, locks that row during the original stock hint, proves no +second admission and live repair grace, then completes through the correct +generation. It requires two ledger admissions, one organization and one +successful MUST audit. Existing generation-1 lock coverage also uses the helper. + +The parent runs all three target cases: 3/3 pass, zero skips. Hardcoding the +supplement to generation 1 makes the new generation-2 regression fail on its +bounded wait. Original source bytes are restored and rebuilt; both lock cases +then pass 2/2, zero skips. Offline plan/result controls pass 72/72 and 30/30. + +Two independent read-only first-round reviewers approve without verified +findings: `pr37_retry_timeout_analysis` (GPT-6-astra/xhigh) checks the accepted +handoff, cleanup and progress contracts; `pr37_handoff_r1_test` +(GPT-6.1-sol/high) checks fixture isolation and regression non-vacuity. They do +not claim independent test execution. A second fresh source-review round and +complete current-source hosted A/B qualification remain pending. + +### P02b-8 native completion correction, review round 2 and freeze (2026-10-25) + +**Reviewed code:** `0d609804f97bacaeefde5545f868fe6ff89e4f68`, tree +`c079613a472d02b41d5d5ccfc45b298624272209`, against `ec038610`. +Two fresh read-only reviewers approve without verified findings: +`pr37_handoff_r2_protocol` (GPT-6-astra/high) verifies the protocol and cleanup +fences; `pr37_handoff_r2_witness` (GPT-6.1-sol/high) verifies the regression, +fixture and documentation claims. Neither reviewer executes tests. + +After commit hooks, the parent rebuilds the exact committed source: both locked +generation cases pass 2/2, zero skips, and the Docker trait control passes 1/1. +The first-round record above owns the three-case positive run, wrong-generation +counterfactual and byte-identical restoration. Both review rounds are complete. +This freeze changes no production implementation, plan or timing bounds. Fresh +complete hosted A/B qualification remains required before current-source +readiness; the failed earlier attempts remain failed. + +### P02b-8 browser artifact ownership correction, review round 1 (2026-10-25) + +[Run 40180307903](https://github.com/HodeTech/LearnStack/actions/runs/40180307903), +attempt 1 at `d6462dc7`, finishes 24/27 jobs successfully. The repaired backlog +case passes in 64.556 seconds. Native proof refuses before test launch with +`unexpected_crash_artifact_docker_overlay_dump_binary_data_image_metadata_unavailable`; +its runner reports image `20261012.334.1`, while the earlier passing native job +reports `20261023.334.3`. This difference does not establish the metadata +failure's cause. The fail-closed native prerequisite is unchanged. + +The separate actual browser case fails during counter-journey cleanup with +`retained_tree`: the C# driver's private temporary parent is not empty. The +receipt does not identify its retained entry, so historical causation remains +unproven. Source inspection nevertheless exposes a reproducible ownership gap. +Pinned Playwright 1.64.0 creates CDP artifacts under its cached process temporary +directory, outside the nested root the fixture owns. Its removal helper collects +filesystem errors without making the CDP close fail. + +A disposable actual-SDK probe uses stock Chromium `156.0.8078.48` on Darwin and +an exact-path, process-local removal refusal. Default CDP creates one unowned +sibling; browser close, joined browser shutdown and fixture disposal succeed +while the parent remains nonempty. An explicit private artifact directory under +the owned root leaves no sibling, and owner disposal removes the marker/root +after actual browser shutdown. Both process groups join without force; the +scoped filesystem hook is restored and the owned outer root removed. The +receipt SHA-256 is +`51fa1cadb45987bedb2662aae843e9265e3884c26d2d2f6943cc469babfd5e8c`. +This is a controlled ownership proof, not an identification of the hosted residue. + +The fixture now creates that `0700` directory and passes it as `artifactsDir`. +Browser/history assertions, process joins, privacy checks and the parent's +nonrecursive empty-root guard are unchanged. Actual removal failures still fail. +The parent runs the full native HTTPS browser positive/history-counter case: +1/1 passes in 28.845 seconds, zero skips. Existing fixture/observer controls pass +37/37; Prettier and whitespace checks pass. No application behavior, test +population, native prerequisite, deadline or shard plan changes. + +Two independent first-round source reviewers approve without findings: +`pr37_browser_cleanup_analysis` (GPT-6-astra/xhigh) executes the isolated SDK +counterexample and reviews resource ownership; `pr37_browser_r1_isolation` +(GPT-6.1-sol/high) independently checks source, isolation and cleanup without +execution. Second-round source review and fresh hosted qualification remain +pending. Failed runs provide no passing siblings to that qualification. + +### P02b-8 browser ownership correction, review round 2 and freeze (2026-10-25) + +**Reviewed executable correction:** `65f328358548da9a0af9b6b7eefb045efb9e08d3`, +tree `446f384e7e3225c7030cdbc4a3318b474eb24830`, against `d6462dc7`. +Two fresh read-only reviewers approve without verified findings: +`pr37_browser_r2_sdk` (GPT-6-astra/high) and `pr37_browser_r2_claims` +(GPT-6.1-sol/high). Both check the pinned SDK, fixture ownership, cleanup and +receipt limits without executing tests or the SDK counterexample. + +The parent retains the first-round actual browser 1/1, fixture/support 37/37, +controlled SDK refusal and hook build/lint/format receipts. This prose-only +freeze also corrects the nonexistent `IModule` label in Phase 08a and restores +ADR-0032 Amendment navigation/current Phase 02b ownership in the decision index; +the claims reviewer independently verifies those bounded carrier changes. +No executable, policy, timing, test population or plan change follows this +review. Both source-review rounds are complete. Fresh complete hosted A/B +qualification is still pending, with failed attempts and unsupported native +preconditions kept distinct from successful qualification. + +### P02b-8 PR correction qualification and closeout (2026-10-25) + +The corrections above and both independent source-review rounds per bundle are +complete. Their qualified head is +`7a2ef1d364a55b7438d17e44a02a5309d433d24d`, tree +`53ffc9e6a4563248d177c13a661fbf8b858d0690`. +[Run 40182091476](https://github.com/HodeTech/LearnStack/actions/runs/40182091476) +completes two full attempts, [A/1](https://github.com/HodeTech/LearnStack/actions/runs/40182091476/attempts/1) +and [B/2](https://github.com/HodeTech/LearnStack/actions/runs/40182091476/attempts/2). +Neither is a failed-job rerun or a union of successful siblings from different +attempts. Both check out merge `68684d128b4ac71bc5384f7cc3211068dc9a1bc4`, with +parents main `0dfade02a08fce6bd937fe0554f94f47c571ca8e` and the qualified head; +the merge tree equals the head tree. Workflow identity matches that checkout. +Earlier 5,992-case receipts and failed correction attempts retain their own +source attribution and do not qualify this population. + +| Completed proof | A / attempt 1 | B / attempt 2 | +|---|---:|---:| +| Successful jobs / required contexts | 27 / 7 | 27 / 7 | +| Unique assembly/case IDs Passed; skipped | 6,122; 0 | 6,122; 0 | +| Unit / Architecture / HTTP / Contract | 2,692 / 540 / 298 / 5 | 2,692 / 540 / 298 / 5 | +| Ordinary / native Docker cases | 2,556 / 31 | 2,556 / 31 | +| Natural producer completion and cleanup | 20 / 20 | 20 / 20 | +| Verified archives / extracted member files | 25 / 957 | 25 / 957 | +| Frontend cases; skips/todos | 2,376; 0/0 | 2,376; 0/0 | +| Maximum producer whole-job seconds | 881 | 920 | +| Maximum producer queue seconds, separate from job wall | 359 | 450 | +| Backend / integration aggregate seconds | 23 / 32 | 15 / 33 | +| Meta whole-job seconds | 88 | 112 | +| Public pages / Lighthouse JSON-and-HTML pairs | 9 / 27 | 9 / 27 | +| Natural demo cleanup milliseconds | 11,270 | 13,280 | + +Authenticated API metadata binds every raw archive digest and all inspected +member bytes. Exact TRX and incremental-completion IDs, outcomes and durations +agree across 22 TRXs per attempt; no skipped or forced-cleanup result supplies +passing evidence. Current-attempt job/artifact identities, source trees, +selectors, complete disjoint case unions, toolchains and cleanup are checked +independently. Each worker retains its twenty-minute ceiling; both aggregates +retain five minutes. Queue delay is not counted as execution wall time. These +successful runs do not requalify every interrupted-path reserve; the unchanged +launcher's separate failure-path controls retain that responsibility. + +The actual method co-memberships differ, including shared-fixture classes; +this is not a bin-label rename. Owner relocations cover 229 Architecture +methods / 405 cases, 1,061 ordinary methods / 2,303 cases and 1,059 shared-fixture +methods / 2,301 cases. An independent reconstruction also compares label-free +partitions. The source, complete case manifest and reviewed plan remain equal. +Two layouts do not prove absence of every possible ordering dependency. + +Both attempts observe SDK `10.0.402`, console `18.7.0-release-26505-111`, equal +console/dependency hashes and xUnit adapter `2.8.2.0` hashes. These observations +do not pin future runner binaries. Both frontend job logs independently confirm +2,273 + 103 passes, zero skips/todos. Public receipts bind all nine URLs and 27 +report/HTML digests to the source/tree, pass their budgets and confirm process, +Compose, private-file, environment and lock cleanup. + +- Manifest digest: + `ecaeae0e230f34bf8c49aa523f2d58ca683c01d113d99eb58003f58c406b40a3`. +- Plan digest: + `f6be9ba11c6cce2c6bdb7c11415553ec72c39704e03a84a422e53cb74851b0ed`. +- A / B assignment digests: + `b48d9e1c8ffdc668867e9e6d5b31e452e80672b19fe391f997a882722c4e5905` / + `7bec875797cbde4b6a51e1aba15c19267285dcc43c706b2fe1e165fbe710cdd4`. +- Parent pair-audit SHA-256: + `10001f727814853dd8b6a1d56f5093c679cc1e271dba0ebfd8f60cb047f24323`. +- Independent A-audit SHA-256: + `8d34a1ae66b8ee46e4c530e338af95a5b61dac5a3d6aac9f94f4012ee7557e39`. +- Independent completed-pair audit SHA-256: + `97b6810d09e38f362d731de56d985db4a5c38d9435cff74c9ba327ad7b8d594b`. + +`pr37_qualification_prepare` (GPT-6.1-sol/high) independently approves A's +complete captured evidence. Fresh `pr37_pair_final_audit` (GPT-6-astra/high) +independently validates both attempts and label-free partitions and approves +the pair without scoped findings. Both execute read-only data validation and +authenticated API/log readbacks, not application builds, tests or browsers. +These are separate automated contexts with shared repository access, not human +approval or independent platform attestation. + +All A archives and API metadata are sealed and verified before starting B. +After rerun, the latest artifacts listing exposes B's 25 IDs and none of A's +captured IDs; explicit attempt-1 job identities still match. The independent A +checks use retained raw archives and the authenticated snapshot. This observed +visibility change establishes no removal cause or permanent availability. +Artifacts have finite retention; neither these hashes nor local supplementary +audit receipts promise a permanent public archive. + +**Live protection readback, 2026-10-25:** strict up-to-date protection and +required conversation resolution remain enabled. All seven exact contexts in +[Contributing](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main) +remain bound to GitHub Actions app `15368`; all three verified review threads +are resolved. No remote protection setting is changed. + +The earlier [bounded dispositions](#p02b-8-pr-correction-verification-2026-10-25) +remain explicit: matcher/type/factory expansion and arbitrary extra-root +rejection are not selected by a regression repair. The inventory grants no +erasure, purge or privilege authority and proves no legal compliance or full +browser-driven OIDC coverage. + +This closeout changes only the delivery receipt/generated index, phase Status +and exit-index qualification pointer. Under ADR-0063's normal-future-push rule, +the later documentation-only head still requires one complete current-head +assignment, including PR-only meta gates. The PR's live checks own that result; +this frozen A/B receipt does not imply it. Maintainer review and merge remain +separate release gates, and Phase 02b remains in progress until merge closeout. + ## Status archive The Status block the phase document carried until 2026-10-22, kept verbatim. Its diff --git a/docs/roadmap/phase-02b-events-auth.md b/docs/roadmap/phase-02b-events-auth.md index 12d5ac396..ac5c19690 100644 --- a/docs/roadmap/phase-02b-events-auth.md +++ b/docs/roadmap/phase-02b-events-auth.md @@ -1,18 +1,22 @@ # Phase 02b: Events, Background Jobs, Identity, and Session -> **Status (2026-10-24).** Phase 02b is **in progress**. P02b-0 through P02b-5 are -> complete, and P02b-1–5 are merged through PRs #29–#33. P02b-6's implementation is -> merged through [PR #34](https://github.com/HodeTech/LearnStack/pull/34); its -> post-merge CI corrections are merged through -> [PR #35](https://github.com/HodeTech/LearnStack/pull/35). P02b-7's earlier -> implementation and source-bound A/B qualification remain recorded. The current -> runtime corrections and observer-test follow-up have completed local validation, -> both fresh independent review rounds and final-source hosted A/B qualification. -> The failed earlier source remains recorded; current-head required checks and -> maintainer review/merge remain the PR gate. -> [ADR-0071](../decisions/0071-uncertain-account-site-refusals.md) is Accepted and -> implemented. The packet row below owns correction state; maintainer review and -> merge remain separate. P02b-8's exit enforcement remains pending. +> **Status (2026-10-25).** Phase 02b is **in progress**. P02b-0 through P02b-7 are +> complete. P02b-1–5 are merged through PRs #29–#33; P02b-6 through PR #34 and +> correction PR #35; P02b-7 through +> [PR #36](https://github.com/HodeTech/LearnStack/pull/36). +> [ADR-0070](../decisions/0070-owned-tenant-bff-sessions.md) and +> [ADR-0071](../decisions/0071-uncertain-account-site-refusals.md) are Accepted and +> implemented. The P02b-7 merge closeout below links the source-bound A/B and +> final PR-head qualification. P02b-8's G16/G18 decisions are Accepted; all four +> implementation steps and both review rounds per step are complete. Its +> [correction qualification closeout](phase-02b-delivery-log.md#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) +> records complete A/B proof on the corrected source. +> [PR #37](https://github.com/HodeTech/LearnStack/pull/37) has completed both +> correction review rounds; earlier qualification stays bound to its own source. +> Current-head checks, conversation resolution, maintainer review and merge +> remain release gates; this phase is not yet marked merged. +> The [individual exit index](phase-02b-exit-evidence.md) names each criterion's +> owner. > > This document is the plan. Every dated decision package, step record, review > round, correction and merge closeout lives in the [delivery log](phase-02b-delivery-log.md), split out @@ -30,8 +34,8 @@ > | P02b-4 | Background jobs | ✅ complete and merged — PR #32, 2026-10-19; [merge closeout](phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) | > | P02b-5 | API authentication | ✅ complete and merged — PR #33, 2026-10-20; [merge closeout](phase-02b-delivery-log.md#p02b-5-merge-and-closeout-2026-10-20) | > | P02b-6 | Realm and seed | ✅ complete and merged — PR #34 and correction PR #35, 2026-10-23; [correction closeout](phase-02b-delivery-log.md#p02b-6-correction-merge-and-closeout-2026-10-23) | -> | P02b-7 | BFF session | [Review corrections and final-source A/B qualified](phase-02b-delivery-log.md#p02b-7-review-correction-qualification-2026-10-24); [PR #36](https://github.com/HodeTech/LearnStack/pull/36) pending maintainer review/merge | -> | P02b-8 | Exit enforcement | Pending — G16 and G18's erasure inventory | +> | P02b-7 | BFF session | ✅ complete and merged — PR #36, 2026-10-25; [merge closeout](phase-02b-delivery-log.md#p02b-7-merge-and-closeout-2026-10-25) | +> | P02b-8 | Exit enforcement | Implemented, reviewed and source-qualified — [acceptance](phase-02b-delivery-log.md#p02b-8-acceptance-2026-10-25); [Step 1](phase-02b-delivery-log.md#p02b-8-step-1-review-round-2-and-closeout-2026-10-25), [Step 2](phase-02b-delivery-log.md#p02b-8-step-2-closeout-2026-10-25), [Step 3](phase-02b-delivery-log.md#p02b-8-step-3-review-round-2-and-closeout-2026-10-25), [Step 4](phase-02b-delivery-log.md#p02b-8-step-4--completed-source-qualification-and-review-closeout-2026-10-25) and [corrected-source A/B](phase-02b-delivery-log.md#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) complete with both review rounds; current-head checks, maintainer review and merge govern release | ## Goal @@ -156,9 +160,10 @@ Each item below is named somewhere as adjacent to this phase's work. Each has an - **Purging processed outbox rows and aged inbox rows.** [Phase 11 § Data Operations](phase-11-production-hardening.md#data-operations) owns it. This phase is the one that starts filling both tables, so it records the - constraint — the `DELETE` grant belongs to `learnstack_platform`, whose only entry - takes a reason and no actor, so a recurring job has no principal to present — and G18 - registers the question. + constraint: only outbox currently grants Platform SELECT/DELETE. Inbox, + delivery and LearnStack job tables do not. Phase 11 must decide the exact + principal, minimum grants, interval and retention/replay floor before its first + writer; G18's inventory grants no purge authority. - **Cross-instance L1 cache invalidation** (`learnstack.cache.invalidation`). Port `ICacheService`, default implementation `InMemoryCacheService`, owning phase [Phase 11](phase-11-production-hardening.md), trigger "more than one application @@ -174,10 +179,11 @@ Each item below is named somewhere as adjacent to this phase's work. Each has an decides what it does to work already in flight — hold, drop, or dead-letter — beside the termination question it already carries. - **The documentation-lint CI promotion.** [Phase 02a](phase-02a-kernel-tenancy.md)'s - Packet 3b record assigns the XML-documentation link check and the prose-width check to - this phase, on the trigger that a second contributor gains write access. The trigger - has not fired; `P02b-8` picks them up if it does, and otherwise they travel to the - phase that inherits them. + Packet 3b record assigns XML-documentation target-existence and changed-prose + 88-column checks on the trigger that a second contributor gains write access. + [Phase 03](phase-03-identity-admin.md#cross-cutting-follow-up-at-phase-exit) + inherits both with that unchanged trigger. Markdown fragment lint establishes + neither check; the exit evidence records the live contributor census. - **The full authenticated browser end-to-end suite.** [Testing Standards § End-to-End Tests](../standards/06-testing.md#end-to-end-tests) assigns the full Playwright Test/axe suite to @@ -284,9 +290,9 @@ premise a row cites is re-verified at that pass rather than trusted. | G13 | What is the BFF session — its custody of the refresh token, its store, its idle and absolute lifetimes, its refresh serialisation under concurrent requests, its terminal `invalid_grant` behaviour, its CSRF control and its logout — and which document owns the access-token lifetime? | The `HttpOnly` cookie Security Standards already describes, encrypted by the session adapter, read only by server code, with single-flight refresh and one authority for the TTL | Phase-doc + one reconciled [Security Standards § Authentication](../standards/11-security.md#authentication); [ADR-0067](../decisions/0067-development-tenant-access-token-issuance.md) is the dedicated development-issuance authority; a new session ADR is required for a server-side store | P02b-6 (which document owns the access-token lifetime: the realm export and its reconciler write it), P02b-7 | Accepted — issuance-TTL part, [2026-10-21 package](phase-02b-delivery-log.md#p02b-6-decision-package-2026-10-20) and separate ADR-0067 acceptance on 2026-10-21; session part Accepted — [ADR-0070](../decisions/0070-owned-tenant-bff-sessions.md) and [revised package](phase-02b-delivery-log.md#p02b-7-revised-decision-package-2026-10-23), [acceptance](phase-02b-delivery-log.md#p02b-7-acceptance-and-implementation-2026-10-23), 2026-10-23 | | G14 | What bounds the request types reachable over HTTP while `AuthorizationBehavior` is `return next()`, and what is the shape of the token-keyed rate-limit stage behind a shared BFF connection? | An enumerated read-only routable set held by a catalogue-registered rule, and a limiter stage after `UseAuthentication` keyed on the validated subject. The early anonymous stage already runs before authentication: P02d-5 delivers 60/min per canonical direct or authenticated-hop visitor IP plus 600/min peer acquisitions/allocations under ADR-0053 and ADR-0054. Exhausted known visitors refuse before peer debit; unknown visitor allocation remains peer-gated. These remain IP/peer quotas, not token quotas; a request they reject never reaches the token stage. Re-verify the [P5 remediation decision](phase-02d-delivery-log.md#p02d-5-external-review-remediation-2026-10-09) before choosing authenticated accounting, preserving pre-classification protection against unknown-host abuse | Phase-doc + catalogue registration; a dated ADR-0032 Amendment for a deny-by-default step instead | P02b-5 (the token-keyed stage and the early stage's treatment of validated callers); G34's anonymous-hop policy and ADR-0054's bounded accounting replacement are Accepted and delivered in P02d-5 | Accepted — 2026-10-19; [P02b-5 package](phase-02b-delivery-log.md#p02b-5-decision-package-2026-10-19) | | G15 | What initiates a replay in this phase? | Targeted internal subscriber replay in P02b-3; producer/operator reset and fencing require a separate Phase 03 contract | Phase-doc; the URL space is its own decision record, per ADR-0036 | — (answered in § The consumer side; recorded so the question travels with the deferral) | Accepted — internal subscriber replay implemented by P02b-3 Step 4; operator contract Phase 03 | -| G16 | What is `LS0002`'s rule name, which project trees does it run over, what does it inspect, and what escalates it to Error? | The name and scope recorded the way Amendment 1 recorded `LS0001`, with the scope reaching the assemblies that actually handle tokens | A dated **ADR-0032** amendment + a catalogue entry + an `AnalyzerReleases` row | P02b-8 | Open | +| G16 | What is `LS0002`'s rule name, which project trees does it run over, what does it inspect, and what escalates it to Error? | The name and scope recorded the way Amendment 1 recorded `LS0001`, with the scope reaching the assemblies that actually handle tokens | A dated **ADR-0032** amendment + a catalogue entry + an `AnalyzerReleases` row | P02b-8 | Accepted — 2026-10-25; [acceptance](phase-02b-delivery-log.md#p02b-8-acceptance-2026-10-25), [ADR-0032 Amendment 6](../decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25); implementation and proofs complete in [Step 1](phase-02b-delivery-log.md#p02b-8-step-1-review-round-2-and-closeout-2026-10-25) | | G17 | What are the label sets for the event and job metrics, is the tenant axis permitted, and is it spelled `tenant` or `tenant_id`? | One note in the document that owns metric names, no raw tenant label on a per-event series, and an oldest-eligible-row age metric separate from the pending count | [Observability Standards § Required Metrics](../standards/10-observability.md#required-metrics) edit | P02b-2 (the first series ships there, and a label added afterwards touches every emitter already written) | Event metrics Accepted — 2026-10-12; runtime/guards [implemented](phase-02b-delivery-log.md#p02b-2-step-4--enforcement-and-closeout-2026-10-12); complete and merged; [merge closeout](phase-02b-delivery-log.md#p02b-2-merge-and-closeout-2026-10-13) owns CI/review/merge state; job label/observation contract Accepted — 2026-10-15 under ADR-0047; job instruments/guards implemented; [P02b-4 merge closeout](phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records final qualification and merge | -| G18 | May an integration-event payload or a job argument carry personal data, what may `last_error` contain, and do the four new durable stores enter the erasure scope? | Identifiers only, a sanitized and length-bounded failure descriptor, and the stores named in the erasure inventory | [Accepted ADR-0057](../decisions/0057-transactional-event-production-and-completion.md) decides the new producer payload/NULL JSON metadata policy and application byte cap; a dated ADR-0038 cross-reference under this acceptance. [Data Protection § Right to Erasure](../architecture/23-data-protection.md#right-to-erasure-right-to-be-forgotten), P02b-8 and Phase 11 retain erasure ownership | P02b-1 (the payload rule: the first payload ships there), P02b-2 (the `last_error` rule and its DDL bound), P02b-8 (the erasure inventory) | Payload and failure descriptors Accepted and implemented; job identifier-only payload/checkpoint and failure-descriptor bounds Accepted — 2026-10-15 under ADR-0047; job payload/checkpoint/failure bounds implemented; [P02b-4 merge closeout](phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records final qualification; erasure inventory open P02b-8 | +| G18 | May an integration-event payload or a job argument carry personal data, what may `last_error` contain, and do the four new durable stores enter the erasure scope? | Identifiers only, a sanitized and length-bounded failure descriptor, and the stores named in the erasure inventory | [Accepted ADR-0057](../decisions/0057-transactional-event-production-and-completion.md) decides the new producer payload/NULL JSON metadata policy and application byte cap; a dated ADR-0038 cross-reference under this acceptance. [Data Protection § Right to Erasure](../architecture/23-data-protection.md#right-to-erasure-right-to-be-forgotten), [the canonical inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory), Phase 03 privileged erasure/redaction and Phase 11 retained-copy/purge operations own their respective scope | P02b-1 (the payload rule: the first payload ships there), P02b-2 (the `last_error` rule and its DDL bound), P02b-8 (the erasure inventory) | Payload and failure descriptors Accepted and implemented; job identifier-only payload/checkpoint and failure-descriptor bounds Accepted — 2026-10-15 under ADR-0047; job payload/checkpoint/failure bounds implemented; [P02b-4 merge closeout](phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records final qualification; erasure inventory Accepted — 2026-10-25; [acceptance](phase-02b-delivery-log.md#p02b-8-acceptance-2026-10-25); the [canonical matrix](../architecture/23-data-protection.md#durable-asynchronous-store-inventory) includes the current event/job/vendor copies rather than the original four-store count; drift controls implemented and reviewed in [Step 2](phase-02b-delivery-log.md#p02b-8-step-2-closeout-2026-10-25) | | G19 | Where do the sample flow's publisher and consumer live — a fixture pair in the integration assembly, or a real event a shipped module consumes? | A real event between two shipped domain modules, because a test-assembly-only consumer leaves every module-scoped sweep with zero subjects | [Accepted ADR-0057](../decisions/0057-transactional-event-production-and-completion.md) and the P02b-1 package; reconcile Tenancy/Customization/Audit specs under this acceptance. ADR-0046 accepts distinct subscription deduplication and envelope delivery scope; P02b-3 implements the two effects and Seeder handoff. The provisioning publisher must prove enqueue from its transaction announcement while ambient context remains unresolved | P02b-1 | Flow and delivery contract Accepted; subscriptions/semantic Seeder handoff implemented by P02b-3 Step 5 | | G20 | What does an anonymous request to a **routed non-public** request type on a live tenant host answer — and does the catalogued `Backend_RequiresJwt_OnAllAuthenticatedRoutes` narrow to a surface outside tenant resolution? A second half rides with it: the shipped assertion middleware says that from this phase the refusal code differs by caller, `tenant_mismatch` for an authenticated one and `not_found` for an anonymous one, written by the middleware itself | AccountSite absent credentials give masked `not_found` 404 on tenant/organization/platform hosts. Invalid present credentials on known hosts give 401, including public routes. Rows 8/11/12 and authenticated assertions use `tenant_mismatch`; membership refusals and anonymous assertions use `not_found`; the generic unresolved MediatR gate is unchanged | The dated **ADR-0036** amendment G11 needs + a catalogue edit to that rule's Asserts line | P02b-5 | Accepted — 2026-10-19; [P02b-5 package](phase-02b-delivery-log.md#p02b-5-decision-package-2026-10-19) | @@ -530,110 +536,63 @@ LearnStack does not implement password hashing, password-reset rendering, MFA en or refresh-token rotation. Those live in Keycloak; the split is described in [Identity and Auth](../architecture/13-identity-and-auth.md). -- **The authentication wiring ADR-0036 stages here**, and its insertion order: - `UseAuthentication` above tenant resolution so a validated claim exists when the - resolver builds its attempt, `UseAuthorization` below the tenant assertions. Two - insertions, not one block, with an ordering rule and a planted-order companion - registered in the catalogue. The claim signal is populated at the one site the - resolver's comment reserves, from a validated `learnstack`-realm principal only. -- **One JWT authority for `/api/v1/*`**, the `learnstack` realm, with the issuer, the - audience, the algorithm allow-list, the clock skew, `azp`, and the rejection of ID - tokens all pinned. `Api_Registers_Only_The_Tenant_Realm_Authority` is catalogued to - this phase and its own note says the structural half passes while issuer validation is - disabled in configuration — the integration half is the load-bearing one. A - `learnstack-hub` token on a tenant-facing endpoint is refused here, not in - demand-gated Phase 02c. -- **The claim shape and the actor's identity**, under **G10**. The pipeline carries a - `UserId` from this phase on, and the resolver already dereferences one when a tenant - claim arrives with a subject, so the value is load-bearing rather than cosmetic. Phase - 03 owns the durable `sub` → `UserId` mapping; this phase owns where the claim comes - from and must not mint a fresh identifier per login. -- **Which matrix rows go live**, under **G11**. `demo-english` is a tenant-wide host and - `demo-yoga` maps to its default organization, so a tenant-only token on the yoga host - is a row that consults `ITenantMembershipReader` — registered as - `DenyAllTenantMembershipReader` until Phase 03. Whichever way G11 resolves, the - outcome is asserted rather than discovered: a successful Keycloak callback on its own - conceals it. -- **The host/JWT tenant cross-check.** A request whose host-derived tenant disagrees - with its JWT tenant returns 404 — not 403, which would confirm the resource exists — - through the **same** recorder and the **same** operation key Packet 9 shipped, with - `metadata.assertionSource = jwt-claim`, per - [ADR-0036 § Recording a rejected assertion](../decisions/0036-tenant-resolution-trusted-inputs.md#recording-a-rejected-assertion). - Not a second detector. The shipped types cannot carry that metadata yet — the - rejection record has no source, actor or correlation field, the recorder hard-codes a - null actor, and the resolver's refusal path only logs — so those are this phase's - edits. The organization dimension follows G11. The cross-check is a fault detector, - not an authorization control, and not the first isolation layer: Row Level Security - and the query filters precede it. -- **What an anonymous request to a routed endpoint answers**, under **G20**. The - catalogued `Backend_RequiresJwt_OnAllAuthenticatedRoutes` is booked to this phase and - says every endpoint outside the public allow-list answers 401 without a bearer token; - [ADR-0036's matrix](../decisions/0036-tenant-resolution-trusted-inputs.md#the-reconciliation-matrix) - row 2 says a non-`[PublicSurface]` request on a tenant host with no credential answers - 404, byte-identical to an unknown host's. Both cannot hold for the same request, and - the default `UseAuthorization` wiring answers the one the matrix forbids. The same - gate carries the refusal **code** split the shipped assertion middleware assigns to - this phase by name — `tenant_mismatch` for an authenticated caller, `not_found` for an - anonymous one, written by the middleware rather than left to the status-code pages. -- **Absence is not disagreement.** A token with no `tenant_id` claim resolves under the - host-only ceiling by design. What this phase must not do is let that be silent: with - the realm as it stands every token is claimless, so a lost mapper looks exactly like - an anonymous visitor. The claimless-token case on a tenant host has no matrix row at - all, and G11 gives it one. -- **The authenticated tier's bound**, under **G14**. Authentication goes live while - `AuthorizationBehavior` is still `return next()`, so without a bound any tenant user - reaches every routed request type until Phase 03. The token-keyed budgets that - [Security Standards § Rate Limiting](../standards/11-security.md#rate-limiting), - Standards 04 and the shipped limiter's own remarks assign to this phase go live with - authentication — they are also the bound ADR-0036 names for its per-occurrence - mismatch row, so activating that path activates this dependency. -- **Seed users**, under **G12**: tenant users only. Operators are the `learnstack-hub` - population and ADR-0004 Amendment 1 makes the separation a hard invariant — the - `learnstack` realm declares no platform-admin role and should not gain one. The - current dev export has no organization claim. **G11** decides whether this phase - mints one or deliberately refuses the authenticated organization-host case; - "across both organizations" is not yet an accepted promise. -- **Keycloak realm roles.** The realm ships three `tenant-*` roles with full scope on - both clients, so they appear in every token, while roles live in LearnStack and not in - Keycloak. Either they leave the realm or they are declared inert with a rule proving - no LearnStack assembly reads a role claim. A documentation link is not a mitigation - for a leak the realm actively causes. - -#### Correction: the realm emits no `tenant_id` claim at all - -This is an unimplemented prerequisite of this phase's authenticated cross-check. -`infra/keycloak/realms/learnstack.json` stores `tenant_id` as a **user attribute** and -declares **zero protocol mappers**. Keycloak does not put user attributes into tokens -unless a mapper says so. The API also has no JwtBearer registration or -`UseAuthentication` today: it does not validate those tokens or populate the -resolver's reserved claim signal. Current public requests use the delivered -host-only admission, query filters and Row Level Security. Authenticated behavior -must not go live until G10–G12 settle the token and resolution contract. - -Three changes, and the third is the one that makes the first two take effect: - -- An **`oidc-usermodel-attribute-mapper`** on a client scope shared by the API and the - BFF's client, projecting the attribute into the access token and the ID token, typed - as `String`, with an explicit audience mapper beside it. A mapper on the API's client - alone shapes nothing in a token minted for another client, which is the client the BFF - redeems the code with. -- The seeded value changed from the slug `"tenant-a"` to the seed tenant's **UUID**. The - claim is consumed as a `TenantId` — a Vogen value object over `Guid` from - [Phase 02a Packet 6](phase-02a-kernel-tenancy.md) — so a slug cannot be parsed. The - attribute is declared **admin-only** in the realm's user-profile configuration: it - alone raises a request to the host-and-claim authority ceiling, so a - self-service-writable attribute is a privilege-escalation path. -- A **reconciliation mechanism**, under **G12**. Keycloak consumes the realm import - once, at first start, and re-import overwrites nothing that already exists. A change - made only in the import reaches no existing workstation, and a Keycloak database wipe - is not the upgrade path — `make seed` today only polls each realm's discovery endpoint - and never writes to Keycloak. Without this step the token-shape test below is green in - CI on a fresh container while every warm workstation issues claimless tokens. - -The test asserts the shape rather than the configuration file: a token issued by the dev -realm for a seed user carries a `tenant_id` claim that parses to that seed tenant's -`TenantId`, and the realm export's seeded value equals `SeedData`'s literal. A realm -export that loses the mapper fails it. +- **Ordered authentication.** `UseAuthentication` runs before tenant resolution; + `UseAuthorization` follows tenant assertions. The resolver consumes only the + validated `learnstack` principal. The catalogue's ordering rule includes a + planted-order control. +- **One tenant API authority.** [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md) + owns the closed issuer/audience/algorithm/purpose/claim profile and key-refresh + behavior. Real signed HTTP and provider cases complement the structural + authority census; `learnstack-hub` tokens are refused on tenant endpoints. +- **Stable actor identity, G10.** The protected UUID-valued `user_id` supplies + `UserId`; `sub` remains Keycloak's subject. No identifier is minted per login. + Phase 03 owns durable subject/actor mapping and the identity domain. +- **Explicit matrix outcomes, G11.** Matching tenant/organization claims enable + rows 6/9 on the two seed hosts. Rows 7/10/14 remain membership-dependent + refusals under `DenyAllTenantMembershipReader` until Phase 03. Claimless valid + principals retain public-only HostOnly authority and a bounded diagnostic; + they gain no authenticated tenant authority. +- **One attributed rejection recorder.** Host/JWT disagreements use the existing + operation key with captured source, actor, correlation and trusted organization + attribution. [ADR-0065](../decisions/0065-bounded-tenant-assertion-diagnostics.md) + bounds durable authenticated admission per defended tenant; suppressed + occurrences retain diagnostics and their refusal. Platform-host membership + refusal has no confirmed host tenant and writes no tenant audit row. +- **Closed HTTP outcomes, G20.** Absent AccountSite credentials return masked + `not_found` 404 on known tenant, organization and platform hosts. Present + invalid/undecidable credentials return 401 on known hosts, including public + routes. Authenticated tenant/organization disagreements use 404 + `tenant_mismatch`; anonymous assertions and membership refusals use + `not_found`, as specified by ADR-0064. +- **Bounded authenticated surface, G14.** The additional validated-subject tier + runs behind the unchanged visitor/physical-peer floors; it promises no + end-to-end 600/minute allowance. While authorization remains a pass-through, + the routable census admits the existing public reads and the exact physically + read-only AccountSite request, with separate infrastructure exclusions. +- **Realm roles convey no LearnStack authority.** The three `tenant-*` roles and + full scope on both named clients remain in the development realm. Assigned + role claims are inert: `Keycloak_Roles_Are_Not_Application_Authority` holds the + production claim-consumer boundary. Phase 03 supplies LearnStack permissions. + +#### Realm issuance and warm reconciliation + +The committed tenant realm issues the accepted UUID profile through a shared +client scope: tenant/actor/organization attribute mappers and the API audience +mapper serve the named API and confidential BFF clients. The three identity +attributes are admin-only in the user profile. Four stable seed actors agree with +`SeedData`; both tenant and organization host outcomes are asserted. + +`make seed` and local `make demo` invoke the shared bounded reconciler. It upgrades +qualified historical warm realms, preserves existing accounts/credentials/MFA and +the Hub realm and reads back the owned state. Real warm-provider controls include +an independently observed zero-write repeat. +[ADR-0068](../decisions/0068-development-warm-realm-qualification.md) owns the +limited profile preparation and stock account-console scope detachment; +[ADR-0067](../decisions/0067-development-tenant-access-token-issuance.md) owns +development issuance lifetime. Fresh-file tests and real warm-provider tests are +separate proof subjects: changing an import alone cannot update an existing realm. +The pre-mapper/claimless baseline remains in the dated delivery records, not as a +current implementation claim here. #### The BFF session @@ -727,22 +686,23 @@ points it does not reach, and both of Packet 9's hand-offs land here. routine polls/claims/acknowledgements/retries from per-invocation security audit. Existing `EnterPlatformAdminScope` entry audit and all other bypass obligations remain unchanged. This is no general background-job exemption. -- **The rejected-assertion row names its actor once there is one.** The recorder writes - a null actor on the authenticated tier today, because no principal exists in the - process and `IsAuthenticated` is a tier rather than an identity. ADR-0036 makes the - actor the finding on that tier, so the realm integration above populates it from the - validated token's user — the observable that also proves the assertion middleware runs - after authentication. +- **Attributed rejected assertions.** Admitted authenticated mismatches use + captured actor/source/correlation and trusted organization attribution under + ADR-0064/0065. The standalone audit refusal path preserves the HTTP refusal on + store failure. Suppressed events and no-confirmed-tenant refusals remain + distinct diagnostics rather than fictitious durable rows. - **Causal actor and causation.** P02b-3 supplies the validated incoming event ID to consumer audit intents and follow-up outbox production; causal actor remains separate from effective SystemActor. Nested commands inherit these identifiers, while a newly drained domain event supplies its own causation ID. The Accepted **G6** producer/common-owner contract owns these bounded metadata keys. -- **Classification for the operations this phase introduces** — the sample flow's - command, the first authenticated read, login, logout and refresh — registered in their - owning module's catalogue source and matrix before their handlers ship, because an - operation the catalogue does not classify is refused, and the join is total in both - directions. The authenticated read carries no permission key until Phase 03. +- **Total module operation classification.** The sample flow's commands and + subscriber operations are registered in their owning catalogues/matrices. + `GetAccountSiteQuery` is explicitly `Off`, with no audit row or permission key. + Selected provider authentication events belong to Keycloak under + [Standards 18](../standards/18-audit-coverage.md#operation-types), not module + handler registration; local BFF lifecycle has no durable LearnStack ledger + under ADR-0070. Phase 03 owns the authenticated identity-event ingress/mirror. The `AuditEntry` aggregate is owned by the **Audit** module and shipped in Phase 02a; rows arrive through the store's parameterised inserts, and @@ -752,41 +712,26 @@ and coverage matrix against it. See ### Compile-time secret leakage (carried out of Phase 02a Packet 3) -Packet 3 shipped runtime redaction — the Serilog enricher and the local error tracker -both scrub the same set through the single `SensitiveTokenCatalog`. It covers logs, OTLP -and error-tracker tags. It does not cover a value already interpolated into an exception -**message**, and this phase adds three durable sinks for one: an outbox row's -`last_error`, a subscriber-side failure record, and a job's persisted failure state. -Those sinks, not a Problem Details body, are the threat this phase's diagnostic answers -— the response factory builds no free text from an exception message. - -`LS0002` is planned, not shipped; its initial Warning severity does not itself -make a build fail. A roadmap document is not its diagnostic registry. -**G16** records it the way ADR-0032 Amendment 1 recorded `LS0001`: its -`LearnStackException-` rule name, the project trees it runs over, what it -inspects, its `AnalyzerReleases` row, its catalogue entry, and the condition that -escalates it from Warning to Error. Two things the record has to settle rather than -inherit: - -- **Its scope.** `LS0001`'s `Domain` + `Application` reference set excludes the - assemblies where this phase handles tokens and provider errors, which is where the - sinks are. -- **Its token source.** The analyzer targets a different framework from the assembly - that holds `SensitiveTokenCatalog`, whose own remark says new tokens land there and - not in consuming projects, and the catalogue's public accessor exposes only part of - the set. A drift test is what makes "matches `SensitiveTokenCatalog`" true rather than - aspirational. - -Its own tests assert the positive case, a clean case staying clean, a sensitive name -outside a `throw` staying clean, no `AD0001` crash — the failure mode ADR-0032 Amendment -1 records for `LS0001` — and that the analyzer's token set equals the catalogue's. - -P02b-2 bounds the durable failure descriptor under **G18** to closed stage, -reason and category codes, with only allowlisted SQLSTATE where applicable; -exception text/type, trace identity and payload are not persisted there. The -canonical DDL owns the byte bound. Step 1 implements the migration beside the -lease columns, including redaction of legacy descriptors without rewriting -event facts/state; Steps 2–3 implement transitions and bounded diagnostics. +Runtime property/tag redaction and compile-time exception-message checking are +complementary. Property redaction does not scrub arbitrary exception messages; +producer, delivery and job stores separately retain only their accepted closed, +bounded failure descriptors rather than raw exception text. + +[ADR-0032 Amendment 6](../decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25) +defines `LS0002`; its canonical rule and proof owners are in the +[catalogue](../standards/21-architecture-tests-catalogue.md#learnstackexception-sensitiveexceptionmessage-roslyn-analyzer). +The rule covers every production C# project, preserving `LS0001`'s narrower +Domain/Application scope. Both runtime and analyzer compile the same internal +word matcher and complete token sets. Synthetic compilations, loaded token +parity, a two-word-only source mutation, evaluated project wiring and actual +CI-warning builds prove their respective boundaries. Initial Warning severity +does not fail the build; Phase 03 exit promotes both rules to Error. + +The diagnostic is name-based, with bounded expression forms. It does not prove +secret absence, trace earlier assignments or cover TypeScript/JavaScript. Review, +closed diagnostic contracts and durable failure-descriptor bounds remain +necessary. [Error Handling](../standards/09-error-handling.md#sensitive-exception-messages) +owns the ongoing exception-message rule and its limits. ### Architecture tests @@ -803,11 +748,9 @@ What this phase owes the catalogue beyond implementing those rows: - **Producer rows delivered by P02b-1:** the announced-transaction write, produced-work refusal, owner-only completion, outbox-only domain handlers and - identifier-only payloads. Later decision passes register and implement the - ADR-0036 middleware-ordering rule, the - routable-set bound (**G14**) and the Keycloak-role-claim rule — with the realm-role - question it answers — in `P02b-5`, where the API first reads a claim; and `LS0002` - under its rule name (**G16**) in `P02b-8`. + identifier-only payloads. The middleware-ordering rule, routable-set bound + (**G14**) and inert Keycloak-role-claim controls are implemented under ADR-0064; + `LS0002` is implemented under ADR-0032 Amendment 6 (**G16**). - **Widened assertions** where a catalogued rule is satisfied by the defect it exists to catch. P02b-1 extends `Outbox_Row_Carries_Correlation_Context` to exact stored identity, tenant/organization, full traceparent and partition values, including @@ -819,7 +762,8 @@ What this phase owes the catalogue beyond implementing those rows: stale-transition refusal; Step 3 implements the actual two-worker proof. P02b-4's accepted `BackgroundJob_Submission_Is_Transactional_And_Stamped` replaces `Hangfire_Job_Payloads_Include_TenantId` with tenant/org/actor/trace and atomic - submission proofs under Accepted ADR-0047; it is not Implemented today. + submission proofs under Accepted ADR-0047; its canonical owner and controls + are Implemented. `OutboxProcessor_NeverBlocks_OnSingleMessageFailure` gains the hanging-handler case. Two rules the catalogue stamps **02a** also widen here, so the Phase-field sweep above does not reach them: the transport arm of @@ -853,10 +797,11 @@ so "the architecture suite is green" does not reach them. `backend integration (Testcontainers)` is already a required check; the [P02b-0 receipt](phase-02b-delivery-log.md#p02b-0-entry-verification-2026-10-12) verifies all seven current required contexts with strict up-to-date protection. `P02b-8` re-verifies those -live settings under the exact reported names. `scripts/assert-tests-ran.py` -already rejects a missing assembly, zero executed tests and any unexecuted test -in the required assemblies; test failures additionally fail the `dotnet test` -command. The phase retains zero skips, per assembly. +live settings under the exact reported names. The current +`scripts/ci-test-shards.py aggregate-*` owners validate complete current-attempt +case identities and zero skips through `ci-test-shard-results.py`; they reject +missing assemblies, unexecuted cases and non-passing outcomes. The phase retains +zero skips, per assembly. ## Deliverables @@ -951,7 +896,7 @@ command. The phase retains zero skips, per assembly. and both visible to the trait sweep. - `LS0002` shipping as a Warning under its catalogued rule name, with its ADR-0032 amendment, its catalogue entry, its `AnalyzerReleases` row, its linked token source - and its four tests. + and compiler, token-parity, mutation, wiring and real-build proofs. - **Carrier reconciliation**, in the change that lands each mechanism: [Events and Outbox](../architecture/15-event-and-outbox.md) (§ Inbox table, § Subscriber side, § Ordering, § Dead-letter — producer side, whose pushed-out @@ -978,8 +923,8 @@ command. The phase retains zero skips, per assembly. Hangfire dashboard route behind the Platform-scope permission with its ADR-0015 amendment, the operator recovery surface, and this phase's stale in-code messages; [Phase 11 § Data Operations](phase-11-production-hardening.md#data-operations), which - acquires the processed-outbox and aged-inbox purge under the `learnstack_platform` - `DELETE` grant with the no-principal constraint **G9** carries; + owns purge decisions against the actual per-store grants and immutable-fact + boundaries, including G9's absent recurring-maintenance principal; [Phase 08a](phase-08a-assessment-notifications.md), which credits `OutboxFlushBehavior` to Phase 02a and books the queue two ways; and `infra/apisix/README.md`, which dates the dashboard's gateway gating to Phase 08a. Two @@ -1101,8 +1046,12 @@ this document; this section names criteria and the records that prove them. remain observed and hold their local partition; unrelated work progresses within the accepted cap. An uncertain physical COMMIT is Indeterminate and recovers from atomic durable state rather than assuming rollback. -- A frame whose captures name an aggregate root that no intent in the frame declares - produces the behaviour G6 records. +- An audit row uses only the captures belonging to its intent's declaring frame + and declared aggregate type. A captured root of another type does not reach + that row's snapshots or changes, under + [ADR-0044 Amendment 5 § 2](../decisions/0044-audit-write-path.md#2-entity_type-and-entity_id-come-from-the-intents-declared-aggregate) + and [Amendment 6 § 3](../decisions/0044-audit-write-path.md#3-each-intent-keeps-its-own-requests-result-the-transactions-state-says-only-what-it-can). + ADR-0057's common owner preserves these composition and frame rules. - A consumer handling an event caused by user U writes a row whose metadata names U and the consumed event, and the follow-up outbox row carries that event as its causation. - Every registered off-path dead-letter slug has a matrix row in the module that writes @@ -1149,7 +1098,8 @@ CI and merge verification; its dated local receipts retain their original scope. structural realm-authority rule cannot see. - On `demo-english`, an authenticated read answers 200 under the host-and-claim ceiling; a token naming the other seed tenant returns 404 and produces exactly one rejection - row under the host's tenant carrying a non-null actor, the request's correlation id, + row under the host's tenant while durable audit allowance is available, carrying + a non-null actor, the request's correlation id, and `metadata.assertionSource = jwt-claim`. A catalogue sweep finds no second slug for the cross-check. - On `demo-yoga`, an organization host, the same request produces the outcome **G11** @@ -1175,12 +1125,13 @@ CI and merge verification; its dated local receipts retain their original scope. and zero on rollback. P02b-3 proves independent create-only `card@1`/`plain@1` delivery, sibling recovery, preserved authored/deleted definitions, semantic built-in identity verification and concurrent fresh seed/delivery convergence. -- Two principals behind one BFF do not share an authenticated quota: through the - **whole** middleware chain, from one peer address, one exhausts that budget and - the other's next request is not 429. G14 settles the delivered pre-auth visitor/ - peer floor's treatment of validated callers; anonymous unknown-host abuse stays - bounded. The 429 carries the one Problem Details shape and `Retry-After`, and - repeated mismatches from one token reach 429 and stop producing audit rows. +- Two principals behind one BFF do not share the additional subject quota. The + actual whole-chain control uses a reduced subject budget below the unchanged + visitor/peer floors: one subject exhausts it while the other's next request + from the same peer succeeds. Separate production-floor controls prove the + earlier IP/peer stages can still refuse validated subjects; no end-to-end + 600/minute allowance is inferred. The 429 has the canonical Problem Details + shape and `Retry-After`; quota refusal precedes the durable assertion recorder. - A second `make seed` against a Keycloak database created from the pre-mapper realm JSON leaves every existing account and the `learnstack-hub` realm intact, applies the client scope and the mappers, and yields a token carrying a UUID-valued `tenant_id`. A @@ -1230,8 +1181,8 @@ CI and merge verification; its dated local receipts retain their original scope. non-sensitive interpolation and on a sensitive name outside a `throw`, produces no `AD0001`, and its token set equals the union of the catalogue's single- and two-word sets — proved by a token added only to the two-word set failing the drift case — with - its rule name, catalogue entry and `AnalyzerReleases` row in the same commit as the - analyzer. + its rule name, catalogue entry and `AnalyzerReleases` row accepted before the + analyzer implementation, as the approved decision sequence requires. - The phase's authenticated endpoint appears in the generated OpenAPI document and in the regenerated SDK surface. - Every event metric uses the literal name and bounded dimensions in @@ -1242,11 +1193,13 @@ CI and merge verification; its dated local receipts retain their original scope. the [P02b-4 merge closeout](phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records final qualification, while Standards 10 owns the exact inventory. - **No row in the [catalogue](../standards/21-architecture-tests-catalogue.md) whose - Phase names 02b is still Registered or Awaiting backfill.** Structural rows are green - in the `backend` check and behavioural rows in the `backend integration` check, which - this phase makes a required one; neither job reports a skipped case in the assemblies - this phase touches. Every structural rule this phase implements has a planted offender - and a companion that fails when the rule's predicate is removed. + Phase names 02b is still Registered or Awaiting backfill.** This includes the + inherited nineteen P02b-4 obligations and the analyzer/inventory additions. + Each owner runs in its actual required context: backend base/architecture + behind `backend`, real database/provider/native work behind `backend integration`, + frontend boundaries/behavior in `frontend`, and offline CI controls in `meta`. + None reports skipped cases. Each structural rule has a planted offender and + a companion that fails when its predicate is removed. ## Risks @@ -1296,13 +1249,14 @@ CI and merge verification; its dated local receipts retain their original scope. mitigation is an integration test that commits and rolls back both together, registered as a new catalogue row rather than assumed to exist. - **Authentication goes live with authorization still a pass-through.** Between this - phase and Phase 03 any tenant user reaches every routed request type. G14 bounds the - routable set and holds the bound with a rule; the token-keyed limits land in the same - packet because admitted per-occurrence assertion auditing depends on them; + phase and Phase 03 authorization does not enforce permissions. G14's closed + read-only routable set and its census prevent that gap from exposing arbitrary + request types; the additional subject limits bound admitted assertion traffic; ADR-0065 separately bounds aggregate audit admission per defended tenant. -- **The access-token TTL is the revocation window.** Between this phase and Phase 03 no - membership check runs and `AuthorizationBehavior` is a pass-through, so a token keeps - tenant access for its full lifetime after the attribute behind it is removed. The +- **The access-token TTL is the revocation window.** Before Phase 03, matching + host/claim rows 6/9 do not re-read live membership and + `AuthorizationBehavior` is a pass-through, so a token can retain that authority + for its remaining lifetime after the backing attribute is removed. The mitigation is the single TTL authority this phase links plus Phase 03's membership read; until then the window is a stated property, not an accident. - **Refresh-token rotation is off in the dev realm.** The realm this phase hardens @@ -1327,10 +1281,9 @@ CI and merge verification; its dated local receipts retain their original scope. refresh/deadline rules apply; masked 403/404 can still revoke. Phase 11's distributed adapter/proxy qualification precedes multiple web processes. - **Keycloak claims leak into authorization decisions.** Keycloak authenticates; - LearnStack authorizes. The realm currently ships three tenant-shaped realm roles with - full scope on both clients, so the mitigation is the realm-role resolution above plus - a rule proving no LearnStack assembly reads a role claim — not a link to the document - that states the split. + LearnStack authorizes. Development role claims remain present, so the + implemented `Keycloak_Roles_Are_Not_Application_Authority` census must continue + to reject their use as permission or membership authority. ## Phase Exit Decision @@ -1344,8 +1297,10 @@ CI and merge verification; its dated local receipts retain their original scope. - An authenticated request answers on a named `/api/v1/*` endpoint on `demo-english`, the organization host's documented outcome is asserted, and a `learnstack-hub` token is 401. -- The host-vs-JWT cross-check returns 404 and writes one row under Packet 9's existing - operation key with a non-null actor and `metadata.assertionSource = jwt-claim`. +- The host-vs-JWT disagreement returns 404 and writes one admitted row under + Packet 9's existing operation key with a non-null actor and + `metadata.assertionSource = jwt-claim`. ADR-0065's audit allowance and + ADR-0064's no-trusted-tenant/no-row exceptions remain authoritative. - The sample integration event flows enqueue → outbox → dispatch → idempotent consumption. Forced interleaving proves one live producer owner; publication stays at least once. **Forced redelivery** produces one committed business @@ -1360,9 +1315,11 @@ CI and merge verification; its dated local receipts retain their original scope. restored from its real durable row; opaque transport hints carry no tenant payload. - Both Phase 02d sites still render anonymously with Keycloak stopped. - `LS0002` ships as a Warning with its record, its catalogue entry and its release row. -- No catalogue row whose Phase names 02b is still Registered or Awaiting backfill; both - CI checks are green with no skipped case in the assemblies this phase touches; and the - behavioural job is a required check, with the branch-protection date recorded. +- No catalogue row whose Phase names 02b is still Registered or Awaiting backfill. + Every required backend, integration, frontend, meta, OpenAPI and public-demo + owner passes its actual population with no skips. `backend integration + (Testcontainers)` remains a required check, verified by dated live protection + readback under its exact name. [Phase 02c](phase-02c-hub-foundation.md) is unblocked by this phase but does not gate it. Phase 02c hangs off the spine and starts only when its own trigger fires — a tenant diff --git a/docs/roadmap/phase-02b-exit-evidence.md b/docs/roadmap/phase-02b-exit-evidence.md new file mode 100644 index 000000000..6e7ed535a --- /dev/null +++ b/docs/roadmap/phase-02b-exit-evidence.md @@ -0,0 +1,171 @@ +# Phase 02b exit evidence index + +This index preserves source order for all 26 top-level Deliverables, 60 Completion +Criteria and 11 Phase Exit Decision obligations in [Phase 02b](phase-02b-events-auth.md). +The abbreviated locators below do not replace, weaken or omit the canonical bullet's +subordinate conditions. Each row refers to its entire canonical bullet. + +This is an ownership index. The +[P02b-8 correction closeout](phase-02b-delivery-log.md#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) +records completed exact-source A/B, artifact/skip/cleanup evidence and the dated +live required-check read-back. The review PR's live checks own qualification of +its actual current head. The frozen-source receipt does not imply a passing +result for a later documentation-only commit; maintainer review and merge remain +separate gates. + +Evidence lanes: **B** = backend base/unit/architecture and non-Docker HTTP tests; +**I** = real Docker/PostgreSQL/Keycloak/native-HTTPS integration; **F** = frontend +Vitest/source/boundary behavior; **J** = stopped-provider public browser and 27 +Lighthouse audits; **O** = generated OpenAPI/SDK and required diff check; +**M** = source/governance/manual census and offline `meta` controls. The executed +case and trait census assigns real Docker/native work to I and base HTTP work to +B, including tests in the `LearnStack.Tests.Integration` assembly. + +Backend class names resolve in Unit, Architecture, Integration or Contract projects +under `backend/tests/`. A partial filename is identified separately from its +declaring test class. +Integration database classes live in `Database/`; provider/native classes live in +`TenancyIdentity/`. Frontend paths are relative to `frontend/apps/web/` unless an +SDK or repository-root path is shown. A filename without a directory identifies +the matching source under that root. Each row names the proof owner for its +particular assertion. Execution evidence remains the responsibility of that +owner's required lane and the Step 4 record. + +## Deliverables + +| ID | Canonical requirement locator | Named evidence / carrier | Lane | +|---|---|---|---| +| D01 | ADR-0046 Accepted; inbox/ledger runtime distinct from acceptance | ADR-0046 Status/dated disclosures; `EventDeliveryMigrationTests`, `DurableEventAcceptanceTests`, `InboxGuardTests`, `DeliveryExecutionTests`, `DeliveryDispatchStoreTests`, `DeliveryProcessorTests`; C13–C20 discriminate its runtime contract. | M, I | +| D02 | ADR-0047 Accepted; ADR-0003 storage amendment | ADR-0047 and ADR-0003 dated amendment; `BackgroundJobStorageMigrationTests`, `HangfireStorageTests`, `BackgroundJobBusinessTests`; catalogue's nineteen complete job obligations name their individual owners. | M, B, I | +| D03 | Every dated register amendment Accepted before governed code | The canonical decision register links each corresponding dated amendment; git ancestry/dated package census verifies ordering. The register, rather than a second partial ADR list here, defines the complete set. Acceptance alone is not runtime proof. | M | +| D04 | Canonical inbox DDL, policy/grants, replay contract, ADR-0023 correction | Database Standards § Inbox; ADR-0023 erratum; `EventDeliveryMigrationTests.Canonical_document_ddl_produces_the_same_applied_inventory_as_the_migration`, `Exact_column_grants_exclude_envelope_reads_completion_forgery_and_purge`; Phase 11 § Data Operations owns purge interval. | M, I | +| D05 | Immediate `IOutbox` INSERT; invariant guard and transaction | `OutboxProducerTests`, `ProducerExecutionTests`, `OutboxProducerConventionTests`, `OutboxContractTests`; C01/C24/C25 and ADR-0057. | B, I | +| D06 | Provisioning fact; two create-only defaults; Seeder handoff | `TenantCreatedProducerTests.Provisioning_business_outbox_and_both_MUST_rows_share_one_commit`; `CustomizationDefaultDeliveryTests` stored/fresh, exact-redelivery and Seeder-race cases; `CustomizationDefaultInitializationTests` lifecycle/semantic identity cases. | I | +| D07 | Fenced producer lease/retry/terminal and grant migration | `OutboxDispatchMigrationTests`, `OutboxDispatchStoreTests`, `OutboxProcessorTests`; C03–C06/C11/C12. | I | +| D08 | Keyed lazy guarded credential; nonempty offender census | `OutboxDispatcherDataSourceGuardTests`, `OutboxDispatcherRoleGuardTests`, `OutboxProductionCompositionTests`; `OutboxDispatchConventionTests.LearnStack_OutboxAdmin_Role_OnlyUsedBy_OutboxProcessor` and its credential registration/resolution dirty controls. | B, I | +| D09 | Stored/rebuilt partition; abstract derivation and per-key serialization | `IntegrationEventContractTests`, `OutboxProducerTests.Both_roots_insert_the_complete_runtime_event_before_business_and_MUST_audit_commit`, `OutboxProducerTests.An_HTTP_request_commits_the_enqueuing_trace_announced_scope_and_exact_partition`, `DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context`; `OutboxEnvelopeReaderTests`; inherited transport/partition controls. | B, I | +| D10 | Shared inbox, guard-before-construction, context | `InboxGuardTests`, `EventDeliveryMigrationTests`, `DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context` and durable duplicate case; `OutboxDispatchConventionTests` (`IntegrationDeliveryBoundaryTests.cs`) / `OutboxDispatchConventionTests` (`DeliveryOwnerBoundaryTests.cs`). | B, I | +| D11 | Independent subscriber terminal/audit/replay; no operator reset | `DeliveryDispatchStoreTests` retry/audit/replay cases; `DeliveryProcessorTests.Siblings_have_independent_retries_and_Active_delivery_runs_beside_exact_Pending_and_privileged_holds`; `DeliveryObservationTests`; Phase 03 owns operator permission/reason/fence. | B, I, M | +| D12 | Real worked enqueue → dispatch → idempotent effect | `CustomizationDefaultDeliveryTests.Stored_backlog_and_fresh_provisioning_reach_both_real_subscribers` and `Reaccepting_the_exact_provisioning_fact_does_not_repeat_inbox_effect_or_audit`; `OutboxDispatchConventionTests` (`IntegrationDeliveryBoundaryTests.cs`) requires both real scoped Active subscriptions and nonzero production subjects. | B, I | +| D13 | Saved domain facts drained once, before invariant/MUST audit | `DomainEventProductionTests` FIFO/save qualification/bounds/atomicity cases; `DomainEventHandlerTests.Domain_Event_Handlers_Are_Outbox_Only` and complete helper/interface offenders; `DeliveryExecutionTests.Actual_delivery_owner_drains_saved_domain_facts_and_rolls_back_translation_failure`. | B, I | +| D14 | Shared audit owner and four owner acts | `ProducerExecutionTests` direct owner, unregistered owner, Off/nested and common-scope cases; `DeliveryExecutionTests` success/fault/ownership-loss cases; `AuditLogBehaviorTests`, `TransactionBehaviorTests`, `DeliveryCommitGateTests`; C21–C28 retain individual conditions. | B, I | +| D15 | Guarded runner/storage/context/pins; no definitions/dashboard | Catalogue's nineteen job obligations and actual owners; `BackgroundJobSubmissionTests`, `BackgroundJobPayloadTests`, `BackgroundJobBusinessTests.Context.cs`, `HangfireStorageTests`, `BackgroundJobProductionManifestTests`; package lock/pins and ADR-0047. | B, I, M | +| D16 | Private producer/subscriber health and bounded snapshots/metrics | `OutboxDispatchConventionTests` (`OutboxDispatchObservationTests.cs`), `OutboxObservationTests`, `DeliveryObservationTests`; `OutboxDispatchStoreTests.Queue_snapshot_counts_every_pending_state_but_ages_only_publish_eligible_work`; `OutboxProcessorTests`, `DeliveryProcessorTests` health/refresh cases; Standards 10 inventory. | B, I | +| D17 | Middleware positions, JWT contract, subject quota plus visitor/peer floors | `TenantAuthenticationHttpTests.Authentication_Middleware_Order_Is_Enforced`, `Api_Registers_Only_The_Tenant_Realm_Authority`; `TenantAuthenticationProfileTests`, `AuthenticatedRateLimitTests`, `RateLimitingHttpTests`; Security 11 authentication and Standards 04 quotas. | B, I, M | +| D18 | Rejection source/actor/correlation and recorder use | `AuditingTenantAssertionRecorderTests`, `TenantAuthenticationReconciliationTests`, `TenantAuthenticationRejectionAuditTests`; `AccountSiteHttpTests.Audit.cs` actual route/header attribution. | B, I | +| D19 | Existing host/JWT refusal slug and 404 | `AccountSiteHttpTests.Actual_account_route_preserves_claim_and_membership_codes_and_durable_host_attribution`; `TenantRealmApiTests.Real_cross_tenant_tokens_refuse_before_configuration_and_audit_the_defended_host`; `AuditCoverageTests` matrix/registration census. | B, I | +| D20 | Real realm scopes/mappers/profile/seed/role/callback shape | `AuthenticationAuthorityTests.Keycloak_Roles_Are_Not_Application_Authority`, `TenantRealmExportTests`, `TenantRealmIssuanceTests`, `TenantRealmProfileProtectionTests`, `TenantRealmSelfServiceTests`, `TenantRealmApiTests`; committed realm JSON and `SeedData`. | B, I, M | +| D21 | Warm idempotent reconciliation preserves accounts/Hub | `TenantRealmReconciliationTests` fresh zero-write, interrupted/uninterrupted legacy upgrade, conflict/no-write and read-back cases; `scripts/reconcile-development-realm.test.mjs`. | I, M | +| D22 | Tenant-host PKCE/native owner/cookies/refresh/CSRF/logout/helper | `bff-session-routes.test.ts`, `session-store.test.ts`, `bff-auth-admission.test.ts`, `bff-boundaries.test.ts`, `provider.test.ts`; both separate real-chain/browser `TenantBffSessionTests`; `add-frontend-route` / `add-feature-gated-ui` shipped-helper carriers. | F, I, M | +| D23 | Authenticated read, guarded page, OpenAPI/SDK | `AccountSiteHttpTests` / `AccountSiteQueryTests`; `src/server/auth/middleware.test.ts`, `src/components/auth/shell.test.tsx`; `OpenApiContractTests.PublicSurface_Contract_Matches_Served_OpenApi`, `backend/openapi/v1.json`, `frontend/packages/sdk/src/authenticated-contract.test.ts`, `authenticated-server.test.ts`; `openapi diff`. The page guard is frontend behavior; OpenAPI describes the HTTP endpoint. | B, I, F, O | +| D24 | Real committed-realm fixture and controlled JWT issuer, truthful traits | `TenancyIdentity/KeycloakFixture*`, `TenantAuthenticationIssuer.cs`; `PersistenceConventionTests.Every_Database_Test_Carries_The_Docker_Trait` / `The_Docker_Trait_Sweep_Can_Actually_Fail` and P02b-6 missing-trait controls; CI native partitions keep real provider/native work in I. | B, I, M | +| D25 | LS0002 Warning, source parity, compiler/mutation/wiring/build proofs | `SensitiveExceptionMessageAnalyzerTests`, `SensitiveTokenCatalogTests`, `AnalyzerBuildTests`; `AnalyzerWiringTests`, `SensitiveExceptionMessageTests` production/suppressed corpus; ADR-0032 Amendments 6–7, catalogue rule and `AnalyzerReleases.Unshipped.md`, linked `SensitiveTokenMatcher` source. | B, M | +| D26 | Entire enumerated carrier reconciliation | The carrier audit covers architecture 13/14/15, standards 05/06/07/09/10/11/20, glossary, `add-integration-event`, Phase 03/08a/11, APISIX README and the post-commit seam comment. Their owning packets and Step 3 reconcile the shipped contracts; an already-current carrier needs no new edit. `CorpusConsistencyTests`, fragment and roadmap lint check structure/owner links; the dated semantic review checks the enumerated claims. | M, B | + +## Completion criteria + +| ID | Canonical requirement locator | Named discriminating evidence | Lane | +|---|---|---|---| +| C01 | Producer state/outbox atomicity and every refusal before INSERT | `OutboxProducerTests` both-roots commit, cancellation/fault, real MUST failure, unusable transaction/tenant, raw/enrolled/foreign/stale/provisioning cases; `TenantCreatedProducerTests`; `OutboxProducerConventionTests`. | B, I | +| C02 | HTTP and delivery trace/context/exact nonnull partition | `OutboxProducerTests.An_HTTP_request_commits_the_enqueuing_trace_announced_scope_and_exact_partition`; `DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context` explicitly asserts stored outgoing trace, tenant/org and nonempty exact partition. | I | +| C03 | Forced independent-store contention; confined grants/fresh tokens | `OutboxDispatchStoreTests.Two_independent_stores_contend_for_one_committed_live_lease`, `Concurrent_stores_claim_distinct_rows_without_owning_a_batch`; `OutboxProcessorTests.Two_independent_actual_processors_cannot_publish_or_claim_one_live_lease_twice`; migration grants. | I | +| C04 | Recovery token fencing and no seventh crash publication | `OutboxDispatchStoreTests.Recovery_by_the_same_store_replaces_the_token_and_fences_every_stale_transition`, terminal reacquisition/expiry cases, `Failed_or_crashed_sixth_claim_requests_terminalization_and_never_claims_a_seventh`. | I | +| C05 | Producer terminal+one MUST row; audit refusal and terminal-only retry | `OutboxDispatchStoreTests.Refused_audit_rolls_back_the_terminal_update_and_retains_the_request_for_audited_retry`, lost COMMIT, substitution and stored metadata cases; `OutboxProcessorTests.A_poison_first_row_terminalizes_with_MUST_audit_and_following_acceptance_progresses`. | I | +| C06 | Five retry delays, closed descriptors, eligibility/snapshot states | `OutboxDispatchStoreTests.Committed_failures_schedule_the_five_database_time_backoffs_without_sleeping`, terminal/exhausted cases, queue snapshot cases; `OutboxProcessorTests.Publication_failure_persists_a_closed_descriptor_and_allows_following_work`. | I | +| C07 | Blocked dispatcher health, live `/healthz` | `OutboxProcessorTests.A_failed_terminal_audit_reports_unhealthy_while_the_actual_healthz_remains_live`; timeout/retained callbacks and `OutboxObservationTests`; `OutboxDispatchConventionTests` (`OutboxDispatchObservationTests.cs`) pins actual health registration and bounded in-memory callbacks. | B, I | +| C08 | Eligible due-row age excludes deferred and terminal rows | `OutboxDispatchStoreTests.Queue_snapshot_counts_every_pending_state_but_ages_only_publish_eligible_work`, `Empty_and_future_occurrence_snapshots_never_report_negative_eligible_age`; `OutboxObservationTests`. | B, I | +| C09 | Credential boot refusal/lazy no-I/O/connectivity/secret-free failures | `OutboxDispatcherDataSourceGuardTests`, `OutboxDispatcherRoleGuardTests`; `OutboxProcessorTests.Actual_host_startup_rejects_invalid_credentials_without_provider_or_secret_text`, actual API guarded startup; `OutboxProductionCompositionTests`; credential census dirty controls. | B, I | +| C10 | Frozen aliases/readiness holds and closed invalid reasons | `OutboxEventRegistryTests`, `OutboxEnvelopeReaderTests`; `OutboxDispatchStoreTests.Real_TenantCreated_contracts_and_aliases_are_held_before_any_payload_validation`, intentional absence and corruption cases; hosted Pending and intentional-absence cases. | B, I | +| C11 | Deterministic eligible order and deliberate same-key overtaking | `OutboxDispatchStoreTests.Selection_orders_by_availability_then_occurrence_then_ID_regardless_of_insert_order`, `Delayed_failure_allows_later_work_on_the_same_partition_to_overtake`. | I | +| C12 | Retained overruns/partition health/four-task cap/no late ack | `OutboxProcessorTests.Timeout_persists_failure_and_holds_the_partition_until_actual_callback_scope_cleanup`, four-callback saturation/release, shared finite shutdown and timeout/shutdown scope ownership. | I | +| C13 | Shared-inbox duplicate/sibling effect and no construction bypass | `InboxGuardTests.Concurrent_claim_waits_on_uniqueness_and_observes_first_transaction_outcome`; `DeliveryExecutionTests.A_durable_inbox_duplicate_completes_the_claim_without_constructing_or_classifying_the_handler`; `CustomizationDefaultDeliveryTests.Reaccepting_the_exact_provisioning_fact_does_not_repeat_inbox_effect_or_audit`; `OutboxDispatchConventionTests` (`IntegrationDeliveryBoundaryTests.cs`) dirty guard/invocation controls. | B, I | +| C14 | Fault rollback, independent poison budget, atomic subscriber terminal audit | `DeliveryExecutionTests.Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_scope_remains_usable`; `DeliveryProcessorTests.Siblings_have_independent_retries_and_Active_delivery_runs_beside_exact_Pending_and_privileged_holds`; `DeliveryDispatchStoreTests.Audit_refusal_rolls_back_transition_then_reacquires_terminal_only_with_actual_metadata` and six-attempt cases. | I | +| C15 | Targeted replay keeps completed inbox and fences late work | `DeliveryDispatchStoreTests.Replay_resets_only_exact_active_terminal_tuple_and_keeps_completed_sibling_inbox_and_stale_fences`, tuple-component and refusal controls; `DeliveryExecutionTests` final ownership-loss/closed-gate cases. | I | +| C16 | Context before constructors; SystemActor versus causal human; org preserved | `DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context`; `OutboxDispatchConventionTests` (`IntegrationDeliveryLifecycleBoundaryTests.cs`) context-writer census; `DeliveryAuditMetadataTests.Both_writers_preserve_delivery_identifiers_without_impersonating_the_causal_actor`; envelope/non-marker contract tests. | B, I | +| C17 | Constructor/cancellation policy, timeout poison, final unknown COMMIT | `DeliveryExecutionTests` fault variants/closing gate/lost COMMIT; `DeliveryProcessorTests.Synchronous_handler_construction_cannot_monopolize_worker_wait_or_other_partitions`, `Lost_sixth_COMMIT_acknowledgement_is_reconciled_from_durable_completion_without_seventh_execution`. | I | +| C18 | Nonzero complete module sweeps and real defaults/lifecycle/Seeder handoff | `OutboxDispatchConventionTests` (`IntegrationDeliveryBoundaryTests.cs`) handler/manifest censuses and missing-subject controls; `DomainEventHandlerTests` all-module roots/helpers; `CustomizationDefaultDeliveryTests`; `CustomizationDefaultInitializationTests`. | B, I | +| C19 | Inbox/ledger RLS/grants/full migration/ordinary privilege/external effect boundary | `EventDeliveryMigrationTests` complete schema, exact grants, app role org/tenant and policy mutants; `DeliveryDispatchStoreTests.Real_scheduler_role_cannot_read_payload_causality_or_inbox`; `OutboxDispatchConventionTests` (`DeliveryOwnerBoundaryTests.cs`) / `OutboxDispatchConventionTests` (`IntegrationDeliveryLifecycleBoundaryTests.cs`) confined capabilities. | B, I | +| C20 | Bounded persisted diagnostics and sensitive-text refusal | `DeliveryDispatchStoreTests.Normal_unknown_commit_and_expired_recovery_have_distinct_stored_diagnostics`; `DeliveryProcessorTests.Worker_bounds_handler_faults_and_a_different_partition_keeps_progressing`; `DeliveryAuditDiagnosticsTests`; registry/failure-descriptor boundary controls. | B, I | +| C21 | One direct-write success; rollback one standalone failed | `DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context` asserts one business/inbox/outbox/success audit; `Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_scope_remains_usable` asserts no committed success and `FailedAuditOriginAsync` requires exactly one standalone failed row; `ProducerExecutionTests.A_direct_owner_constructs_its_handler_after_admission_and_writes_one_correct_MUST_row`. | I | +| C22 | Planted mutating unclassified consumer fails closed | `DeliveryExecutionTests.Invalid_metadata_or_unclassified_handler_refuses_before_business_construction`; `DeliveryProcessorTests.Unclassified_handler_is_refused_before_construction_with_a_distinct_closed_descriptor`; `AuditCoverageTests.Integration_Audit_Census_Catches_An_Unregistered_Handler_For_A_Shared_Event`. | B, I | +| C23 | Absorbed event-free versus produced-work refusal, indeterminate, once-only clear | `ProducerExecutionTests` event-free/produced-work refusal and direct/Off owner cases discriminate shared-owner semantics. `DeliveryExecutionTests.Lost_COMMIT_acknowledgement_retains_atomic_completion_and_never_repeats_business` owns the actual physical-COMMIT theory, including its Step 4 row-bound indeterminate-row count and actual capture-clear delta extension. `Integration_Event_Handler_Restores_Tenant_Context` and `Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_scope_remains_usable` own success/fault boundary assertions. The Step 4 record owns execution and hosted qualification of the direct count/clear proof. `AuditLogBehaviorTests.An_indeterminate_commit_prefers_a_duplicate_to_a_loss` and `DeliveryCommitGateTests.An_unacknowledged_commit_fault_is_indeterminate_and_cleanup_cannot_replace_it` remain separate component controls. | B, I | +| C24 | Saved domain translation precedes audit and shares commit; attribution | `DomainEventProductionTests` FIFO/detach/delete/failed-canceled/atomic source-outbox-audit cases; `DeliveryExecutionTests.Actual_delivery_owner_drains_saved_domain_facts_and_rolls_back_translation_failure`; actual dispatch/default consumption C12/C18. | B, I | +| C25 | Translation/257th rollback, complete forbidden-helper sweep, no replay | `DomainEventProductionTests.Event_257_rolls_back_the_whole_unit_even_when_its_overflow_is_absorbed`, cancellation/fault cleanup, success same-scope reuse and source atomicity; `DomainEventHandlerTests` forbidden dependencies/raises/notification/helpers/interfaces/every-assembly controls. | B, I | +| C26 | Ignored cancellation and uncertain physical COMMIT retain truthful ownership | `DeliveryExecutionTests.Closing_the_gate_while_a_callback_ignores_cancellation_prevents_a_late_commit`, ownership-loss and lost-COMMIT cases; `DeliveryProcessorTests` four-retained, callback fault/shared shutdown and sixth unknown-COMMIT cases; `DeliveryCommitGateTests`. | B, I | +| C27 | Captured root has no declared intent in its frame: accepted type-filter outcome | `AuditStoreTests.A_capture_of_another_entity_type_does_not_reach_the_row` plants only SomethingElse under a ProbeTenant intent in the default RequestFrame and asserts persisted before/after NULL. `AuditStateCaptureTests.A_capture_belongs_to_the_frame_whose_handler_flushed_it` and `AuditLogBehaviorTests.A_nested_request_s_row_describes_its_own_writes_and_not_its_parent_s` independently constrain frame ownership. ADR-0044 Amendment 5 § 2 selects matching declared EntityType; ADR-0057 changes no classification semantics. The canonical criterion names this accepted type-filter/frame contract. This is not an arbitrary extra-root rejection policy. | B, I, M | +| C28 | Causal user/event audit metadata and outgoing causation | `DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context` asserts SystemActor, consumed EventId, causal user and outgoing causation; `DeliveryAuditMetadataTests`; `DeliveryCommitGateTests.Delivery_causation_is_inherited_by_nested_production_and_domain_identity_takes_precedence`. | B, I | +| C29 | Off-path slugs must have owning-module matrix rows | `AuditCoverageTests.Every_TenantOwned_Command_HasAuditCoverage` checks catalogue-to-matrix missing rows; `Every_Matrix_Row_Whose_Command_Exists_Is_Registered` checks the reverse direction; `The_Matrix_Sweep_Reads_Every_Slug_And_Can_Actually_Fail`, `An_off_path_marker_has_to_match_how_the_operation_is_registered`, owning-module-only and duplicate controls. | B | +| C30 | Enqueue-time missing/default tenant, trace and org refusal | `BackgroundJobSubmissionTests` admission/source/scope/stamp cases; `BackgroundJobPayloadTests.Empty_and_uninitialized_identifiers_are_refused_before_writing`; `BackgroundJobRegistryTests` and `BackgroundJobExecutionAdmissionTests`. | B, I | +| C31 | Durable-row tenant/org job context, RLS and one-worker cleanup | `BackgroundJobBusinessTests.BackgroundJob_Execution_Restores_Tenant_And_Trace` in `.Context.cs` checks real app-role context/restoration with org/cancel variants; `Business_aggregate_child_job_outbox_and_MUST_audit_share_the_final_completion`; storage isolation controls. | I | +| C32 | First storage boot/grants/role creator bounds and whole-schema offender | `BackgroundJobStorageMigrationTests.Fresh_down_reapply_restores_every_job_object_and_retains_existing_event_storage`, canonical DDL and `.Isolation.cs` planted grant/force-RLS controls; `HangfireStorageTests.Bootstrap_constructs_real_stock_storage_only_after_exact_schema_guards_and_acl_verification`; `DatabaseRoleTests` role/NOCREATEDB/public creator controls; architecture `PersistenceConventionTests` exact table-class census. | B, I | +| C33 | Dashboard 404 for all deployment modes | `BackgroundJobProductionManifestTests.BackgroundJob_Runtime_Has_No_Production_Definitions_Or_Dashboard` and its planted route/registry controls; the actual Program root and HTTP refusal are checked for all five DeploymentMode values in the Development test host, without claiming production deployment support. | B | +| C34 | No module job-runtime references | `OutboxDispatchConventionTests` (`BackgroundJobManifestBoundaryTests.cs`) / `OutboxDispatchConventionTests.BackgroundJob_Definitions_Stay_In_Their_Owning_Module`; module/dependency dirty controls; production assembly census is nonempty. | B | +| C35 | Real committed-realm signed tenant equals SeedData | `TenantRealmIssuanceTests.Fresh_import_issues_the_API_profile_for_all_four_declared_identities`; `TenantRealmApiTests.Every_seed_persona_reads_its_actual_account_site_under_the_matching_host_scope`; real fixture committed realm input. | I | +| C36 | Each host login/registered callbacks; route-level exchange/refresh/logout | `TenantRealmIssuanceTests.Authorization_refuses_an_unregistered_callback`; `bff-session-routes.test.ts` bound callback/logout and refresh cases; `TenantBffSessionTests.Reconciled_warm_realm_serves_both_native_hosts_with_real_refresh_logout_and_persisted_events`. No full browser OIDC claim. | F, I | +| C37 | Actual JWKS activation/refetch and withdrawn-key refusal | `TenantAuthenticationProfileTests.Real_configuration_manager_refreshes_new_key_and_never_reaccepts_withdrawn_unexpired_key` in `.Transport.cs` uses explicit test refresh timings and held JWKS response. | B | +| C38 | Hub issuer and wrong issuer under trusted key return 401 | `TenantAuthenticationProfileTests` profile/transport issuer controls; `TenantRealmApiTests.A_genuine_Hub_issuer_token_is_rejected_without_changing_the_operator_or_Hub_client`; actual account endpoint. | B, I | +| C39 | English 200 and mismatch 404; one attributed existing-slug audit | `AccountSiteHttpTests.Actual_account_HTTP_reads_English_and_Yoga_row_9_under_ReadOnly_without_query_audits`; `.Audit.cs` row-8 host/JWT attribution; `TenantRealmApiTests.Real_cross_tenant_tokens_refuse_before_configuration_and_audit_the_defended_host`; `AuditCoverageTests` no second registered slug. | B, I | +| C40 | Yoga organization outcome is named matrix row | `AccountSiteHttpTests` actual English/Yoga row 9; `TenantAuthenticationReconciliationTests.Matching_tenant_and_organization_tokens_reach_rows_6_and_9`, membership-denial matrix controls; `TenantRealmApiTests` real org disagreement. | B, I | +| C41 | Claimless signed token follows explicit HostOnly ceiling | `TenantAuthenticationReconciliationTests.Claimless_profiles_keep_the_HostOnly_or_unresolved_ceiling_with_one_fixed_Debug_event_per_request`; `AccountSiteHttpTests.Claimless_signed_profiles_keep_the_public_ceiling_and_emit_one_fixed_Debug_event_per_admitted_request`; real provider claimless actor case. | B, I | +| C42 | Nonempty routed non-public admission; anonymous masked bytes versus auth code | `TenantAuthenticationHttpTests.Backend_RequiresJwt_OnAllAuthenticatedRoutes`; `AuthenticatedHttpSurfaceRuntimeTests` actual closed route union; `TenantAuthenticationReconciliationTests.Absent_credentials_on_every_known_host_class_match_the_unknown_host_masked_404`; `AccountSiteHttpTests.Audit.cs` canonical codes. | B, I | +| C43 | Protected profile metadata and self-service/registration counterfactual | `TenantRealmExportTests` admin-only profile predicate; `TenantRealmProfileProtectionTests.Same_seed_account_can_edit_ordinary_profile_but_cannot_see_write_or_delete_authority`, ordinary registration/injection and user-editable counterfactual; reconciliation projection refusal. | B, I | +| C44 | Authenticated and id-addressed isolation with visible positives | `AccountSiteQueryTests.Actual_account_query_refuses_foreign_tenant_or_sibling_organization_provenance_before_reading`, contrasting positive query/HTTP controls; `TenantRealmApiTests` matching and cross-tenant/org controls; `PublicEducationHttpTests` / `TenantIsolationHttpTests` inherited id-addressed app-role positives/hidden resources. | I | +| C45 | Provision fact pending/rollback; two create-only defaults/convergence | `TenantCreatedProducerTests.Provisioning_business_outbox_and_both_MUST_rows_share_one_commit`; `CustomizationDefaultDeliveryTests` real stored/fresh, audit rollback, redelivery and Seeder race; `CustomizationDefaultInitializationTests` lifecycle/semantic identity. | I | +| C46 | Whole-chain independent subject quota, preserved floors, canonical 429 before audit | `AuthenticatedRateLimitTests.Authenticated_Rate_Limits_Use_Validated_Subject`, `Production_visitor_quota_blocks_validated_subjects_with_replenishment_disabled`; `.Admission.cs` durable-writes/audit-order controls; `TenantAuthenticationReconciliationTests.Subject_exhaustion_stops_recording_survives_token_and_tenant_rotation_and_leaves_B_independent`; peer-floor controls. | B, I | +| C47 | Legacy warm second-seed preservation and third-seed zero writes | `TenantRealmReconciliationTests.Legacy_upgrade_resumes_durable_partial_writes_and_preserves_accounts_and_unrelated_state`, uninterrupted legacy and fresh repeated-zero-write cases; Node reconciler repeat/warm lifecycle controls. | I, M | +| C48 | Exact configured lifetime/override bounds/observed issuance window/late clamp | `TenantRealmExportTests`, `TenantRealmIssuanceTests.Live_import_has_exact_lifespan_callbacks_and_confidential_PKCE_configuration`, `Actual_signed_tokens_detect_live_mapper_scope_audience_scalar_and_lifespan_mutants`, `Late_session_refresh_is_clamped_while_the_configured_access_lifespan_remains_exactly_900`. | B, I | +| C49 | State/verifier refusal; secure opaque cookie actually stored/sent on both hosts | `bff-session-routes.test.ts` bound callback/state/cookie projection; `provider.test.ts` verifier wire tests; `TenantBffSessionTests.Native_https_browser_stores_host_cookies_and_revalidates_logout_history_with_a_live_counter_control` / `scripts/verify-bff-browser.mjs` observe stored-and-sent cookies. | F, I | +| C50 | Single-flight revision, cookie bounds, failed-refresh anonymous 200, logout/history | `session-store.test.ts` shared-refresh/settlement/revocation; `bff-session-routes.test.ts` failed-refresh anonymous, unrelated transaction and logout return controls; `bff-auth-admission.test.ts` malformed/duplicate/oversized families; separate provider and browser `TenantBffSessionTests`. | F, I | +| C51 | Cross-host Origin and missing session-CSRF POST refusal | `bff-auth-admission.test.ts`, `bff-session-routes.test.ts`; real native browser form/Origin refusal in `TenantBffSessionTests.Native_https_browser_stores_host_cookies_and_revalidates_logout_history_with_a_live_counter_control`; `logout-response.test.ts` raw body suppression. | F, I | +| C52 | Exact studio/portal guards and disabled 503 with no provider work | `src/server/auth/middleware.test.ts`, `src/middleware.test.ts`, `bff-session-routes.test.ts`; `TenantBffSessionTests.Enabled_native_startup_and_shutdown_make_no_provider_or_API_connection`; `src/components/auth/shell.test.tsx`. | F, I | +| C53 | Independent admission caps and actual-settlement ownership | `session-store.test.ts` source17/pending129/subject9/global1024 controls, canceled signin/refresh, closing logout and stop settlement; `session-http-lifetime.test.ts`; `TenantBffSessionTests` EOF/acquisition cleanup and nonzero shutdown counters. | F, I | +| C54 | Ordinary AccountSite 401 no idle touch/recovery; positive publication witness | `account-site-policy.test.ts` owner/caller/HTTP matrix and post-refresh 401 revocation; `session-store.test.ts` positive validation/independent lifetime controls; catalogue `Bff_Session_Refresh_And_Revocation_Have_One_Owner`. | F | +| C55 | Separate actual warm chain and controlled-grant real cookie/history qualification | `TenantBffSessionTests.Reconciled_warm_realm_serves_both_native_hosts_with_real_refresh_logout_and_persisted_events` + `verify-bff-session.mjs`; separately `Native_https_browser_stores_host_cookies_and_revalidates_logout_history_with_a_live_counter_control` + `verify-bff-browser.mjs`. Phase 06 retains full browser-driven OIDC. | I | +| C56 | Both public sites render with Keycloak stopped | `.github/workflows/ci.yml` `public-demo` / `public demo + lighthouse`; `scripts/verify-public-demo.mjs`, demo lifecycle and `public-demo-ci.test.ts`; explicit provider-stopped browser/product receipt and 9 URLs × 3 Lighthouse runs. F lifecycle controls do not replace J execution. | F, J, M | +| C57 | Exact LS0002 Warning, clean negatives, no AD0001, two-word drift | `SensitiveExceptionMessageAnalyzerTests.Reports_One_Fixed_Warning_At_The_Thrown_Creation`, clean excluded forms, complete union and two-word-only source mutation; `SensitiveTokenCatalogTests`; `AnalyzerBuildTests` evaluated new-project/warning/other-warning controls; architecture `AnalyzerWiringTests`; ADR/release/catalogue carriers. | B, M | +| C58 | Authenticated endpoint generated OpenAPI/SDK | `OpenApiContractTests.PublicSurface_Contract_Matches_Served_OpenApi` joins served schema and `backend/openapi/v1.json`; SDK `authenticated-contract.test.ts`, `authenticated-server.test.ts`, `contract-ownership-compiler.test.ts`; CI generated SDK check and `openapi diff` policy/offender controls. | B, F, O | +| C59 | Exact event/job metric names, closed dimensions, immutable states | `OutboxObservationTests`, `DeliveryObservationTests`, `BackgroundJobObservationTests`; `OutboxDispatchStoreTests` queue snapshot due/deferred/terminal cases; `DeliveryProcessorTests.Successful_executions_do_not_force_scans_and_refresh_failure_keeps_the_previous_snapshot`; `OutboxDispatchConventionTests` (`BackgroundJobMetricBoundaryTests.cs`); Standards 10 inventory. | B, I | +| C60 | Zero 02b pending catalogue rows; actual lane/zero skips/offender companions | Computed catalogue Phase/status census; `CorpusConsistencyTests` named owner/status/count/skip controls; actual complete B/I/F/J/O/M final-source receipts, `ci-test-shards.py`, aggregate/current-attempt `ci-test-shard-results.py`, native launcher/provisioning offline controls. Include LS0002 and `AsyncStoreInventoryTests` addition; do not infer protection from workflow YAML. | B, I, F, J, O, M | + +## Phase-exit obligations + +| ID | Canonical obligation locator | Required evidence | Lane | +|---|---|---|---| +| E01 | ADR-0046/0047 and every dated amendment Accepted/carried | D01–D04/D26 decision-register/dated-amendment ordering census and semantic carrier reconciliation. | M | +| E02 | Warm realm seed user BFF login and real TenantId | C35/C36/C47/C55 actual warm-provider case, matching stored provider events and `SeedData` UUID; retain separate controlled-grant browser proof. | I | +| E03 | Named API English success/Yoga outcome/Hub401 | C38–C40 `AccountSiteHttpTests`, `TenantRealmApiTests` on `/api/v1/account/site`; generated contract C58. | B, I, O | +| E04 | Host/JWT 404 and one admitted attributed existing-key row | C39 actual route row-8 proof and real provider cross-tenant case; source/actor/correlation/matrix assertions. | I, B | +| E05 | Actual sample end-to-end, one producer lease, per-subscription forced-redelivery effect | C03/C13/C18/C45: real `CustomizationDefaultDeliveryTests` original reacceptance and both default effects plus independent store/processor contention. At-least-once publication, no exactly-once transport claim. | B, I | +| E06 | Independent consumer terminal state/counter/audit | C14 `DeliveryDispatchStoreTests` terminal/audit atomicity, `DeliveryProcessorTests` poisoned sibling progress, `DeliveryObservationTests` exact counter. | B, I | +| E07 | Direct-write success versus one standalone failed delivery audit | C21/C23 actual direct-write/fault delivery cases; `FailedAuditOriginAsync` requires exactly one failed row. The Step 4 record owns execution and hosted qualification of the actual lost-COMMIT row-count/capture-clear extension. | B, I | +| E08 | Job owner/context/definition/identifier admission; durable authority and opaque hints | C30/C31; `BackgroundJobSubmissionTests`, `BackgroundJobPayloadTests`, `BackgroundJobRegistryTests`, `BackgroundJobBusinessTests.Context.cs`; `HangfireStorageTests.Hangfire_Invocations_And_Diagnostics_Are_Closed`, bridge/manifest/capability controls. | B, I | +| E09 | Two stopped-provider public sites | C56 J provider-stopped actual browser/product/Lighthouse receipt and lifecycle controls. | J, F, M | +| E10 | LS0002 Warning plus decision/catalogue/release | D25/C57 exact compiler, token mutation, build/wiring and records. | B, M | +| E11 | Zero pending 02b rows, green real contexts/no skips, dated required behavior check | C60 final-source executed case/artifact/aggregate receipts plus live main branch-protection read-back recording exact `backend integration (Testcontainers)` required context and date, alongside all seven required names; workflows alone prove no remote setting. | B, I, F, J, O, M | + +## Explicit exclusions and named owners + +The first two boundaries below occur under “What this phase is not”; X01–X11 +preserve the source order of “Explicitly not in this phase”. Owner-document locators +were inspected; they allocate work without accepting future decision gates. + +| ID | Exclusion | Owner / verified carrier | +|---|---|---| +| T01 | Dapr event adapter | Phase 11 demand-gated building blocks; `IEventBus` / default `InProcessEventBus`; trigger second process consumes integration event (ADR-0035). | +| T02 | Kafka event adapter | Phase 11 demand-gated building blocks; `IEventBus` / default `InProcessEventBus`; trigger cross-process volume/replay/ordering (ADR-0035). | +| X01 | Operator recovery API, producer reset, permissions/reason/fencing/runbook | Phase 03 integration-event/job recovery sections; internal targeted subscriber replay is already delivered. | +| X02 | Hangfire dashboard | Phase 03 dashboard permission and ADR-0015 amendment; Phase 11 Security owns APISIX gating. No current route. | +| X03 | Production job definitions; tenantless audit jobs | Phase 04 media transcoding, Phase 08a notification/attempt-expiry definitions; Phase 11 audit partition/retention jobs. Runtime/fixtures do not count as production definitions. | +| X04 | Keycloak identity-event feed and authenticated ingress | Phase 03 Identity event/Keycloak ownership and audit feed; Audit spec remains no current consumers/inbox. | +| X05 | `/readyz` mapping/unhealthy deployment backstop | Phase 11 Reliability/health surfaces; current outbox/delivery checks stay registered and private. | +| X06 | Outbox/inbox/delivery/job-history purge and interval/principal choice | Phase 11 Data Operations; exact per-store grants/immutability and no-principal constraints retained. ADR-0046 replay floor is not a purge implementation. | +| X07 | Cross-instance cache invalidation | Phase 11 demand-gated building blocks; `ICacheService` / `InMemoryCacheService`; trigger more than one application instance. No current topic/subscription. | +| X08 | Tenant-status policy for already queued/in-flight async work | [Phase 02c § Internal-API handlers LearnStack hosts](phase-02c-hub-foundation.md#internal-api-handlers-learnstack-hosts) owns the decision before its first status-transition/termination writer: select hold/drop/dead-letter policy there. Existing lease fences, actual quiescence and reservation ownership remain authoritative; a status change alone releases no capacity. | +| X09 | XML target-existence/changed prose 88-column CI promotion | Phase 03 cross-cutting follow-up; trigger second active write contributor. The Step 4 closeout records the live contributor census; fragment lint does not establish either check. | +| X10 | Full browser-driven authenticated Playwright Test/axe OIDC journeys | Phase 06 Testing/end-to-end and inherited baseline table; current stub routes, real token/native warm chain and controlled-grant cookie/history are narrower proofs. | +| X11 | Production realm provisioning | Phase 11 Security/Keycloak hardening for both realms; dev realm/reconciler is current scope. | + +The G18 inventory is coverage/governance evidence only: `AsyncStoreInventoryTests` +and the canonical Data Protection inventory do not implement field erasure, DSAR +or legal-compliance certification. Phase 03 owns the identity/DSAR integration; +Phase 11 owns later-module/retained-copy and purge/retention reconciliation. diff --git a/docs/roadmap/phase-02c-hub-foundation.md b/docs/roadmap/phase-02c-hub-foundation.md index 8ddf57315..686a76575 100644 --- a/docs/roadmap/phase-02c-hub-foundation.md +++ b/docs/roadmap/phase-02c-hub-foundation.md @@ -257,6 +257,18 @@ tenant the links, mail and bookmarks still pointing at the first one; the termin handler this phase builds decides whether a slug is ever released, and on what condition, before an index filter is allowed to decide it by accident. +**Status changes decide the fate of asynchronous work.** Before this phase's +first status-transition or termination writer, its decision pass selects the +hold, drop or dead-letter policy for already queued or in-flight outbox, +delivery and job work. This is the owner named by +[Phase 02b's asynchronous-status exclusion](phase-02b-events-auth.md#explicitly-not-in-this-phase); +Phase 02b selects no policy; Phase 02c decides before that first writer. +The decision preserves the existing lease fences, +actual-quiescence requirements and reservation ownership under +[ADR-0046](../decisions/0046-durable-event-delivery-and-recovery.md) and +[ADR-0047](../decisions/0047-transactional-background-job-runtime.md). A tenant +status change alone proves neither settled work nor a released reservation. + Each handler: - Runs on the **internal listener only** and is unreachable from the public surface @@ -323,15 +335,16 @@ keeps the 24-hour cadence and 0–119-minute jitter; signed-key hardening and revocation-list operations remain Phase 11. This is a periodic job, distinct from the entitlement-push integration-event consumer above. -The accepted expanded P02b-4 contract supplies durable recurrence and the -restricted tenantless trigger → enumeration → separately announced submission -foundation. This phase registers the real phone-home recurrence/child definitions -and chooses the nonarchived policy that includes Suspended tenants. Verify stable -occurrence/jitter, bounded resumable fan-out and duplicate-tick controls with the -real Hub adapter here. No tenant sentinel or general business bypass substitutes -for that authority. [ADR-0047 is Accepted — 2026-10-15](../decisions/0047-transactional-background-job-runtime.md#workload-envelope-and-first-consumer-obligations); -P02b-4 implementation/proofs remain pending. This handoff claims no delivered -foundation or implemented grant. +[Phase 02b](phase-02b-events-auth.md) supplies the delivered durable-recurrence +and restricted tenantless trigger → enumeration → separately announced +submission foundation under +[ADR-0047](../decisions/0047-transactional-background-job-runtime.md#workload-envelope-and-first-consumer-obligations). +This phase registers the real phone-home recurrence/child definitions and chooses +the nonarchived policy that includes Suspended tenants. Its real Hub adapter +proofs verify stable occurrence/jitter, bounded resumable fan-out and duplicate +ticks. Delivered runtime and fixture controls do not implement these Hub-specific +definitions or prove the adapter. No tenant sentinel or general business bypass +substitutes for the declared authority. ### `platform_host_to_tenant` mirroring @@ -440,6 +453,9 @@ repository, against the Hub schema. Its LearnStack-side counterpart is this list ## Completion Criteria +- The status/termination decision and its queued/in-flight work controls ship + before the first affected writer. A status transition alone neither releases + an unresolved reservation nor establishes external quiescence. - A tenant created through `POST /api/internal/tenants` exists in LearnStack with its default organization, resolves at `{slug}.{platform-domain}` through `platform_host_to_tenant`, and its entitlement projection is populated. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 69c9cfc00..6418ca781 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -108,11 +108,11 @@ data, and three concrete defects follow from it: `tenant_id`, no query filter and no Row Level Security policy. A learner enrolled in a language school and a yoga studio would carry both tenants' fields in one blob that both tenants read. -- **A tenant-scoped data request is not separated from global account deletion.** - [Data Protection](../architecture/23-data-protection.md) describes one erasure - workflow that ends in "invalidate Keycloak user". Initiated by a tenant admin, that - workflow destroys an identity that other tenants are actively using. One tenant must - not be able to close a person's account with another. +- **A tenant-scoped data request needs separate authority from global closure.** + [Data Protection](../architecture/23-data-protection.md#right-to-erasure-right-to-be-forgotten) + separates those workflows. This phase implements that boundary: invalidating + Keycloak from a tenant-admin request would destroy an identity other tenants + actively use. - **JSONB columns carry no PII metadata.** Data Protection requires every aggregate to declare a PII category and claims a CI check over columns named like `email` or `phone`. A `custom_fields` blob is one column whose keys are authored by tenants at @@ -188,10 +188,10 @@ by this note. mechanism that bounds the bundle, not a `WHERE tenant_id = …` clause a developer can forget in one of a dozen modules. - A tenant-scoped erasure removes the `Membership` and its `MembershipProfile`, - anonymises that tenant's behaviour rows, and anonymises the actor field on that - tenant's audit entries while keeping the action record - ([Data Protection § Right to Erasure](../architecture/23-data-protection.md)). The - `users` row survives for as long as any membership remains anywhere. + anonymises that tenant's behaviour rows, and redacts the permitted human-facing + audit fields while keeping the action record. Audit identifiers and causal + metadata remain subject to the first-writer decision below. The `users` row + survives for as long as any membership remains anywhere. - **Global account closure has no tenant-admin endpoint.** It is a platform-scoped operation. It fans out `UserAnonymisationRequestedV1` to every tenant the person belongs to and reconciles completion per Data Protection's 30-day workflow. @@ -199,6 +199,24 @@ by this note. [Phase 02a Packet 7](phase-02a-kernel-tenancy.md) is the only path that reads across tenants during either flow, and every use of it is MUST-class audited. +**Durable-copy prerequisite.** This phase still implements tenant-scoped DSAR +export/erasure, separate global closure, subject/actor mapping, request authority +and audit redaction. It consumes the canonical +[durable asynchronous store inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory) +and its [first-writer prerequisites](../architecture/23-data-protection.md#erasure-authority-and-first-writer-prerequisites). +Before the first affected writer, settle a bounded decision for surviving +identifier/payload/audit references, exact principal and minimum grants, +immutable facts, dependency/deletion order, replay/deduplication floors and +durable completion. Ordinary app-role/SystemActor delivery or dispatcher +credentials authorize no privileged erasure. The existing inbox, delivery and +job grants provide no generic Platform purge; operator authority and erasure +do not prove external quiescence or reservation release. + +[Phase 11](phase-11-production-hardening.md#data-operations) extends these +workflows across later modules and retained copies, with purge/retention, +backup/provider/diagnostic and operational reconciliation. That later work does +not defer this phase's DSAR or redaction implementation. + **PII classification on JSONB.** Every `TenantCustomFieldDef` row carries a required `pii_category` drawn from the closed set in [Data Protection § Personal Data Inventory](../architecture/23-data-protection.md) — @@ -366,6 +384,25 @@ Authorization is the third layer, not the first. A permission check that passes runs under the tenant's `ITenantContext` and under Row Level Security; a deny is a better error message, not the isolation boundary. +### Operator recovery and dashboard admission + +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. +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. + ### Gateway Configuration Corrections The APISIX gateway **adapter** is demand-gated to @@ -490,18 +527,32 @@ result as a second, bounded caller or to give it a method of its own, and settle inbox boundary with it: the inbox mark lives on another connection, so a redelivery must find the result row already written rather than record a second one. +The same decision must account for immutable `actor_user_id`, entity/causation +identifiers and new `metadata.causal_actor_user_id` references. Current redaction +permits only `actor_email`, `ip_address`, `user_agent`, `before_state`, +`after_state` and `changes`; `metadata` is outside the column grant. Preserve +those boundaries until the bounded decision and any required migration ship. +Redacting the six columns alone does not establish complete anonymisation. + ### Cross-cutting follow-up at phase exit - **Escalate both analyzers from Warning to Error** — `LS0001` - (`LearnStackException-DomainExceptionThrow`) and `LS0002` (the - secrets-in-exception-message rule introduced in + (`LearnStackException-DomainExceptionThrow`) and `LS0002` + (`LearnStackException-SensitiveExceptionMessage`, introduced in [Phase 02b](phase-02b-events-auth.md)) — and remove both from `WarningsNotAsErrors` in `backend/Directory.Build.props` — the documented escalation point per - [ADR-0032 § Sub-decision 4 + Amendment 1](../decisions/0032-exception-handling-logging-and-observability.md). - Until this gate the analyzer fires as a Warning so that a legitimate - aggregate-invariant throw does not break CI. By phase exit the identity domain is the - first substantial body of domain code, and the rule has been exercised against real - aggregates rather than against an empty solution. + [ADR-0032](../decisions/0032-exception-handling-logging-and-observability.md). + Reconcile each rule's scoped call sites and obtain a clean solution build + before this exit gate. `LS0001` retains its Domain/Application scope; + `LS0002` covers all production C# projects under `backend/src`. Both remain + Warnings until this gate; neither belongs in `NoWarn`. +- **Inherited documentation CI trigger.** When a second active contributor gains + write access, add XML-documentation target-existence and changed-prose + 88-column checks to CI under + [Documentation Standards](../standards/13-documentation.md) and the existing + [contributor trigger](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main). + Existing Markdown fragment lint does not establish either check. The trigger + remains unchanged; no protection-setting change is authorized by this handoff. ## Deliverables @@ -509,8 +560,9 @@ find the result row already written rather than record a second one. (tenant-owned, organization-scoped), `Role` and `Permission` with explicit scope, `Invitation` — on top of Keycloak. - Written attribute-ownership table, enforced by `User_Aggregate_Has_No_TenantScoped_Columns`. -- Tenant-scoped DSAR export and erasure, running under `ITenantContext` as - `learnstack_app`; global account closure as a separate platform-scoped operation. +- Tenant-scoped DSAR export and erasure, with business handlers running under + `ITenantContext` as `learnstack_app`; separate platform-scoped global closure + and audit redaction after the bounded first-writer decisions above. - `TenantCustomFieldDef` with a mandatory `pii_category`, the `Membership` target, the definition editor, and the schema-driven membership form. - Category-driven redaction of custom-field values in logs and error-tracking payloads. @@ -519,6 +571,9 @@ find the result row already written rather than record a second one. the first permission-sensitive route, with real denied-dispatch controls. - The Platform-scope permission gate replacing `DenyAllPlatformAdminGate`, with the killswitch toggle command, its permission key and its runbook. +- Operator recovery and Hangfire dashboard admission under the + [bounded first-writer decisions](#operator-recovery-and-dashboard-admission), + including denied-route, fencing, reason and audit controls. - Admin login, tenant switcher and organization switcher via OIDC PKCE. - Tenant- and organization-aware user management screens. - Invitation flow end to end, tenant and organization bound. @@ -547,6 +602,10 @@ find the result row already written rather than record a second one. the ability to log in. - No tenant-admin endpoint can delete or anonymise the global `User` row or the Keycloak user. +- DSAR and audit redaction account for the canonical durable-copy inventory and + satisfy their bounded first-writer decisions. Tests preserve immutable facts, + replay/deduplication floors, unresolved reservations and same-transaction MUST + evidence; six-column redaction alone is not proof of complete anonymisation. - Every `TenantCustomFieldDef` row carries a `pii_category`; a definition with category `Payment` is rejected; the export bundle contains exactly the fields the categories permit. @@ -556,6 +615,10 @@ find the result row already written rather than record a second one. rejection (Tenant vs Organization) returns the correct Problem Details code. - Unauthorized users cannot reach admin endpoints, and a denied command returns `Result.Fail(forbidden)` rather than throwing. +- Dashboard and recovery routes remain absent until their application permission + and dated decisions ship. Cross-scope/unauthorized recovery cannot reset producer + state, bypass subscriber deduplication, release uncertain job capacity or reuse + a completed privileged connection. - The [runtime authorization gate](#authorization) refuses an unclassified protected endpoint and a valid principal lacking its permission before handler execution; explicit public routes still work anonymously. Updating the static route census @@ -580,6 +643,10 @@ find the result row already written rather than record a second one. ## Risks +- **Redaction mistaken for anonymisation.** Retained actor/entity/causation IDs + and metadata survive six-column redaction. The bounded first-writer decision + and durable-copy controls are exit requirements, not a later operations waiver. + - **Re-implementing what Keycloak owns** — password hashing, reset emails, token rotation. If a capability appears in the Keycloak vs LearnStack split table in [Identity and Authentication](../architecture/13-identity-and-auth.md), it stays in @@ -621,6 +688,8 @@ find the result row already written rather than record a second one. integration test running as `learnstack_app`. - A tenant-scoped erasure in one tenant leaves that person's access to the other tenant intact, and no tenant-admin path can reach the global account. +- The bounded DSAR/redaction decision and applicable durable-copy controls above + are implemented; surviving immutable references are explicitly reconciled. - Every `TenantCustomFieldDef` carries a PII category, and export, redaction and retention are driven by the definitions rather than by the JSONB blob. - `AuthorizationBehavior` is a real implementation and every write endpoint carries an diff --git a/docs/roadmap/phase-07-enrollment-learner-portal.md b/docs/roadmap/phase-07-enrollment-learner-portal.md index 2d2c0531c..7ae9b374a 100644 --- a/docs/roadmap/phase-07-enrollment-learner-portal.md +++ b/docs/roadmap/phase-07-enrollment-learner-portal.md @@ -177,6 +177,10 @@ Built on the Studio shell, permission system, and typed SDK from ### Progress Tracking +Before the first learner-behaviour writer, integrate its records with Phase 03's +DSAR export/erasure workflow and preserve the +[durable-copy prerequisites](../architecture/23-data-protection.md#erasure-authority-and-first-writer-prerequisites). + - Lesson progress. - Module progress. - Course progress. diff --git a/docs/roadmap/phase-08a-assessment-notifications.md b/docs/roadmap/phase-08a-assessment-notifications.md index c49d07cd1..d80ee54e1 100644 --- a/docs/roadmap/phase-08a-assessment-notifications.md +++ b/docs/roadmap/phase-08a-assessment-notifications.md @@ -13,14 +13,15 @@ domain capability on top of it, not new plumbing. ### What this phase does not own -Three mechanisms are routinely mis-attributed to this phase. Stated once, here, so no +These mechanisms are routinely mis-attributed to this phase. Stated once, here, so no reader and no later phase has to guess: | Mechanism | Owning phase | What Phase 08a adds | |---|---|---| -| Outbox — `outbox_messages` table, `OutboxFlushBehavior` | [Phase 02a](phase-02a-kernel-tenancy.md) | Nothing | +| Outbox table and ambient transaction foundation | [Phase 02a](phase-02a-kernel-tenancy.md) | Nothing | +| Immediate outbox enqueue, producer guard and transaction-owner completion under ADR-0057 | [Phase 02b](phase-02b-events-auth.md) | Event production through the existing contract | | Outbox dispatcher — polling, retry, backoff, dead-letter, inbox guard, `IEventBus` transport | [Phase 02b](phase-02b-events-auth.md) | Event types, topics, and idempotent consumers | -| Background jobs — typed scheduling, host/storage, restored authority, retry/audit, external/capacity/recurrence foundation under Accepted ADR-0047 (implementation pending) | [Phase 02b](phase-02b-events-auth.md) | Job/provider definitions and declared queue/profile assignments | +| Background jobs — typed scheduling, host/storage, restored authority, retry/audit, external/capacity/recurrence foundation under Accepted ADR-0047 | [Phase 02b](phase-02b-events-auth.md) | Job/provider definitions and declared queue/profile assignments | | Scoring / completion DSL engine — ADR-0025, sandbox, evaluator | [Phase 05](phase-05-education-learning-content.md) | Callers, answer maps, and result-band projection | Phase 08a writes **no** dispatcher, **no** job host, and **no** expression evaluator. If @@ -161,16 +162,16 @@ idempotency/reconciliation must separately prevent duplicate external delivery. ### Background Jobs -**P02b-4 acceptance update — 2026-10-15.** The maintainer accepts expanded H1: -stock Hangfire wakeups with LearnStack-owned submission, retries/audit, external +The inherited runtime uses stock Hangfire wakeups with LearnStack-owned +submission, retries/audit, external stages, capacity and recurrence/fan-out under [ADR-0047](../decisions/0047-transactional-background-job-runtime.md). -P02b-4 implementation remains pending. This phase supplies notification/expiry +This phase supplies notification/expiry definitions and chooses declared queues/profiles, not a second retry policy or activator. Provider sends require stable logical-operation idempotency and known effect reconciliation; inbox/event dedup alone cannot prove an email was sent once. The accepted typed job obligations replace the old payload/base-class spellings; -P02b-4 still owes their runtime enforcement. +the inherited runtime enforces them. Additions to the existing host, not a new one: @@ -183,14 +184,16 @@ Additions to the existing host, not a new one: Typed transactional submission, exact tenant/org restoration, profile/capacity admission and the replacement BackgroundJob_* obligations are accepted by [P02b-4](phase-02b-delivery-log.md#p02b-4-decision-package-2026-10-15). -Their implementation/proofs remain pending; this phase depends on that completed -foundation and adds no runner. +Their implementation/proofs are recorded in the +[P02b-4 merge closeout](phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19); +this phase consumes that foundation and adds no runner. ## Deliverables - `LearnStack.Modules.Assessment` and `LearnStack.Modules.Notifications` scaffolded — - each with `{Domain, Application, Application.Contracts, Infrastructure}`, its `IModule` - registration, its `docs/modules//audit.md`, and its permission-catalogue rows. + each with `{Domain, Application, Application.Contracts, Infrastructure}`, its + composition-root registration, its `docs/modules//audit.md`, and its + permission-catalogue rows. - Assessment MVP: assessments, question bank, attempts, grading, result visibility. - Placement-test path scored through the Phase 05 `TenantScoringRule` evaluator, with the result-band → level projection. diff --git a/docs/roadmap/phase-11-production-hardening.md b/docs/roadmap/phase-11-production-hardening.md index a0a493867..4c2029926 100644 --- a/docs/roadmap/phase-11-production-hardening.md +++ b/docs/roadmap/phase-11-production-hardening.md @@ -262,6 +262,13 @@ bounds request *cost* once a request is inside. Neither substitutes for the othe ### Security +- Qualify the APISIX `openid-connect` block against the tenant realm before + gateway activation. Phase 03 corrects the route table; it does not activate + the gateway. Adopt that corrected file rather than the older architecture + sketch. +- Gate `/admin/hangfire*` at APISIX in addition to Phase 03's application + Platform-scope permission and dated ADR-0015 disclosure. Prove both denied + layers; a realm role alone grants no application authority. - Secure headers (HSTS, CSP with nonces, COOP/CORP, Permissions-Policy). - CORS policy enforced at APISIX (`cors` plugin) + per-handler ASP.NET layer. - CSRF strategy for non-Action mutating routes. @@ -440,8 +447,8 @@ counters continue during suppression; their volume and retention need sizing too backoff and crash-loop alerts/runbooks. Preserve [ADR-0059's host/exit boundary](../decisions/0059-owned-hangfire-server-generations.md#host-shutdown-bounds-and-observation); [ADR-0060's fatal remedy](../decisions/0060-fatal-hangfire-startup-and-unsafe-unwind.md) - is Accepted — 2026-10-16; its runtime qualification remains P02b-4 work. - P02b-4 promises no automatic supervisor restart. + is implemented and qualified by P02b-4's isolated runtime proofs. Those proofs + promise no automatic supervisor restart or production deployment qualification. A restarted API supplies no positive external quiescence or reservation release. - **Production crash diagnostics.** Own runtime and OS crash-collector/dump policy: default enablement, secret exposure, access, storage, export and retention/deletion. @@ -598,20 +605,39 @@ same `ILiveClassProvider`. ### Data Operations +This phase extends [Phase 03](phase-03-identity-admin.md)'s tenant-scoped DSAR +export/erasure, separate global closure and audit redaction across later modules +and retained copies. Phase 03 retains those implementations, subject mapping and +request authority. The canonical +[durable asynchronous store inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory) +and its [first-writer prerequisites](../architecture/23-data-protection.md#erasure-authority-and-first-writer-prerequisites) +bound this work; this handoff chooses no retention period, purge principal or +new erasure permission. + - Backup strategy. - Restore drills — a drill counts only when a backup is restored to a fresh instance and the integration suite passes against it. +- Retained database/WAL/backup, provider-event and diagnostic-copy reconciliation, + including a post-restore control that does not reintroduce erased references. + Source-row deletion and local BFF invalidation do not prove removal from these + copies. Qualify the actual retention/deletion and operational evidence here. - Migration strategy, including the two-step plan every destructive change requires. - Seed data strategy. - Data retention policy. - Soft delete and purge jobs. -- Processed `outbox_messages` and aged `inbox_messages` purging. Both tables start - filling in [Phase 02b](phase-02b-events-auth.md), which records the constraint rather - than solving it: the `DELETE` grant belongs to `learnstack_platform`, whose only entry - takes a reason and no actor, so a recurring job has no principal to present — and an - inbox purge shorter than the redelivery window silently breaks deduplication. Phase - 02b states how long a pair stays replayable; this phase picks the principal and the - interval that honours it. +- 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 + 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 + order, purge interval and retention/replay floor. Reuse Phase 03's established + DSAR/redaction authority; any extension for later stores or purge requires its + own bounded decision before its writer. A recurring job cannot borrow the + dispatcher's credential or treat ordinary SystemActor delivery as authority. + Retention must preserve deduplication throughout the maximum redelivery window; + erasure cannot release unresolved reservations or prove external quiescence. - Recording retention and purge jobs. - `audit_log` retention and partition lifecycle — see **Demand-gated building blocks** above; the jobs and their cadence are specified by @@ -652,9 +678,11 @@ same `ILiveClassProvider`. ### Compliance Readiness - GDPR/KVKK data handling review. -- User data export. -- User deletion / anonymization strategy, honouring the global-`User`-versus-tenant-owned-profile - boundary established in [Phase 03](phase-03-identity-admin.md). +- Complete Phase 03's export and erasure workflows across later modules and + retained copies, preserving its global-`User`-versus-tenant-owned-profile + boundary and first-writer prerequisites. +- Purge/retention and provider/diagnostic/backup operations, with exercised + reconciliation evidence against the canonical inventory. - Consent tracking. - Terms / privacy content support. - Classroom recording consent and retention review. @@ -701,6 +729,9 @@ same `ILiveClassProvider`. evidence, explicit diagnostic/readiness decisions, and exercised IdP, key, subject-capacity and assertion-suppression runbooks. - Backup and restore process with a completed drill. +- Later-module and retained-copy DSAR reconciliation, bounded purge/retention + decisions and operational controls against the canonical asynchronous-store + inventory, preserving Phase 03's implementation and authority boundary. - Performance baseline against the budgets in [15-performance.md](../standards/15-performance.md). - Gateway/CDN response-cache policy and isolation/freshness proofs before activation, @@ -758,10 +789,13 @@ same `ILiveClassProvider`. 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. -- The outbox and inbox purge jobs run under a principal the platform-admin gate admits — - named, not borrowed from the dispatcher's credential — and the inbox retention floor - is at least the maximum redelivery window, asserted by a case that advances retention - and shows a still-replayable event performing its effect once rather than twice. +- 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 + authority. The inbox retention floor is at least the maximum redelivery window, + asserted by advancing retention and showing a still-replayable event performing + its effect once rather than twice. Immutable facts, uncertain effects and + reservations survive until their independently required evidence permits change. - No module references a Dapr, Kafka, Valkey or Vault client type. `Modules_Do_Not_Reference_DeploymentMode` is green. - Production deployment is repeatable and documented. @@ -773,6 +807,10 @@ same `ILiveClassProvider`. [Observability Standards § Health checks](../standards/10-observability.md#health-checks) sets. - Backup restore test passes on a fresh instance. +- Export/erasure reconciliation covers later modules and retained provider, + diagnostic, database/WAL/backup copies in the canonical inventory. Restoring a + backup does not reintroduce erased references; local BFF invalidation and source + cleanup are not used as evidence for independent copies. - Tenant + organization isolation regression tests exist, are not skippable, and run as `learnstack_app`. - **A single tenant cannot degrade another tenant's request latency beyond a stated diff --git a/docs/standards/02-backend-coding.md b/docs/standards/02-backend-coding.md index 6e8392087..644e7b973 100644 --- a/docs/standards/02-backend-coding.md +++ b/docs/standards/02-backend-coding.md @@ -8,6 +8,8 @@ Tenant API authentication additions derive from [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md). Producer additions derive from [ADR-0057](../decisions/0057-transactional-event-production-and-completion.md). +Exception diagnostic wiring derives from +[ADR-0032 Amendments 6–7](../decisions/0032-exception-handling-logging-and-observability.md#amendment-7--diagnostic-wiring-and-proof-clarifications-2026-10-25). C# / .NET conventions for LearnStack backend code. @@ -20,6 +22,10 @@ C# / .NET conventions for LearnStack backend code. - `ImplicitUsings` enabled in modern projects. - `LangVersion` = `latest`. - File-scoped namespaces everywhere. +- Production C# projects inherit analyzer wiring from + `backend/src/Directory.Build.props`; do not duplicate references or silence + `LS0002` project-wide. The [canonical catalogue](21-architecture-tests-catalogue.md#learnstackexception-sensitiveexceptionmessage-roslyn-analyzer) + owns its bounded expression scope, severity and proof obligations. ## Naming diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index 48b4240de..f38414801 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -49,10 +49,11 @@ PostgreSQL schema, EF Core, and migration conventions. - One `DbContext` per module (not one global). - Schema migrations live with the owning module. -With [P02d-1 complete](../roadmap/phase-02d-delivery-log.md#delivery-record-p02d-1), -five migration chains exist: Tenancy, Platform, Customization, Audit and -Education. P02b-3 Step 1 brings their inventory to twenty-three data tables and -five migration-history tables. +Five migration chains exist: Tenancy, Platform, Customization, Audit and +Education. The complete applied-table census, including job and pinned vendor +storage, is checked independently from `pg_catalog` by +[`SchemaTableClasses`](../../backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs). +Its reviewed classes cover every data table and the five migration-history tables. ## Naming @@ -1431,6 +1432,12 @@ changes `xmin` while leaving `row_version` intact. ## Read Models +Every new durable asynchronous table or stored projection must be reconciled +with the [canonical copy inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory) +and its explicit scope classifications (ADR-0046/0047/0057). Update the census +and planted controls before introducing an unsupported DDL form; inventory +coverage grants no erasure or purge authority. + Public read models consumed by other modules: - Live in the producing module's migrations. diff --git a/docs/standards/09-error-handling.md b/docs/standards/09-error-handling.md index ad4cafaef..ba701277c 100644 --- a/docs/standards/09-error-handling.md +++ b/docs/standards/09-error-handling.md @@ -390,6 +390,21 @@ Enforcement: - Architecture test `Domain_Methods_Do_Not_Throw_For_Expected_Cases` walks `Result`-returning methods and asserts the analyzer's report is empty. +## Sensitive Exception Messages + +Exception messages never carry sensitive values such as credentials. Property-based +runtime redaction does not scrub an exception's message. Use fixed messages and +the existing closed descriptors at durable failure boundaries. + +[ADR-0032 Amendment 6](../decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25) +defines `LS0002` (`LearnStackException-SensitiveExceptionMessage`): a bounded +sensitive-name guard on directly thrown exception string arguments, across all +production C# projects. The analyzer shares the runtime token matcher; it does +not trace earlier values, inspect literal contents or cover JavaScript/TypeScript. +Warning severity remains visible in CI until Phase 03 exit, when both `LS0001` +and `LS0002` become Errors. A justified public-metadata false positive may be +suppressed at that exact site; never silence the rule project-wide. + ## Controller Mapping — `Result` → `IActionResult` Per diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index ef362ea6a..3d259f972 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -677,7 +677,11 @@ In addition to system metrics, business KPIs: tenant id, organization id, user id, request path). - Provider events are tagged with `tenant_id` (and `organization_id` where applicable) to allow per-tenant inspection. -- PII redaction applied before the provider receives the event. +- The adapters redact matching `AdditionalTags` property names before provider + egress. Exception messages/stacks and unrelated values are not scrubbed; use + fixed messages and closed descriptors under + [Sensitive Exception Messages](09-error-handling.md#sensitive-exception-messages). + Phase 11 qualifies provider egress and retained diagnostic copies before production. - Sentry release tags match the deployed git sha. - The capture boundary — which exceptions go to the provider and which only to OTel — is in diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index c13f4637d..ca7fd7fe0 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -903,6 +903,11 @@ and the edge has no way to know it. ## Error Messages +- Exception strings contain no credentials or sensitive personal values. Runtime property + redaction does not scrub arbitrary exception messages; the bounded compile-time + guard and its limits are in + [Error Handling § Sensitive Exception Messages](09-error-handling.md#sensitive-exception-messages), + under ADR-0032 Amendment 6. Review and closed diagnostic controls still apply. - Server-side messages explain what happened; client-facing messages avoid disclosure. - 404 used to hide cross-tenant existence. - Stack traces never reach clients. diff --git a/docs/standards/17-code-review.md b/docs/standards/17-code-review.md index b49d9f7ba..2a99c92ec 100644 --- a/docs/standards/17-code-review.md +++ b/docs/standards/17-code-review.md @@ -5,6 +5,8 @@ Public accessibility enforcement additionally derives from [ADR-0027](../decisions/0027-frontend-i18n.md) and [ADR-0056](../decisions/0056-public-demo-browser-and-lighthouse-enforcement.md). +Exception diagnostic review additionally derives from +[ADR-0032](../decisions/0032-exception-handling-logging-and-observability.md#amendment-7--diagnostic-wiring-and-proof-clarifications-2026-10-25). How LearnStack reviews pull requests. The goal is faster, safer ship — not gatekeeping. @@ -58,6 +60,9 @@ Before requesting reviews, run the relevant checklist on your own diff: - [ ] Strongly-typed ids are used; no raw `Guid` on the public surface — except a module-local id in a cross-module contract, which is [ADR-0023 Amendment 8](../decisions/0023-strongly-typed-id-source-generator.md)'s bounded exception. - [ ] No `DateTime.UtcNow` / `DateTime.Now` in domain or application code (use `IClock` / `TimeProvider`). - [ ] Architecture tests still pass locally. +- [ ] Exception messages use fixed text; the bounded LS0002 corpus/build guard + passes with no project-wide suppression. Review values outside its + [name-based scope](09-error-handling.md#sensitive-exception-messages) separately. - [ ] Tenant-isolation test added for the new surface. ### Frontend self-review diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index 1e4015b6c..04ce2362c 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -553,19 +553,18 @@ table above is the policy those deliverables implement, not a description of tod changes no platform-admin pre-entry audit or other bypass operation. Accepted ADR-0047 adds only the named job/recurrence routing/status extension, conditional on exact grants/caller censuses, bounded diagnostics, metrics/health - and same-transaction terminal MUST audit. Until P02b-4 implements those controls, - acceptance grants no executable exemption; ordinary business mutations and - privileged maintenance remain audited under their existing contracts. + and same-transaction terminal MUST audit; + the [canonical job obligations](21-architecture-tests-catalogue.md#p02b-4-background-job-obligations) + name their owners and proofs. Ordinary business mutations and privileged + maintenance remain audited under their existing contracts. - Accepted ADR-0047's sixth `WriteJobTerminalAsync` method accepts only the actual fenced job-transition witness and matching caller connection/transaction. It validates stored tenant/organization/job/definition/attempt/acquisition values, MUST/SecurityEvent classification and the exact `platform.job.dead_letter` draft. It opens or commits no transaction; failed audit rolls back terminal state. - P02b-4 Step 5 implements this seam; its delivery record owns qualification and - review status. The event seam and original four writes retain their contracts. + The event seam and original four writes retain their contracts. - `WriteEventTerminalAsync(AuditEntryDraft, EventTerminalTransition, DbConnection, - DbTransaction, CancellationToken)` is the narrow fifth write, implemented in - P02b-2 Step 2; both independent review rounds passed. + DbTransaction, CancellationToken)` is the narrow fifth write. Only a successful fenced UPDATE result mints the restricted witness binding actual tenant/org/event/acquisition/kind/reason/attempts/subscription and live transaction. Validate declared MUST/SecurityEvent operation and matching draft diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index bfd7a9436..8f5841061 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -147,7 +147,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**263 test methods run in +**282 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, @@ -156,12 +156,12 @@ 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 -[Step 9 record](../roadmap/phase-02b-delivery-log.md#p02b-4-step-9--enforcement-and-packet-closeout-2026-10-18) -distinguishes local enforcement qualification from pending review/packet/CI closeout. -P02b-5 adds the authenticated route/helper census and closed claim/role authority -controls; its seven obligations have actual local owners. Its Step 5 and -[review remediation](../roadmap/phase-02b-delivery-log.md#p02b-5-external-review-remediation-2026-10-20) -records distinguish prior hosted qualification from the current correction head. +[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. @@ -169,10 +169,10 @@ and most rows pair a rule with the companion assertion that stops it passing vac **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 proved the point by being wrong on arrival: it published "ninety-five in that assembly" in the -same commit that added three more. The count of methods is the count of `[Fact]` and `[Theory]` -**declarations**, one per line, over source with literal contents removed — the attributes -written as strings inside `Every_Database_Test_Carries_The_Docker_Trait` and its companion are -not declarations, and the meta-test's `[Fact(DisplayName = …)]` is. +same commit that added three more. The method count uses **compiled methods** +carrying `[Fact]`/`[Theory]`, discovered by reflection. +Attributes written as fixture strings and declarations removed by conditional +compilation do not count; an actual `[Fact(DisplayName = …)]` method does. **The rows and the code are held together by a test, not by a table.** This section used to carry a hand-written list of rule → file, and it went stale the way any second copy does — on @@ -188,8 +188,8 @@ two fifths of its subject is the defect this section is about. It also refuses a test class that exists nowhere, because otherwise a renamed or deleted file drops its entries out of the subject instead of failing. -**235 rules in this catalogue are Implemented, and 133 of them are in that assembly.** -The other 102 are no less binding, and most could not live there. The table says where +**237 rules in this catalogue are Implemented, and 134 of them are in that assembly.** +The other 103 are no less binding, and most could not live there. The table says where and why, and deliberately carries no per-row count: those are the numbers nothing recomputes, and the first version of this table claimed "three rules" for a suite that holds ten. @@ -442,12 +442,11 @@ otherwise). Phase 03 escalation, and a pragma is the sanctioned way to keep a genuine invariant throw — so the test compiles each project's sources itself, sets the severity, and reports suppressed diagnostics. It parses with the symbols the build defines, so an `#if` region is - read rather than skipped, and it fails loudly on a source it cannot parse, because a compiler - behind the SDK reads a new language feature as a syntax error and a scan that cannot read a - file sees nothing in it. The wiring leg reads the reference as an element rather than as a - line: the attributes may be written in either order, a commented-out reference is not a - reference, and a `Condition` is refused outright — a conditional analyzer does not run in the - configuration the condition excludes, and this rule cannot tell which that is. Its companion, + read rather than skipped, and fails loudly on an unparseable source. The wiring + leg evaluates actual MSBuild imports and analyzer-reference metadata rather than + assuming each project spells out its own reference. It also verifies the + compiler-visible `LS0001` scope flag; shared assembly wiring for `LS0002` must + not broaden the older rule. Its companion, `The_Domain_Exception_Report_Can_Actually_Fail`, plants all four shapes — thrown from a `Result` method, the same one silenced by a pragma, a pragma-silenced invariant guard, and an unsuppressed throw — and requires exactly the three the rule refuses. Mutation-checked: @@ -465,11 +464,13 @@ otherwise). reviewer-dependent. Genuine aggregate-invariant throws (the sanctioned use) are the rare sites that suppress with justification (`#pragma warning disable LS0001`). The analyzer ships in - `backend/analyzers/LearnStack.Analyzers` and is referenced by every - module's `Domain` + `Application` project (and the core `LearnStack.Domain` - / `LearnStack.Application`) via - `` - (NOT a PackageReference — the analyzer is built in-tree, not packed). + `backend/analyzers/LearnStack.Analyzers`. The unconditional reference in + `backend/src/Directory.Build.props` loads it as an in-tree analyzer, with + `ReferenceOutputAssembly="false"`; the compiler-visible + `LearnStackAnalyzeDomainExceptionThrow` property preserves its exact + Domain/Application scope. The same reference loads + [LS0002](#learnstackexception-sensitiveexceptionmessage-roslyn-analyzer) in all + production projects. Do not duplicate per-project references. - **Severity:** Warning in Phase 02a; listed in `WarningsNotAsErrors` (Directory.Build.props) so it does not break CI under `TreatWarningsAsErrors` before the documented escalation. Flipped to Error @@ -484,6 +485,64 @@ otherwise). - **Status:** **Implemented** — analyzer + unit tests. - **Phase:** 02a (Packet 3). +#### `LearnStackException-SensitiveExceptionMessage` (Roslyn analyzer) + +- **Rule name:** `LearnStackException-SensitiveExceptionMessage`. +- **Diagnostic id:** `LS0002`. +- **Asserts:** direct thrown Exception construction is checked for sensitive + names in direct string references, interpolation and string concatenation, + within the bounded semantic contract in ADR-0032 Amendment 6. All production + C# projects under `backend/src` are wired automatically, while `LS0001` keeps + its Domain/Application scope. The runtime and analyzer use one internal + source for the complete single/two-word token union and word matcher. +- **Severity:** Warning, including CI; `WarningsNotAsErrors` preserves this + posture until Phase 03 exit, when both diagnostics become Errors. +- **Proofs:** compiler-clean positive/negative cases, exact ID/location/severity + and no `AD0001`; independent union and two-word-only mutation; evaluated + MSBuild/new-project wiring and unchanged `LS0001` scope; a real `CI=true` + Warning build and an unrelated-warning failure control. No taint analysis or + JavaScript/TypeScript coverage is claimed. +- **Source:** [ADR-0032 Amendment 6](../decisions/0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25). +- **Kind:** compile-time. +- **Status:** **Implemented** — analyzer, `SensitiveExceptionMessageAnalyzerTests` + and `AnalyzerBuildTests` in `LearnStack.Tests.Unit`. +- **Supporting architecture proofs:** + `SensitiveExceptionMessageTests` runs + `Production_Exception_Messages_Do_Not_Contain_Sensitive_References` for both + production configurations, including suppressed reports; + `The_Sensitive_Report_Sees_Suppressed_And_Conditional_Violations` plants them. + `AnalyzerWiringTests` checks evaluated settings and unconditional reference + ancestry, with OS/CI/Choose and editorconfig/targets suppression controls. + These are supporting proofs of this rule, not additional catalogue rules. +- **Phase:** 02b (P02b-8). + +#### `Durable_Async_Store_Inventory_Covers_The_Storage_Census` + +- **Asserts:** the canonical erasure inventory covers the actual event/job + storage census and all guarded vendor tables, including explicit control-only + classifications. Added tables, missing inventory rows and a removed row are + discriminated by planted controls. This is a coverage check, not a proof of + field-level erasure, legal compliance or personal-data absence. +- **Source:** ADR-0046/0047/0057 and + [Data Protection inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory), + accepted through [P02b-8](../roadmap/phase-02b-delivery-log.md#p02b-8-decision-package-2026-10-25). +- **Type:** storage-definition and documentation census with dirty controls. +- **Kind:** structural. +- **Status:** **Implemented** — `AsyncStoreInventoryTests` reads the ordered, + compiled `UpOperations` for Platform, Audit, Tenancy, Customization and Education, + including expanded vendor installer SQL. It reconciles every table with the + canonical inventory or an explicit synchronous/module exclusion. Opaque + procedural DDL, stored projections and unsupported schema/path changes fail + closed with their origin; planted controls assert the intended reason. + Vendor rows independently match + `HangfireStorageContract.Columns`. Added/dropped/renamed storage, every removed + row, duplicate/malformed tables and blank vendor classifications fail the + controls. Audit/provider/diagnostic/backup/volatile custody entries are required; + the independent live PostgreSQL `r`/`p`/`m` relation census remains a separate + backstop, with `StorageRelationCensusTests` checking each kind. Exact vendor + column shape remains the independent `HangfireSchemaShape.Verify` runtime proof. +- **Phase:** 02b (P02b-8). + #### `Handlers_Return_Result` - **Asserts:** every `IRequestHandler` implementation in any @@ -2694,6 +2753,12 @@ which decides identity, multiplicity, capture and classification; - **Type:** xUnit over the behavior and the scoped capture, with a nested-dispatch case. **Kind:** behavioural. - **Status:** **Implemented** (`AuditLogBehaviorTests`, Packet 9 step 8). A theory over three endings — success, refusal, handler exception — because each leaves the behaviour by a different door and only the `finally` is common to them; plus the nested case, so the pair pins "exactly once, by the outermost" rather than merely "at least once". + `DeliveryExecutionTests` additionally observes the unmodified production capture + populated by real saves, then empty on successful, faulted and lost-COMMIT + delivery. A completed retry produces no new frame or indeterminate row. + `AuditCaptureWiringTests` checks the real `IAuditStateCapture`/`IAuditSubject` + aliases and cross-scope isolation. `AuditStateCaptureTests` exercises cleared + nested state independently; the behavior tests retain exactly-once call proof. - **Phase:** 02a (Packet 9). #### `Every_Shipped_Request_Is_Registered` @@ -3320,6 +3385,9 @@ Introduced by [Phase 02b](../roadmap/phase-02b-events-auth.md). also checks the real HTTP producer's stored trace, announced tenant/org and exact nonempty partition; the delivery proof checks the same quartet for its outgoing event. Actual production consumers are Active. + Its lost-COMMIT theory independently counts exactly one row-bound standalone + `indeterminate` audit beside the durable success row, observes one outer capture + clear and proves that a rejected completed retry changes neither count. - **Phase:** 02b, P02b-3. #### `Integration_Event_Handlers_Use_InboxGuard` @@ -5069,9 +5137,9 @@ structural test proves — and what it does not. behavioural and asserted in `PlatformAdminGateTests`; a structural rule cannot see it. *Subject, vacuous:* there is no permission to hold. `AuthorizationBehavior.Handle` is - `return next()`, authentication arrives in - [Phase 02b](../roadmap/phase-02b-events-auth.md), and the Platform-scope permission - with the Identity module in [Phase 03](../roadmap/phase-03-identity-admin.md). So + `return next()`. 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 @@ -5691,8 +5759,9 @@ assertions below; each Implemented status names its actual canonical owner. Acceptance alone promotes no rule, and a partial foundation does not enforce a complete assertion. The [Step 9 record](../roadmap/phase-02b-delivery-log.md#canonical-enforcement-reconciliation) -distinguishes executed local qualification from packet/review and exact PR-head -CI/job-budget closure. +retains the original local enforcement scope; the +[merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) +records final packet/review and PR-source CI/job-budget qualification. Production business/recurrence registries remain empty; real framework subjects and fixture definitions make the implemented controls non-vacuous. diff --git a/docs/standards/README.md b/docs/standards/README.md index 0c7291092..9622d668c 100644 --- a/docs/standards/README.md +++ b/docs/standards/README.md @@ -108,8 +108,8 @@ included. | 02 | [Backend Coding](02-backend-coding.md) | **Active** | MediatR pipeline, `Result`, `IClock`, the `LS0001` analyzer and the pipeline-order test all ship. Packet 6 brought the first `DbContext`, the first aggregates and the ambient unit of work, so its EF Core and domain-modelling clauses became live. Tenancy, Customization, Audit and Education now implement domain and persistence code. | | 03 | [Frontend Coding](03-frontend-coding.md) | **Active** | ESLint and TypeScript strict mode are configured, the Vitest harness runs, and Packet 10 added the two rules this document's § Forbidden names — the direct-`fetch` ban and `dangerouslySetInnerHTML` outside the sanitised-HTML primitive — with a test that lints fixtures through the app's own configuration, because a configured rule and a missing one look identical from a green `pnpm lint`. P02d-5 delivers trusted entry/caller controls; P02d-6 Step 1 implements complete UI catalogues, ICU/callsite controls and synchronous chrome/state views; Step 2 adds catalog/course views and metadata; Step 3 adds ordered lesson presentation and blocking JSX accessibility controls. | | 04 | [API Design](04-api-design.md) | **Active** | Packet 4 shipped the versioned route convention and its startup guards, one Problem Details shape on every error including the framework-minted ones, cursor pagination, the sort grammar, idempotency keys, ETag concurrency, correlation ids, the request-body limit and the tenancy edge — each with tests in the required `backend` check. P02d-4 adds four institution public GET/HEAD pairs, served/snapshot contract controls and compatibility CI; application writers remain unrouted. | -| 05 | [Database](05-database.md) | **Active** | Packet 6 applied it — two migration chains, ten tables — and Packets 8 and 9 took it to four chains and seventeen data tables. P02d-1 Step 2 adds Education: five chains and twenty-one data tables (twenty-six including five migration-history tables), with parent-mirror and Pattern A proofs. The four-role model and the canonical RLS template this document owns — `ENABLE` **and** `FORCE`, one `AND`-ed policy per table, an explicit `WITH CHECK` — are asserted against a real PostgreSQL as `learnstack_app`. Its § Concurrency, § Table classes, § Indexes and § GRANT matrix each have a test that fails without them. Partitioning and the retention job are still ahead. | -| 06 | [Testing](06-testing.md) | **Active** | Unit, architecture and contract suites, and the Docker-free integration tests, run in the required `backend` job — Packet 4 removed the filter that used to exclude the integration assembly, which by then held the only tests that could catch an unversioned route. The Docker-bound `backend-integration` job activated in Packet 6 with the four-role provisioning suite; the split is by `[Trait("Requires","Docker")]` and the two jobs' filters are exact complements. The `backend-integration` job is required as of P02d-1, 2026-09-14 ([CONTRIBUTING § Branch protection](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main)). | +| 05 | [Database](05-database.md) | **Active** | Five compiled migration chains are reconciled against the independent live PostgreSQL census and canonical table classes; the [database standard](05-database.md#table-classes) owns the current classification. The four-role model and canonical RLS template (`ENABLE` **and** `FORCE`, one `AND`-ed policy per table) are tested as `learnstack_app`. Concurrency, indexes and exact grants each have planted controls. Partitioning and retention jobs belong to Phase 11. | +| 06 | [Testing](06-testing.md) | **Active** | Unit, architecture, contract and Docker-free HTTP populations feed the required backend aggregate; complementary ordinary/native Docker populations feed `backend integration (Testcontainers)`. The [CI contract](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main) names all seven required contexts. ADR-0063's complete current-attempt case and cleanup receipts, rather than a two-job filter sketch, enforce the partition. | | 07 | [Frontend Architecture](07-frontend-architecture.md) | **Active** | The one-app rule is mechanical — `Frontend_Has_Only_The_Web_App` fails a second application in this repository — and the route groups it prescribes exist as layouts. The rest, the server/client split and the tenant context an SDK call carries, is exercised first in [Phase 02d](../roadmap/phase-02d-walking-skeleton.md): Active for what ships, and the phase that adds components is the one that tests them. | | 08 | [Localization](08-localization.md) | **Active** | Packet 6 shipped `tenant_locales` and the slug schema. The partial unique default index enforces at most one default, not existence of a default for every enabled set; P02d-2 ships supported-write validation and the default-enabled CHECK constraint; raw deletes can still leave an enabled locale set without a default. `LocalizedText` and `LocalizedMessage` ship with their own cases, and API errors are keyed. P02d-1 shipped Education Pattern A satellites, canonical locales and flat localized-slug uniqueness; P02d-4 Step 3 delivers exact enabled public locale admission and response labels. P02d-5 Step 3 delivers membership-first redirect G36. P02d-6 Step 1 implements Accepted ADR-0027/G39's next-intl 4.14.9 plugin/request runtime, app-local `src/i18n/messages/{en,tr}/public.json` and catalogue controls. Phase 04 inherits the foundation for CMS/Studio. | | 09 | [Error Handling](09-error-handling.md) | **Active** | L1 `IExceptionHandler`, the exception hierarchy, `ProblemDetailsFactory` and `HttpStatusMap` shipped in Packet 3. | diff --git a/frontend/apps/web/scripts/verify-bff-browser.mjs b/frontend/apps/web/scripts/verify-bff-browser.mjs index 7ae89badb..c3546e6a2 100644 --- a/frontend/apps/web/scripts/verify-bff-browser.mjs +++ b/frontend/apps/web/scripts/verify-bff-browser.mjs @@ -207,6 +207,9 @@ try { .digest('base64'); const profile = join(root, 'chromium-profile'); mkdirSync(profile, { mode: 0o700 }); + // Keep SDK artifacts inside the root whose actual cleanup the fixture verifies. + const artifacts = join(root, 'playwright-artifacts'); + mkdirSync(artifacts, { mode: 0o700 }); owner.assertActive(); stage = 'browser-spawn'; browserProcess = owner.ownChild( @@ -263,7 +266,10 @@ try { timeout: 10_000, }); stage = 'browser-connect'; - browser = await chromium.connectOverCDP('http://127.0.0.1:' + port, { timeout: 10000 }); + browser = await chromium.connectOverCDP('http://127.0.0.1:' + port, { + timeout: 10000, + artifactsDir: artifacts, + }); version = browser.version(); assert.match(version, /^\d+(?:\.\d+){1,3}$/); stage = 'browser-context'; diff --git a/infra/apisix/README.md b/infra/apisix/README.md index 378f53a8a..6c7797222 100644 --- a/infra/apisix/README.md +++ b/infra/apisix/README.md @@ -1,7 +1,9 @@ # APISIX Gateway (Dev) -LearnStack's only tenant-facing ingress, per +LearnStack's demand-gated gateway, per [ADR-0015 (API Gateway: APISIX)](../../docs/decisions/0015-api-gateway-apisix.md). +The current native development ingress runs without it; Phase 11 owns activation +on [ADR-0035's gateway trigger](../../docs/decisions/0035-demand-gated-infrastructure.md#the-gated-set). File-driven standalone mode — `apisix.yaml` is the only source of truth, hot-reloaded on file change. No etcd, no Admin API, no dashboard. @@ -51,9 +53,10 @@ route-level `ip-restriction`; see the commented stub at the bottom of | 99 | `/api/v*/**` | OPTIONS | `cors` only (preflight bypass) | `host.docker.internal:5080` | | 100 | `/api/v*/**` | GET/POST/PUT/PATCH/DELETE | `cors`, `limit-req` (100 r/s), `request-id`, `prometheus` | `host.docker.internal:5080` | -`openid-connect` is **commented out** in route 100; Phase 03 wires the -plugin against the `learnstack` Keycloak realm discovery endpoint. The -backend re-validates the JWT (defence in depth — gateway compromise must +`openid-connect` is **commented out** in route 100; Phase 11 qualifies the +gateway plugin against the `learnstack` Keycloak realm discovery endpoint. +Phase 03 owns the published route-priority and secret-reference corrections. +The backend re-validates the JWT (defence in depth — gateway compromise must not bypass auth). The `/api/internal/*` route is a **disabled placeholder** documenting the @@ -95,6 +98,7 @@ surface is the SSL cert pair that Phase 11 introduces when TLS lands. - Hub-side APISIX route block (`hub.learnstack.dev`) — Phase 02c, lives in the separate `learnstack-hub` repo. - The .NET `AddJwtBearer` middleware (the backend's defence-in-depth - JWT re-validation) — Phase 02b. -- Hangfire dashboard `/admin/hangfire*` gating — Phase 08a when Hangfire - itself lands. + JWT validation) — delivered in Phase 02b, independently of this gateway. +- Hangfire dashboard `/admin/hangfire*` gating — Phase 03 owns the application + permission and route; Phase 11 owns the APISIX boundary. Phase 02b maps no + dashboard route. diff --git a/infra/apisix/apisix.yaml b/infra/apisix/apisix.yaml index b9260a172..ac19df359 100644 --- a/infra/apisix/apisix.yaml +++ b/infra/apisix/apisix.yaml @@ -51,7 +51,7 @@ routes: priority: 100 plugins: cors: {} - # openid-connect realm discovery is wired in Phase 03 against the + # Phase 11 qualifies openid-connect before gateway activation against the # learnstack Keycloak realm. Placeholder kept so the route schema # validates today. # openid-connect: diff --git a/infra/apisix/config.yaml b/infra/apisix/config.yaml index b2247ec29..79b89d57c 100644 --- a/infra/apisix/config.yaml +++ b/infra/apisix/config.yaml @@ -33,7 +33,7 @@ nginx_config: plugins: - real-ip - cors - - openid-connect # JWT validation (Phase 03 wires Keycloak realm) + - openid-connect # Phase 11 qualifies JWT validation before activation - jwt-auth - limit-req - limit-count diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index bd902f1d6..7279d1b0c 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -8585,6 +8585,7 @@ "LearnStack.Tests.Integration.Database.PublicServerRenderingTests", "LearnStack.Tests.Integration.Database.PublicSiteHttpTests", "LearnStack.Tests.Integration.Database.SeederTests", + "LearnStack.Tests.Integration.Database.StorageRelationCensusTests", "LearnStack.Tests.Integration.Database.TenancySchemaTests", "LearnStack.Tests.Integration.Database.TenancyWriterTests", "LearnStack.Tests.Integration.Database.TenantAssertionAuditTests",