Implement owned Profile schema and atomic authorized lifecycle

This commit is contained in:
Steffen committed 2026-10-14 11:37:12 +02:00
1 parent 523cfbf42e
commit bfe6ebf5af
24 files changed
+3056 -3

No files matched your search

@@ -0,0 +1,99 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class CreatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
{
// This HTTP contract is independent of the service's implementation DTOs.
public sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
[Fact]
public async Task Valid_profile_is_assigned_an_identifier_and_can_be_retrieved_after_restart()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "steffen@example.test"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var created = await response.Content.ReadFromJsonAsync<Profile>();
Assert.NotNull(created);
Assert.NotEqual(Guid.Empty, created.PatientId);
Assert.Equal("Steffen Example", created.Name);
Assert.Equal(new DateOnly(1980, 1, 1), created.DateOfBirth);
Assert.Equal("steffen@example.test", created.ContactInfo);
Assert.Equal($"/api/patients/{created.PatientId}", response.Headers.Location!.ToString());
await fixture.RestartHostsAsync();
using var retrieved = await fixture.Client.GetAsync(response.Headers.Location);
Assert.Equal(HttpStatusCode.OK, retrieved.StatusCode);
Assert.Equal(created, await retrieved.Content.ReadFromJsonAsync<Profile>());
await using var db = fixture.CreateDbContext();
var stored = await db.Patients.SingleAsync(p => p.PatientId == created.PatientId);
Assert.Equal(created.Name, stored.Name);
Assert.Equal(created.DateOfBirth, stored.DateOfBirth);
Assert.Equal(created.ContactInfo, stored.ContactInfo);
Assert.NotEqual(default, stored.CreatedAt);
Assert.Equal(stored.CreatedAt, stored.UpdatedAt);
}
[Theory]
[InlineData("{\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":null,\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":\"\",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":\" \",\"dateOfBirth\":\"1980-01-01\"}", "Name")]
[InlineData("{\"name\":\"Steffen Example\"}", "DateOfBirth")]
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":null}", "DateOfBirth")]
public async Task Missing_required_information_is_rejected_without_persisting(string json, string field)
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PostAsync("/api/patients", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.True(problem.RootElement.GetProperty("errors").TryGetProperty(field, out _));
Assert.Equal(countBefore, await db.Patients.CountAsync());
}
[Theory]
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"invalid\"}")]
[InlineData("{\"name\":\"Steffen Example\",\"dateOfBirth\":\"1980-02-30\"}")]
[InlineData("{")]
public async Task Malformed_information_is_rejected(string json)
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await fixture.Client.PostAsync("/api/patients", content);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(countBefore, await db.Patients.CountAsync());
}
[Fact]
public async Task Separate_creations_have_distinct_identifiers_and_contact_information_is_optional()
{
var request = new { name = "Steffen Example", dateOfBirth = "1980-01-01" };
using var first = await fixture.Client.PostAsJsonAsync("/api/patients", request);
using var second = await fixture.Client.PostAsJsonAsync("/api/patients", request);
Assert.Equal(HttpStatusCode.Created, first.StatusCode);
Assert.Equal(HttpStatusCode.Created, second.StatusCode);
var firstProfile = await first.Content.ReadFromJsonAsync<Profile>();
var secondProfile = await second.Content.ReadFromJsonAsync<Profile>();
Assert.NotEqual(firstProfile!.PatientId, secondProfile!.PatientId);
Assert.Null(firstProfile.ContactInfo);
Assert.Equal(firstProfile, await fixture.Client.GetFromJsonAsync<Profile>(first.Headers.Location));
}
[Fact]
public async Task Unknown_identifier_returns_not_found()
{
using var response = await fixture.Client.GetAsync($"/api/patients/{Guid.NewGuid()}");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
@@ -0,0 +1,65 @@
using System.Net;
using HealthApp.Infrastructure;
using HealthApp.Profile.Persistence;
using HealthApp.TestSupport;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public class PatientApiFixture : IAsyncLifetime
{
private readonly string databaseName="architecture_b_"+Guid.NewGuid().ToString("N");
private readonly string runtimeRole="b_runtime_"+Guid.NewGuid().ToString("N");
private string admin="";
private WebApplicationFactory<HealthApp.Program>? host;
public string ConnectionString {get;private set;}="";
public string RuntimeConnectionString {get;private set;}="";
public HttpClient Client {get;private set;}=null!;
public HttpClient RawClient {get;private set;}=null!;
public AuthenticatedTestClient Authentication {get;}=new();
public Dictionary<string,string?> AdditionalGatewayConfiguration {get;}=new();
public async Task InitializeAsync()
{
admin=Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION")??throw new InvalidOperationException("TEST_POSTGRES_CONNECTION required.");
await using var c=new NpgsqlConnection(admin);await c.OpenAsync();
await new NpgsqlCommand($"CREATE DATABASE {databaseName}; CREATE ROLE {runtimeRole} LOGIN PASSWORD 'test-runtime-only';",c).ExecuteNonQueryAsync();
ConnectionString=new NpgsqlConnectionStringBuilder(admin){Database=databaseName,SearchPath="profile,observations"}.ConnectionString;
await using var db=new NpgsqlConnection(ConnectionString);await db.OpenAsync();
var root=FindRoot();
foreach(var _ in new[]{0,1})
foreach(var script in Directory.GetFiles(Path.Combine(root,"src/Modules/Profile/Migrations"),"*.sql").Order())
await new NpgsqlCommand(await File.ReadAllTextAsync(script),db).ExecuteNonQueryAsync();
await new NpgsqlCommand($"REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT CONNECT ON DATABASE {databaseName} TO {runtimeRole}; GRANT USAGE ON SCHEMA profile TO {runtimeRole}; GRANT SELECT,INSERT,UPDATE ON profile.patient TO {runtimeRole}; GRANT SELECT ON profile.schema_version TO {runtimeRole};",db).ExecuteNonQueryAsync();
RuntimeConnectionString=new NpgsqlConnectionStringBuilder(ConnectionString){Username=runtimeRole,Password="test-runtime-only"}.ConnectionString;
Start();
}
public static string FindRoot()
{
var d=new DirectoryInfo(AppContext.BaseDirectory);
while(d is not null && !File.Exists(Path.Combine(d.FullName,"HealthApp.slnx")))d=d.Parent;
return d?.FullName??throw new InvalidOperationException("root missing");
}
internal PatientDbContext CreateDbContext()=>new(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(ConnectionString).Options);
private void Start()
{
host=new WebApplicationFactory<HealthApp.Program>().WithWebHostBuilder(b=>{
b.UseEnvironment("Development");b.ConfigureKestrel(k=>k.Listen(IPAddress.Loopback,0));
b.ConfigureAppConfiguration((_,c)=>c.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(AdditionalGatewayConfiguration).AddInMemoryCollection(new Dictionary<string,string?>{["ConnectionStrings:HealthDatabase"]=RuntimeConnectionString}));
b.ConfigureServices(s=>s.PostConfigure<BearerTokenOptions>("Bearer",o=>o.TimeProvider=Authentication.Clock));
});
host.UseKestrel(0);RawClient=host.CreateClient();Client=Authentication.Wrap(RawClient);
}
public async Task RestartHostsAsync(){Client.Dispose();RawClient.Dispose();if(host is not null)await host.DisposeAsync();Start();}
public async Task DisposeAsync()
{
Client?.Dispose();RawClient?.Dispose();if(host is not null)await host.DisposeAsync();
NpgsqlConnection.ClearAllPools();
if(admin.Length>0){await using var c=new NpgsqlConnection(admin);await c.OpenAsync();await new NpgsqlCommand($"DROP DATABASE IF EXISTS {databaseName} WITH(FORCE); DROP ROLE IF EXISTS {runtimeRole};",c).ExecuteNonQueryAsync();}
if(Directory.Exists(Authentication.KeyDirectory))Directory.Delete(Authentication.KeyDirectory,true);
}
}
@@ -0,0 +1,32 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using PatientProfile.AcceptanceTests;
using Xunit;
namespace HealthApp.AcceptanceTests;
public sealed class ProfileLifecycleTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
{
[Fact]
public async Task Concurrent_creation_lost_response_and_restart_preserve_one_accessible_profile()
{
var token=await AuthenticatedTestClient.LoginAsync(fixture.RawClient,"test-200");
async Task<HttpResponseMessage> Create(){using var r=new HttpRequestMessage(HttpMethod.Post,"/api/patients"){Content=JsonContent.Create(new{name="Concurrent",dateOfBirth="1980-01-01"})};r.Headers.Authorization=new AuthenticationHeaderValue("Bearer",token);return await fixture.RawClient.SendAsync(r);}
var responses=await Task.WhenAll(Create(),Create());
Assert.Single(responses,r=>r.StatusCode==HttpStatusCode.Created);Assert.Single(responses,r=>r.StatusCode==HttpStatusCode.Conflict);
using var retry=await Create();Assert.Equal(HttpStatusCode.Conflict,retry.StatusCode);
await using(var db=fixture.CreateDbContext()){Assert.Equal(1,await db.Patients.CountAsync(p=>p.AccountId=="test-200"));}
await fixture.RestartHostsAsync();using var read=new HttpRequestMessage(HttpMethod.Get,"/api/patients/me");read.Headers.Authorization=new AuthenticationHeaderValue("Bearer",token);
using var found=await fixture.RawClient.SendAsync(read);Assert.Equal(HttpStatusCode.OK,found.StatusCode);
foreach(var response in responses)response.Dispose();
}
[Fact]
public async Task Runtime_role_cannot_create_or_drop_health_objects()
{
await using var c=new NpgsqlConnection(fixture.RuntimeConnectionString);await c.OpenAsync();
var e=await Assert.ThrowsAsync<PostgresException>(()=>new NpgsqlCommand("CREATE TABLE profile.forbidden(id integer)",c).ExecuteNonQueryAsync());Assert.Equal("42501",e.SqlState);
e=await Assert.ThrowsAsync<PostgresException>(()=>new NpgsqlCommand("DROP TABLE profile.patient",c).ExecuteNonQueryAsync());Assert.Equal("42501",e.SqlState);
}
}
@@ -0,0 +1,71 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class UpdatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
{
private sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
[Fact]
public async Task Updated_profile_preserves_identity_and_date_of_birth_and_survives_restart()
{
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
});
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
var path = $"/api/patients/{created.PatientId}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name = "Steffen Updated", contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var expected = created with { Name = "Steffen Updated", ContactInfo = "new@example.test" };
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Profile>());
await fixture.RestartHostsAsync();
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Profile>(path));
}
[Fact]
public async Task Updating_a_missing_patient_is_rejected_without_creating_a_profile()
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
var path = $"/api/patients/{Guid.NewGuid()}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name = "Steffen Example", contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(countBefore, await db.Patients.CountAsync());
using var retrieval = await fixture.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task Invalid_name_is_rejected_without_changing_the_profile(string? name)
{
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
});
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
var path = $"/api/patients/{created.PatientId}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name, contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(created, await fixture.Client.GetFromJsonAsync<Profile>(path));
}
}