diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_09_01.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_09_01.trx
new file mode 100644
index 0000000..9b14d5e
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_09_01.trx
@@ -0,0 +1,2711 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_10_57.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_10_57.trx
new file mode 100644
index 0000000..67fa95d
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_10_57.trx
@@ -0,0 +1,2841 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/implementation-log.md b/ImplementationPlan/implementation-log.md
index abf9703..38b13d9 100644
--- a/ImplementationPlan/implementation-log.md
+++ b/ImplementationPlan/implementation-log.md
@@ -43,3 +43,7 @@ SummaryPolicy, TrendPolicy, ClinicalPolicy and Guidance-owned versioned Referenc
### Stage 5 checkpoint — passed
Overview composes typed Profile, Observation and Analytics queries; profile/latest/selected series share repeatable-read from authorization. Analytics releases capture before calculation. Deterministic interleaving commits Profile and Observation changes after Profile capture: in-flight overview stays old/coherent; next sees new values; selected query called once; transaction inactive before Analytics returns. All adopted Overview, patient and professional suites pass: 266/266 cases, zero warnings/errors. Ownership now checks route metadata before model validation to preserve denied empty-404 behaviour. Stage 4 commit `cab10c5`.
+
+### Stage 6 checkpoint — passed
+
+Bounded pooled DB source, configurable health/assessment admission and deadlines, cancellation/rollback, release-before-result filter, sanitized dependency errors/no-store, authenticated liveness/readiness and fail-closed remote VerifyFull requirement. Deterministic locked-write deadline leaves profile unchanged; exhausted assessment budget returns 503+Retry-After while public guidance works; DB outage readiness is 503 while guidance/login remain usable. Restored original replacement-handler same-normalized-identity own/other assertions using real B profiles rather than obsolete HTTP stub. Fresh-schema context-default test retains all original value/text/Unknown assertions, with explicit synthetic associated patient for FK and no live migration. Module conformance checks pass. 276/276 tests passed; zero warnings/errors. Stage 5 commit `cc7f871`. Native deployment verification remains pending.
diff --git a/ImplementationPlan/test-adaptations.md b/ImplementationPlan/test-adaptations.md
index 9c264d5..9b7d384 100644
--- a/ImplementationPlan/test-adaptations.md
+++ b/ImplementationPlan/test-adaptations.md
@@ -20,3 +20,6 @@ Insight/context/trend/deletion-derived tests: service-stop helpers represent DB
| PatientAuthenticationTests.Direct_services_reject_client_tokens_missing_keys_and_forged_keys / Service_credentials_are_limited_to_their_documented_read_calls | Replaced together by Sole_public_edge_accepts_client_ticket_but_service_headers_grant_no_access: valid client ticket works at sole edge, forged service headers grant nothing, internal by-account route absent. Originals remain baseline evidence. Patient/professional denial matrices unchanged |
| PatientAuthenticationTests.Database_failure_rolls_back_profile_and_association_together | Same B-local trigger/no-row/retry assertions, search_path resolves owned Profile schema; unexpected write failure still 500 |
| Original view/overview wire DTOs | Same JSON fields. Shared context DTO nullable annotation needs test null-forgiving operator after established setup; assertions unchanged |
+
+| Original AuthenticationIntegrationTests replacement handler | Standard ASP.NET replacement scheme is now default at sole edge; test seeds real B-local Profile instead of HTTP PatientHandler. Own 200, other empty 404 assertions unchanged. Production HTTP rejection test retained |
+| MeasurementContextMigrationTests | Fresh schema given equivalent synthetic row and required associated patient; same original IDs/times/values/text/Unknown detail assertions. No old-schema/live import, per Q4 |
diff --git a/src/HealthApp.Infrastructure/RequestTransaction.cs b/src/HealthApp.Infrastructure/RequestTransaction.cs
index c77fe62..2f108e9 100644
--- a/src/HealthApp.Infrastructure/RequestTransaction.cs
+++ b/src/HealthApp.Infrastructure/RequestTransaction.cs
@@ -28,7 +28,7 @@ public sealed class RequestTransaction(NpgsqlDataSource source) : IAsyncDisposab
}
public async ValueTask DisposeAsync()
{
- if(Transaction is not null)await Transaction.DisposeAsync();
- if(Connection is not null)await Connection.DisposeAsync();
+ if(Transaction is not null){await Transaction.DisposeAsync();Transaction=null;}
+ if(Connection is not null){await Connection.DisposeAsync();Connection=null;}
}
}
diff --git a/src/HealthApp/Program.cs b/src/HealthApp/Program.cs
index e43703c..1179e4b 100644
--- a/src/HealthApp/Program.cs
+++ b/src/HealthApp/Program.cs
@@ -16,7 +16,10 @@ public class Program
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
- builder.Services.AddControllers();
+ builder.Logging.AddFilter("Microsoft.AspNetCore",LogLevel.Warning);
+ builder.Logging.AddFilter("Microsoft.EntityFrameworkCore",LogLevel.None);
+ builder.Services.AddControllers(o=>o.Filters.Add());
+ builder.Services.AddSingleton();
builder.Services.AddProblemDetails();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
@@ -26,6 +29,8 @@ public class Program
var text=c.GetConnectionString("HealthDatabase");
if(string.IsNullOrWhiteSpace(text))throw new InvalidOperationException("HealthDatabase connection is required.");
var options=new NpgsqlConnectionStringBuilder(text){Pooling=true,MaxPoolSize=c.GetValue("Resources:MaxPoolSize",32)};
+ var local=options.Host is "localhost" or "127.0.0.1" or "::1" || options.Host?.StartsWith('/')==true;
+ if((c.GetValue("Database:Remote",false)||!local)&&options.SslMode!=SslMode.VerifyFull)throw new InvalidOperationException("Remote database requires verified TLS and hostname checking.");
return NpgsqlDataSource.Create(options.ConnectionString);
});
builder.Services.AddScoped();builder.Services.AddProfile();builder.Services.AddObservations();builder.Services.AddScoped();
@@ -44,6 +49,9 @@ public class Program
var lifetime=app.Configuration.GetValue("Authentication:TokenLifetimeMinutes",30);
if(lifetime is <=0 or >1440)throw new InvalidOperationException("Invalid token lifetime.");
if(string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"]))throw new InvalidOperationException("Authentication:KeyDirectory is required.");
+ _=app.Services.GetRequiredService();
+ if(app.Configuration.GetValue("Resources:RequestDeadlineSeconds",30d)<=0)throw new InvalidOperationException("Request deadline must be positive.");
+ if(!string.IsNullOrWhiteSpace(app.Configuration.GetConnectionString("HealthDatabase")))_=app.Services.GetRequiredService();
_=app.Services.GetRequiredService();
_=app.Services.GetRequiredService();
app.UseExceptionHandler();
@@ -53,26 +61,19 @@ public class Program
await next(ctx);
});
app.UseAuthentication();app.UseAuthorization();
- app.Use(async(ctx,next)=> {
- if(ctx.GetEndpoint()?.Metadata.GetMetadata() is not null || ctx.Request.Path.StartsWithSegments("/api/professionals")){await next(ctx);return;}
- if(ctx.User.Identity?.IsAuthenticated!=true){await next(ctx);return;}
- if(ctx.User.IsInRole("HealthcareProfessional") && ctx.Request.Method!="GET"){ctx.Response.StatusCode=403;return;}
- var tx=ctx.RequestServices.GetRequiredService();
+ app.UseMiddleware();
+ app.MapControllers();
+ app.MapGet("/health/live",()=>Results.Ok(new{status="live"})).RequireAuthorization();
+ app.MapGet("/health/ready",async (HttpContext ctx)=>{
try{
- var write=ctx.Request.Method!="GET";
- await tx.BeginAsync(write,ctx.RequestAborted);
- Guid? actual=null;
- if(Guid.TryParse(ctx.Request.RouteValues["patientId"]?.ToString(),out var patientId))actual=patientId;
- else if(Guid.TryParse(ctx.Request.RouteValues["observationId"]?.ToString(),out var observationId))actual=await ctx.RequestServices.GetRequiredService().ResolveOwnerAsync(observationId,ctx.RequestAborted);
- if(ctx.Request.RouteValues.ContainsKey("patientId") || ctx.Request.RouteValues.ContainsKey("observationId"))
- {
- var approved=actual is null?null:await ctx.RequestServices.GetRequiredService().AuthorizeAsync(ctx.User,actual.Value,write,ctx.RequestAborted);
- if(approved is null){ctx.Response.StatusCode=404;return;}
- }
- await next(ctx);
- }
- catch(NpgsqlException){if(ctx.Response.HasStarted)ctx.Abort();else {ctx.Response.Clear();await Results.Problem(statusCode:503,title:"Health data dependency is unavailable.").ExecuteAsync(ctx);}}
- });app.MapControllers();
+ _=ctx.RequestServices.GetRequiredService().CreateProtector("readiness").Protect("probe");
+ var catalog=ctx.RequestServices.GetRequiredService();
+ if(string.IsNullOrWhiteSpace(catalog.Version))return Results.StatusCode(503);
+ await using var connection=await ctx.RequestServices.GetRequiredService().OpenConnectionAsync(ctx.RequestAborted);
+ await using var command=new NpgsqlCommand("SELECT (SELECT max(version) FROM profile.schema_version)=1 AND (SELECT max(version) FROM observations.schema_version)=1",connection);
+ return await command.ExecuteScalarAsync(ctx.RequestAborted) is true?Results.Ok(new{status="ready"}):Results.StatusCode(503);
+ }catch(NpgsqlException){return Results.StatusCode(503);}
+ }).RequireAuthorization();
await app.RunAsync();
}
}
diff --git a/src/HealthApp/Security/RequestBoundaryMiddleware.cs b/src/HealthApp/Security/RequestBoundaryMiddleware.cs
new file mode 100644
index 0000000..745bc3f
--- /dev/null
+++ b/src/HealthApp/Security/RequestBoundaryMiddleware.cs
@@ -0,0 +1,71 @@
+using HealthApp.Contracts;
+using HealthApp.Infrastructure;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc.Filters;
+using Npgsql;
+namespace HealthApp.Security;
+public sealed class RequestAdmission(IConfiguration configuration) : IDisposable
+{
+ public SemaphoreSlim Health {get;}=new(Positive(configuration,"Resources:MaxConcurrentRequests",32));
+ public SemaphoreSlim Assessment {get;}=new(Positive(configuration,"Resources:MaxConcurrentAssessments",4));
+ private static int Positive(IConfiguration c,string key,int fallback)
+ {var value=c.GetValue(key,fallback);return value>0?value:throw new InvalidOperationException(key+" must be positive.");}
+ public void Dispose(){Health.Dispose();Assessment.Dispose();}
+}
+public sealed class ReleaseTransactionFilter : IAsyncActionFilter
+{
+ public async Task OnActionExecutionAsync(ActionExecutingContext context,ActionExecutionDelegate next)
+ {
+ try{await next();}
+ finally{if(context.HttpContext.Items[typeof(RequestTransaction)] is RequestTransaction tx && tx.Active)await tx.DisposeAsync();}
+ }
+}
+public sealed class RequestBoundaryMiddleware(RequestDelegate next,RequestAdmission admission,IConfiguration configuration,ILogger logger)
+{
+ public async Task InvokeAsync(HttpContext ctx)
+ {
+ if(ctx.GetEndpoint() is null || ctx.GetEndpoint()!.Metadata.GetMetadata() is not null || ctx.Request.Path.StartsWithSegments("/api/professionals") || ctx.Request.Path.StartsWithSegments("/health")){await next(ctx);return;}
+ if(ctx.User.Identity?.IsAuthenticated!=true){await next(ctx);return;}
+ if(!ctx.User.IsInRole("Patient")&&!ctx.User.IsInRole("HealthcareProfessional")){ctx.Response.StatusCode=403;return;}
+ if(ctx.User.IsInRole("HealthcareProfessional")&&ctx.Request.Method!="GET"){ctx.Response.StatusCode=403;return;}
+ var assessment=ctx.Request.RouteValues["controller"]?.ToString() is "Insights" or "HealthOverview";
+ if(!await admission.Health.WaitAsync(0,ctx.RequestAborted)){await Overloaded(ctx);return;}
+ var assessmentHeld=false;
+ var parent=ctx.RequestAborted;
+ using var deadline=CancellationTokenSource.CreateLinkedTokenSource(parent);
+ deadline.CancelAfter(TimeSpan.FromSeconds(configuration.GetValue("Resources:RequestDeadlineSeconds",30d)));
+ ctx.RequestAborted=deadline.Token;
+ RequestTransaction? tx=null;
+ try
+ {
+ if(assessment){assessmentHeld=await admission.Assessment.WaitAsync(0,deadline.Token);if(!assessmentHeld){await Overloaded(ctx);return;}}
+ tx=ctx.RequestServices.GetRequiredService();ctx.Items[typeof(RequestTransaction)]=tx;
+ var write=ctx.Request.Method!="GET";await tx.BeginAsync(write,deadline.Token);
+ Guid? actual=null;
+ if(Guid.TryParse(ctx.Request.RouteValues["patientId"]?.ToString(),out var patient))actual=patient;
+ else if(Guid.TryParse(ctx.Request.RouteValues["observationId"]?.ToString(),out var observation))actual=await ctx.RequestServices.GetRequiredService().ResolveOwnerAsync(observation,deadline.Token);
+ if(ctx.Request.RouteValues.ContainsKey("patientId")||ctx.Request.RouteValues.ContainsKey("observationId"))
+ {
+ var scope=actual is null?null:await ctx.RequestServices.GetRequiredService().AuthorizeAsync(ctx.User,actual.Value,write,deadline.Token);
+ if(scope is null){ctx.Response.StatusCode=404;return;}
+ }
+ await next(ctx);
+ }
+ catch(OperationCanceledException) when(parent.IsCancellationRequested){ctx.Abort();}
+ catch(OperationCanceledException){ctx.RequestAborted=parent;await Failure(ctx,504);}
+ catch(NpgsqlException e){ctx.RequestAborted=parent;await Failure(ctx,e.InnerException is TimeoutException?504:503);}
+ finally
+ {
+ if(tx is not null)await tx.DisposeAsync();ctx.RequestAborted=parent;
+ if(assessmentHeld)admission.Assessment.Release();admission.Health.Release();
+ }
+ }
+ private Task Failure(HttpContext ctx,int status)
+ {
+ logger.LogWarning("Operation {Operation} failed with {Status}; correlation {Correlation}",ctx.Request.RouteValues["action"],status,ctx.TraceIdentifier);
+ if(ctx.Response.HasStarted){ctx.Abort();return Task.CompletedTask;}
+ ctx.Response.Clear();ctx.Response.Headers.CacheControl="no-store";
+ return Results.Problem(statusCode:status,title:status==504?"Request deadline reached.":"Health data dependency is unavailable.").ExecuteAsync(ctx);
+ }
+ private static Task Overloaded(HttpContext ctx){ctx.Response.Headers.RetryAfter="1";ctx.Response.Headers.CacheControl="no-store";return Results.Problem(statusCode:503,title:"Request capacity is unavailable.").ExecuteAsync(ctx);}
+}
diff --git a/tests/HealthApp.AcceptanceTests/AuthenticationIntegrationTests.cs b/tests/HealthApp.AcceptanceTests/AuthenticationIntegrationTests.cs
new file mode 100644
index 0000000..176f4d6
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/AuthenticationIntegrationTests.cs
@@ -0,0 +1,82 @@
+using System.Net;
+using System.Security.Claims;
+using System.Text;
+using System.Text.Encodings.Web;
+using HealthApp.TestSupport;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using Xunit;
+
+namespace PatientProfile.AcceptanceTests;
+
+public sealed class AuthenticationIntegrationTests
+{
+ [Fact]
+ public async Task Production_gateway_rejects_plain_http_even_for_login_and_public_guidance()
+ {
+ var authentication = new AuthenticatedTestClient();
+ try
+ {
+ var configuration = authentication.Configuration();
+ foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
+ configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/";
+ using var host = new WebApplicationFactory().WithWebHostBuilder(builder =>
+ {
+ builder.UseEnvironment("Production");
+ builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
+ });
+ using var http = host.CreateClient();
+ using var guidance = await http.GetAsync("/api/measurement-guidance");
+ Assert.Equal(HttpStatusCode.BadRequest, guidance.StatusCode);
+ using var login = await http.PostAsync("/api/authentication/login", new StringContent("{}", Encoding.UTF8, "application/json"));
+ Assert.Equal(HttpStatusCode.BadRequest, login.StatusCode);
+ using var https = host.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
+ using var available = await https.GetAsync("/api/measurement-guidance");
+ Assert.Equal(HttpStatusCode.OK, available.StatusCode);
+ }
+ finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
+ }
+
+ [Theory]
+ [InlineData("Patient", "test-0")]
+ [InlineData("HealthcareProfessional", "professional")]
+ public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy(string role,string accountId)
+ {
+ var fixture=new PatientApiFixture();await fixture.InitializeAsync();
+ try
+ {
+ Guid patient=Guid.NewGuid();
+ await using(var db=fixture.CreateDbContext())
+ {
+ var time=new DateTime(2026,9,12);
+ db.Patients.Add(new HealthApp.Profile.Domain.Patient{PatientId=patient,AccountId="test-0",Name="Replacement",DateOfBirth=new DateOnly(1980,1,1),CreatedAt=time,UpdatedAt=time});await db.SaveChangesAsync();
+ }
+ fixture.AdditionalGatewayConfiguration["TestIdentity:Role"]=role;fixture.AdditionalGatewayConfiguration["TestIdentity:AccountId"]=accountId;
+ fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:{accountId}:0"]=patient.ToString();
+ fixture.ConfigureServices=services=>{
+ services.AddAuthentication().AddScheme("Replacement",null);
+ services.PostConfigure(options=>{options.DefaultAuthenticateScheme="Replacement";options.DefaultChallengeScheme="Replacement";options.DefaultScheme="Replacement";});
+ };
+ await fixture.RestartHostsAsync();
+ using var own=await fixture.RawClient.GetAsync($"/api/patients/{patient}");Assert.Equal(HttpStatusCode.OK,own.StatusCode);
+ using var other=await fixture.RawClient.GetAsync($"/api/patients/{Guid.NewGuid()}");Assert.Equal(HttpStatusCode.NotFound,other.StatusCode);Assert.Empty(await other.Content.ReadAsStringAsync());
+ }
+ finally{await fixture.DisposeAsync();}
+ }
+
+ public sealed class ReplacementHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
+ : AuthenticationHandler(options, logger, encoder)
+ {
+ protected override Task HandleAuthenticateAsync() => Task.FromResult(
+ AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[]
+ {
+ new Claim(ClaimTypes.NameIdentifier, configuration["TestIdentity:AccountId"]!), new Claim(ClaimTypes.Role, configuration["TestIdentity:Role"]!)
+ }, Scheme.Name)), Scheme.Name)));
+ }
+
+}
diff --git a/tests/HealthApp.AcceptanceTests/ConformanceTests.cs b/tests/HealthApp.AcceptanceTests/ConformanceTests.cs
new file mode 100644
index 0000000..ab2a661
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/ConformanceTests.cs
@@ -0,0 +1,31 @@
+using System.Reflection;
+using HealthApp.Contracts;
+using HealthApp.TestSupport;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Xunit;
+namespace HealthApp.AcceptanceTests;
+public sealed class ConformanceTests
+{
+ [Fact]
+ public void Persistence_entities_and_contexts_are_private_and_dependency_graph_is_acyclic()
+ {
+ var assemblies=new[]{typeof(HealthApp.Profile.ProfileModule).Assembly,typeof(HealthApp.Observations.ObservationsModule).Assembly,typeof(HealthApp.Analytics.AnalyticsModule).Assembly,typeof(HealthApp.Overview.OverviewModule).Assembly,typeof(HealthApp.Guidance.GuidanceQueries).Assembly};
+ foreach(var assembly in assemblies)
+ {
+ Assert.DoesNotContain(assembly.GetExportedTypes(),t=>t.Name.EndsWith("DbContext")||t.Name is "Patient" or "BloodPressureObservation");
+ Assert.DoesNotContain(assembly.GetReferencedAssemblies(),a=>a.Name=="HealthApp");
+ }
+ foreach(var a in new[]{typeof(HealthApp.Analytics.AnalyticsModule).Assembly,typeof(HealthApp.Overview.OverviewModule).Assembly,typeof(HealthApp.Guidance.GuidanceQueries).Assembly})Assert.DoesNotContain(a.GetTypes(),t=>typeof(Microsoft.EntityFrameworkCore.DbContext).IsAssignableFrom(t));
+ Assert.Empty(typeof(AuthorizedPatientContext).GetConstructors(BindingFlags.Public|BindingFlags.Instance));
+ }
+ [Fact]
+ public void Final_solution_has_one_web_host_and_no_reference_project_or_internal_business_http()
+ {
+ var root=PatientProfile.AcceptanceTests.PatientApiFixture.FindRoot();var solution=File.ReadAllText(Path.Combine(root,"HealthApp.slnx"));Assert.DoesNotContain("Reference/",solution);
+ var webProjects=Directory.GetFiles(Path.Combine(root,"src"),"*.csproj",SearchOption.AllDirectories).Where(p=>File.ReadAllText(p).Contains("Sdk=\"Microsoft.NET.Sdk.Web\""));Assert.Single(webProjects);
+ foreach(var path in Directory.GetFiles(Path.Combine(root,"src"),"*.cs",SearchOption.AllDirectories).Where(p=>!p.Contains("/obj/")&&!p.Contains("/bin/")))
+ {var code=File.ReadAllText(path);Assert.DoesNotContain("IHttpClientFactory",code);Assert.DoesNotContain("X-Service-Key",code);Assert.DoesNotContain("X-Gateway-Key",code);}
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/MeasurementContextMigrationTests.cs b/tests/HealthApp.AcceptanceTests/MeasurementContextMigrationTests.cs
new file mode 100644
index 0000000..17907dd
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/MeasurementContextMigrationTests.cs
@@ -0,0 +1,70 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Npgsql;
+using HealthApp.Observations.Persistence;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class MeasurementContextMigrationTests
+{
+ [Fact]
+ public async Task Fresh_schema_retains_original_values_and_text_without_inventing_context()
+ {
+ var admin = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")
+ ?? throw new InvalidOperationException("TEST_POSTGRES_CONNECTION is required.");
+ var database = "us04_context_upgrade_" + Guid.NewGuid().ToString("N");
+ await using var connection = new NpgsqlConnection(admin);
+ await connection.OpenAsync();
+ await using (var create = new NpgsqlCommand($"CREATE DATABASE {database}", connection))
+ await create.ExecuteNonQueryAsync();
+ try
+ {
+ var options = new DbContextOptionsBuilder().UseNpgsql(
+ new NpgsqlConnectionStringBuilder(admin) { Database = database }.ConnectionString).Options;
+ await using var db = new ObservationDbContext(options);
+ await using(var target=new NpgsqlConnection(new NpgsqlConnectionStringBuilder(admin){Database=database}.ConnectionString))
+ {
+ await target.OpenAsync();
+ foreach(var module in new[]{"Profile","Observations"})
+ foreach(var file in Directory.GetFiles(Path.Combine(PatientProfile.AcceptanceTests.PatientApiFixture.FindRoot(),"src/Modules",module,"Migrations"),"*.sql"))
+ await new NpgsqlCommand(await File.ReadAllTextAsync(file),target).ExecuteNonQueryAsync();
+ }
+ var observation = Guid.NewGuid();
+ var patient = Guid.NewGuid();
+ await db.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO profile.patient(patient_id,account_id,name,date_of_birth,created_at,updated_at) VALUES ({patient}, 'historical-test', 'Synthetic history', '1980-01-01', '2026-09-12 09:00:00', '2026-09-12 09:00:00')");
+ await db.Database.ExecuteSqlInterpolatedAsync($"""
+ INSERT INTO observations.observation
+ (observation_id, patient_id, measured_at, systolic, diastolic, pulse, context, note, created_at, updated_at)
+ VALUES ({observation}, {patient}, '2026-09-12 08:00:00', 128, 82, 68,
+ 'Morning reading; resting?', 'Historical note', '2026-09-12 09:00:00', '2026-09-12 09:00:00')
+ """);
+
+ var saved = await db.Observations.AsNoTracking().SingleAsync();
+ Assert.Equal(observation, saved.ObservationId);
+ Assert.Equal(patient, saved.PatientId);
+ Assert.Equal(new DateTime(2026, 9, 12, 8, 0, 0), saved.MeasuredAt);
+ Assert.Equal(128, saved.Systolic);
+ Assert.Equal(82, saved.Diastolic);
+ Assert.Equal(68, saved.Pulse);
+ Assert.Equal("Morning reading; resting?", saved.Context);
+ Assert.Equal("Historical note", saved.Note);
+ Assert.Equal("Unknown", saved.MeasurementContext.Setting);
+ Assert.Equal("Unknown", saved.MeasurementContext.ActivityCondition);
+ Assert.Null(saved.MeasurementContext.RestDurationMinutes);
+ Assert.Null(saved.MeasurementContext.BodyPosition);
+ Assert.Null(saved.MeasurementContext.MeasuredArm);
+ Assert.Null(saved.MeasurementContext.DeviceDetails);
+ Assert.Null(saved.MeasurementContext.CuffDetails);
+ Assert.Null(saved.MeasurementContext.AdditionalCircumstances);
+ Assert.Equal(new DateTime(2026, 9, 12, 9, 0, 0), saved.CreatedAt);
+ Assert.Equal(saved.CreatedAt, saved.UpdatedAt);
+ }
+ finally
+ {
+ await using var drop = new NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", connection);
+ await drop.ExecuteNonQueryAsync();
+ }
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/OperationalTests.cs b/tests/HealthApp.AcceptanceTests/OperationalTests.cs
new file mode 100644
index 0000000..486b52e
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/OperationalTests.cs
@@ -0,0 +1,76 @@
+using Microsoft.Extensions.DependencyInjection;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using HealthApp.TestSupport;
+using Npgsql;
+using Observation.AcceptanceTests;
+using Xunit;
+namespace HealthApp.AcceptanceTests;
+public sealed class OperationalTests(ObservationApiFixture fixture) : IClassFixture
+{
+ [Fact]
+ public async Task Readiness_uses_configured_schemas_and_guidance_remains_public_during_database_outage()
+ {
+ var token=await AuthenticatedTestClient.LoginAsync(fixture.RawClient);
+ async Task Ready(){using var q=new HttpRequestMessage(HttpMethod.Get,"/health/ready");q.Headers.Authorization=new AuthenticationHeaderValue("Bearer",token);return await fixture.RawClient.SendAsync(q);}
+ using(var ready=await Ready())Assert.Equal(HttpStatusCode.OK,ready.StatusCode);
+ await fixture.StopObservationServiceAsync();
+ try
+ {
+ using var notReady=await Ready();Assert.Equal(HttpStatusCode.ServiceUnavailable,notReady.StatusCode);
+ using var guidance=await fixture.RawClient.GetAsync("/api/measurement-guidance");Assert.Equal(HttpStatusCode.OK,guidance.StatusCode);
+ Assert.NotEmpty(await AuthenticatedTestClient.LoginAsync(fixture.RawClient));
+ }
+ finally{await fixture.RestartHostsAsync();}
+ }
+ [Fact]
+ public async Task Deadline_cancels_locked_write_without_changing_profile()
+ {
+ using var create=await fixture.Client.PostAsJsonAsync("/api/patients",new{name="Keep",dateOfBirth="1980-01-01"});var p=(await create.Content.ReadFromJsonAsync())!;
+ fixture.AdditionalGatewayConfiguration["Resources:RequestDeadlineSeconds"]="0.2";await fixture.RestartHostsAsync();
+ await using var c=new NpgsqlConnection(fixture.ConnectionString);await c.OpenAsync();await using var t=await c.BeginTransactionAsync();
+ await new NpgsqlCommand("SELECT patient_id FROM profile.patient WHERE patient_id=@id FOR UPDATE",c,t){Parameters={new NpgsqlParameter("id",p.PatientId)}}.ExecuteScalarAsync();
+ try
+ {
+ using var timed=await fixture.Client.PutAsJsonAsync($"/api/patients/{p.PatientId}",new{name="Must not persist"});
+ Assert.Equal(HttpStatusCode.GatewayTimeout,timed.StatusCode);
+ await t.RollbackAsync();var saved=(await fixture.Client.GetFromJsonAsync($"/api/patients/{p.PatientId}"))!;Assert.Equal("Keep",saved.Name);
+ }
+ finally{fixture.AdditionalGatewayConfiguration.Remove("Resources:RequestDeadlineSeconds");await fixture.RestartHostsAsync();}
+ }
+ [Fact]
+ public async Task Assessment_admission_does_not_block_guidance_and_overload_is_explicit()
+ {
+ using var create=await fixture.Client.PostAsJsonAsync("/api/patients",new{name="Budget",dateOfBirth="1980-01-01"});var p=(await create.Content.ReadFromJsonAsync())!;
+ fixture.AdditionalGatewayConfiguration["Resources:MaxConcurrentAssessments"]="1";await fixture.RestartHostsAsync();
+ var held=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);var release=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ fixture.ConfigureServices=services=>{
+ var descriptor=services.Last(d=>d.ServiceType==typeof(ProfileQueries));services.Remove(descriptor);
+ services.AddScoped(sp=>new PausedProfile((ProfileQueries)descriptor.ImplementationFactory!(sp),async()=>{held.TrySetResult();await release.Task;}));
+ };await fixture.RestartHostsAsync();
+ try
+ {
+ var path=$"/api/patients/{p.PatientId}/overview?from=2026-09-01&to=2026-09-30";var first=fixture.Client.GetAsync(path);await held.Task.WaitAsync(TimeSpan.FromSeconds(10));
+ using var second=await fixture.Client.GetAsync(path);Assert.Equal(HttpStatusCode.ServiceUnavailable,second.StatusCode);Assert.NotNull(second.Headers.RetryAfter);
+ using var guidance=await fixture.RawClient.GetAsync("/api/measurement-guidance");Assert.Equal(HttpStatusCode.OK,guidance.StatusCode);
+ release.SetResult();using var completed=await first;Assert.Equal(HttpStatusCode.OK,completed.StatusCode);
+ }
+ finally{release.TrySetResult();fixture.ConfigureServices=null;fixture.AdditionalGatewayConfiguration.Remove("Resources:MaxConcurrentAssessments");await fixture.RestartHostsAsync();}
+ }
+ private sealed class PausedProfile(ProfileQueries inner,Func pause) : ProfileQueries
+ {
+ public Task ResolveAccountAsync(string a,CancellationToken ct)=>inner.ResolveAccountAsync(a,ct);
+ public async Task GetAsync(AuthorizedPatientContext scope,CancellationToken ct){var p=await inner.GetAsync(scope,ct);await pause();return p;}
+ }
+ [Fact]
+ public async Task Remote_connection_without_hostname_verified_tls_is_rejected_before_start()
+ {
+ fixture.AdditionalGatewayConfiguration["Database:Remote"]="true";
+ try
+ {
+ var e=await Assert.ThrowsAsync(()=>fixture.RestartHostsAsync());Assert.Contains("verified TLS",e.Message);
+ }
+ finally{fixture.AdditionalGatewayConfiguration.Remove("Database:Remote");await fixture.RestartHostsAsync();}
+ }
+}