Enforce bounded operations deadlines and deployment readiness

This commit is contained in:
Steffen committed 2026-10-14 12:16:08 +02:00
1 parent cc7f87105d
commit f451b55de1
11 files changed
+5912 -22

No files matched your search

@@ -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<HealthApp.Program>().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<AuthenticationSchemeOptions,ReplacementHandler>("Replacement",null);
services.PostConfigure<AuthenticationOptions>(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<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> 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)));
}
}
@@ -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);}
}
}
@@ -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<ObservationDbContext>().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();
}
}
}
@@ -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<ObservationApiFixture>
{
[Fact]
public async Task Readiness_uses_configured_schemas_and_guidance_remains_public_during_database_outage()
{
var token=await AuthenticatedTestClient.LoginAsync(fixture.RawClient);
async Task<HttpResponseMessage> 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<PatientDto>())!;
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<PatientDto>($"/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<PatientDto>())!;
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<ProfileQueries>(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<Task> pause) : ProfileQueries
{
public Task<Guid?> ResolveAccountAsync(string a,CancellationToken ct)=>inner.ResolveAccountAsync(a,ct);
public async Task<PatientDto?> 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<InvalidOperationException>(()=>fixture.RestartHostsAsync());Assert.Contains("verified TLS",e.Message);
}
finally{fixture.AdditionalGatewayConfiguration.Remove("Database:Remote");await fixture.RestartHostsAsync();}
}
}