diff --git a/HealthApp.slnx b/HealthApp.slnx
index a31f78e..aa5aa84 100644
--- a/HealthApp.slnx
+++ b/HealthApp.slnx
@@ -1 +1 @@
-
+
diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_33_57.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_33_57.trx
new file mode 100644
index 0000000..4729f0f
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_33_57.trx
@@ -0,0 +1,1219 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ [xUnit.net 00:00:01.28] PatientProfile.AcceptanceTests.CreatePatientTests.Valid_profile_is_assigned_an_identifier_and_can_be_retrieved_after_restart [FAIL]
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_35_56.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_35_56.trx
new file mode 100644
index 0000000..c36c01d
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_11_35_56.trx
@@ -0,0 +1,1326 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/implementation-log.md b/ImplementationPlan/implementation-log.md
index 7e403ec..c0a3e42 100644
--- a/ImplementationPlan/implementation-log.md
+++ b/ImplementationPlan/implementation-log.md
@@ -27,3 +27,7 @@ Read authoritative approval completely. Q1–Q5 resolved; Q5 overrides Ubuntu-on
### Stage 1 checkpoint — passed
Single ASP.NET host, Contracts and Guidance projects; framework login/accounts/assignments and identical guidance content relocated. No business HTTP clients, service-key authentication or extra listeners. Original guidance suite: only host namespace changed; functional assertions unchanged, existing upstream traps still prove zero calls. Added framework login/generic failure/no-store/service-key rejection check. 10/10 cases passed; TRX `stage1-trx` records initial configuration timing failure followed by successful correction. Commit Stage 0: `cee98e7`.
+
+### Stage 2 — Profile checkpoint
+
+Profile facade/owned schema/immutable DTOs; account unique/non-null, durable atomic insert and locked updates. Shared request transaction uses repeatable-read for reads and read-committed for locked writes. Runtime DB role restricted to DML, no runtime migration. Module-owned versioned SQL migration (applied twice) implements schema lifecycle; EF Core retains data access. Original create/update tests copied with namespace adaptation only; relative Location regression fixed in production controller, not assertions. Added concurrent create/retry/restart/persistent-ticket and runtime DDL-denial tests. 29/29 cases passed. Remaining all-endpoint authorization and Observation schema checks proceed with Stage 3. Stage 1 commit `523cfbf`.
diff --git a/src/HealthApp.Contracts/AuthorizedPatientContext.cs b/src/HealthApp.Contracts/AuthorizedPatientContext.cs
new file mode 100644
index 0000000..8c44d35
--- /dev/null
+++ b/src/HealthApp.Contracts/AuthorizedPatientContext.cs
@@ -0,0 +1,22 @@
+using System.Runtime.CompilerServices;
+[assembly:InternalsVisibleTo("HealthApp")]
+namespace HealthApp.Contracts;
+// Only the API/access assembly issues this request-local capability after policy checks.
+public sealed class AuthorizedPatientContext
+{
+ internal AuthorizedPatientContext(Guid patientId, bool canWrite){PatientId=patientId;CanWrite=canWrite;}
+ public Guid PatientId {get;}
+ public bool CanWrite {get;}
+ public void RequireWrite(){if(!CanWrite)throw new UnauthorizedAccessException("Read-only scope.");}
+}
+public interface ProfileQueries
+{
+ Task ResolveAccountAsync(string accountId,CancellationToken ct);
+ Task GetAsync(AuthorizedPatientContext scope,CancellationToken ct);
+}
+public interface ProfileCommands
+{
+ Task CreateAsync(string trustedAccountId,CreatePatientRequest request,CancellationToken ct);
+ Task UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest request,CancellationToken ct);
+}
+public sealed class ProfileAlreadyExistsException : Exception;
diff --git a/src/HealthApp.Contracts/CreatePatientRequest.cs b/src/HealthApp.Contracts/CreatePatientRequest.cs
new file mode 100644
index 0000000..9b106b8
--- /dev/null
+++ b/src/HealthApp.Contracts/CreatePatientRequest.cs
@@ -0,0 +1,14 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace HealthApp.Contracts;
+
+public sealed record CreatePatientRequest
+{
+ [Required]
+ public string? Name { get; init; }
+
+ [Required]
+ public DateOnly? DateOfBirth { get; init; }
+
+ public string? ContactInfo { get; init; }
+}
diff --git a/src/HealthApp.Contracts/PatientDto.cs b/src/HealthApp.Contracts/PatientDto.cs
new file mode 100644
index 0000000..cc25fce
--- /dev/null
+++ b/src/HealthApp.Contracts/PatientDto.cs
@@ -0,0 +1,3 @@
+namespace HealthApp.Contracts;
+
+public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
diff --git a/src/HealthApp.Contracts/UpdatePatientRequest.cs b/src/HealthApp.Contracts/UpdatePatientRequest.cs
new file mode 100644
index 0000000..8e5d55c
--- /dev/null
+++ b/src/HealthApp.Contracts/UpdatePatientRequest.cs
@@ -0,0 +1,11 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace HealthApp.Contracts;
+
+public sealed record UpdatePatientRequest
+{
+ [Required]
+ public string? Name { get; init; }
+
+ public string? ContactInfo { get; init; }
+}
diff --git a/src/HealthApp.Infrastructure/HealthApp.Infrastructure.csproj b/src/HealthApp.Infrastructure/HealthApp.Infrastructure.csproj
new file mode 100644
index 0000000..f134f79
--- /dev/null
+++ b/src/HealthApp.Infrastructure/HealthApp.Infrastructure.csproj
@@ -0,0 +1,4 @@
+
+net10.0enableenable
+
+
diff --git a/src/HealthApp.Infrastructure/RequestTransaction.cs b/src/HealthApp.Infrastructure/RequestTransaction.cs
new file mode 100644
index 0000000..c77fe62
--- /dev/null
+++ b/src/HealthApp.Infrastructure/RequestTransaction.cs
@@ -0,0 +1,34 @@
+using System.Data;
+using Microsoft.EntityFrameworkCore;
+using Npgsql;
+namespace HealthApp.Infrastructure;
+// Coordinates mechanics only; it has no health table/query or access-policy knowledge.
+public sealed class RequestTransaction(NpgsqlDataSource source) : IAsyncDisposable
+{
+ public NpgsqlConnection? Connection {get;private set;}
+ public NpgsqlTransaction? Transaction {get;private set;}
+ public bool Active=>Transaction is not null;
+ public async Task BeginAsync(bool write,CancellationToken ct)
+ {
+ if(Active)return;
+ Connection=await source.OpenConnectionAsync(ct);
+ Transaction=await Connection.BeginTransactionAsync(write?IsolationLevel.ReadCommitted:IsolationLevel.RepeatableRead,ct);
+ }
+ public async Task EnlistAsync(DbContext context,CancellationToken ct)
+ {
+ if(Transaction is null || Connection is null)throw new InvalidOperationException("No request transaction.");
+ if(context.Database.GetDbConnection()!=Connection)context.Database.SetDbConnection(Connection,false);
+ await context.Database.UseTransactionAsync(Transaction,ct);
+ }
+ public async Task FinishAsync(CancellationToken ct)
+ {
+ if(Transaction is null)return;
+ await Transaction.CommitAsync(ct);await Transaction.DisposeAsync();Transaction=null;
+ await Connection!.DisposeAsync();Connection=null;
+ }
+ public async ValueTask DisposeAsync()
+ {
+ if(Transaction is not null)await Transaction.DisposeAsync();
+ if(Connection is not null)await Connection.DisposeAsync();
+ }
+}
diff --git a/src/HealthApp/Controllers/PatientController.cs b/src/HealthApp/Controllers/PatientController.cs
new file mode 100644
index 0000000..d1a3dc7
--- /dev/null
+++ b/src/HealthApp/Controllers/PatientController.cs
@@ -0,0 +1,29 @@
+using System.Security.Claims;
+using HealthApp.Contracts;
+using HealthApp.Infrastructure;
+using HealthApp.Security;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+namespace HealthApp.Controllers;
+[ApiController,Route("api/patients")]
+public sealed class PatientController(ProfileQueries queries,ProfileCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
+{
+ [HttpPost,Authorize(Policy="Patient")]
+ public async Task Create(CreatePatientRequest r,CancellationToken ct)
+ {
+ try{var p=await commands.CreateAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!,r,ct);await tx.FinishAsync(ct);return Created($"/api/patients/{p.PatientId}",p);}
+ catch(ProfileAlreadyExistsException){return Conflict(new{title="A profile already exists for this account."});}
+ }
+ [HttpGet("me"),Authorize(Policy="Patient")]
+ public async Task Me(CancellationToken ct)
+ {
+ var id=await queries.ResolveAccountAsync(User.FindFirstValue(ClaimTypes.NameIdentifier)!,ct);if(id is null)return NotFound();
+ var scope=await access.AuthorizeAsync(User,id.Value,false,ct);var p=await queries.GetAsync(scope!,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);
+ }
+ [HttpGet("{patientId:guid}")]
+ public async Task Get(Guid patientId,CancellationToken ct)
+ {var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return NotFound();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
+ [HttpPut("{patientId:guid}"),Authorize(Policy="Patient")]
+ public async Task Update(Guid patientId,UpdatePatientRequest r,CancellationToken ct)
+ {var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return NotFound();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
+}
diff --git a/src/HealthApp/HealthApp.csproj b/src/HealthApp/HealthApp.csproj
index 153b747..0373287 100644
--- a/src/HealthApp/HealthApp.csproj
+++ b/src/HealthApp/HealthApp.csproj
@@ -1,4 +1,4 @@
net10.0enableenable
-
+
diff --git a/src/HealthApp/Program.cs b/src/HealthApp/Program.cs
index f6c5a88..4e26651 100644
--- a/src/HealthApp/Program.cs
+++ b/src/HealthApp/Program.cs
@@ -1,4 +1,7 @@
using HealthApp.Guidance;
+using HealthApp.Infrastructure;
+using HealthApp.Profile;
+using Npgsql;
using HealthApp.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
@@ -14,6 +17,14 @@ public class Program
builder.Services.AddSingleton();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
+ builder.Services.AddSingleton(sp=> {
+ var c=sp.GetRequiredService();
+ 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)};
+ return NpgsqlDataSource.Create(options.ConnectionString);
+ });
+ builder.Services.AddScoped();builder.Services.AddProfile();builder.Services.AddScoped();
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
builder.Services.AddOptions().Configure((o,c,l)=> {
var keys=c["Authentication:KeyDirectory"];
@@ -37,7 +48,15 @@ public class Program
if(!ctx.Request.Path.StartsWithSegments("/api/measurement-guidance"))ctx.Response.Headers.CacheControl="no-store";
await next(ctx);
});
- app.UseAuthentication();app.UseAuthorization();app.MapControllers();
+ 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();
+ try{await tx.BeginAsync(ctx.Request.Method!="GET",ctx.RequestAborted);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();
await app.RunAsync();
}
}
diff --git a/src/HealthApp/Security/AccessPolicy.cs b/src/HealthApp/Security/AccessPolicy.cs
new file mode 100644
index 0000000..81e6791
--- /dev/null
+++ b/src/HealthApp/Security/AccessPolicy.cs
@@ -0,0 +1,12 @@
+using System.Security.Claims;
+using HealthApp.Contracts;
+namespace HealthApp.Security;
+public sealed class AccessPolicy(ProfileQueries profiles,ProfessionalAssignments assignments)
+{
+ public async Task AuthorizeAsync(ClaimsPrincipal user,Guid actualPatient,bool write,CancellationToken ct)
+ {
+ var account=user.FindFirstValue(ClaimTypes.NameIdentifier)!;
+ bool allowed=user.IsInRole("HealthcareProfessional") ? !write&&assignments.IsAssigned(account,actualPatient) : user.IsInRole("Patient")&&await profiles.ResolveAccountAsync(account,ct)==actualPatient;
+ return allowed?new AuthorizedPatientContext(actualPatient,write):null;
+ }
+}
diff --git a/src/Modules/Profile/AssemblyInfo.cs b/src/Modules/Profile/AssemblyInfo.cs
new file mode 100644
index 0000000..f136d84
--- /dev/null
+++ b/src/Modules/Profile/AssemblyInfo.cs
@@ -0,0 +1,2 @@
+using System.Runtime.CompilerServices;
+[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
diff --git a/src/Modules/Profile/Domain/Patient.cs b/src/Modules/Profile/Domain/Patient.cs
new file mode 100644
index 0000000..6e9743c
--- /dev/null
+++ b/src/Modules/Profile/Domain/Patient.cs
@@ -0,0 +1,12 @@
+namespace HealthApp.Profile.Domain;
+
+internal sealed class Patient
+{
+ public string? AccountId { get; set; }
+ public Guid PatientId { get; set; }
+ public string Name { get; set; } = "";
+ public DateOnly DateOfBirth { get; set; }
+ public string? ContactInfo { get; set; }
+ public DateTime CreatedAt { get; set; }
+ public DateTime UpdatedAt { get; set; }
+}
diff --git a/src/Modules/Profile/Migrations/001-profile.sql b/src/Modules/Profile/Migrations/001-profile.sql
new file mode 100644
index 0000000..d8f253b
--- /dev/null
+++ b/src/Modules/Profile/Migrations/001-profile.sql
@@ -0,0 +1,7 @@
+CREATE SCHEMA IF NOT EXISTS profile;
+CREATE TABLE IF NOT EXISTS profile.schema_version(version integer PRIMARY KEY);
+CREATE TABLE IF NOT EXISTS profile.patient (
+ patient_id uuid PRIMARY KEY, account_id text NOT NULL, name varchar NOT NULL,
+ date_of_birth date NOT NULL,contact_info varchar,created_at timestamp without time zone NOT NULL,updated_at timestamp without time zone NOT NULL);
+CREATE UNIQUE INDEX IF NOT EXISTS "IX_patient_account_id" ON profile.patient(account_id);
+INSERT INTO profile.schema_version VALUES(1) ON CONFLICT DO NOTHING;
diff --git a/src/Modules/Profile/Persistence/PatientDbContext.cs b/src/Modules/Profile/Persistence/PatientDbContext.cs
new file mode 100644
index 0000000..8a2bb64
--- /dev/null
+++ b/src/Modules/Profile/Persistence/PatientDbContext.cs
@@ -0,0 +1,24 @@
+using Microsoft.EntityFrameworkCore;
+using HealthApp.Profile.Domain;
+
+namespace HealthApp.Profile.Persistence;
+
+internal sealed class PatientDbContext(DbContextOptions options) : DbContext(options)
+{
+ public DbSet Patients => Set();
+
+ protected override void OnModelCreating(ModelBuilder modelBuilder)
+ {
+ var patient = modelBuilder.Entity();
+ patient.ToTable("patient", "profile");
+ patient.HasKey(p => p.PatientId);
+ patient.Property(p => p.AccountId).HasColumnName("account_id").IsRequired();
+ patient.HasIndex(p => p.AccountId).IsUnique();
+ patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever();
+ patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired();
+ patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date");
+ patient.Property(p => p.ContactInfo).HasColumnName("contact_info").HasColumnType("character varying");
+ patient.Property(p => p.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
+ patient.Property(p => p.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
+ }
+}
diff --git a/src/Modules/Profile/Profile.csproj b/src/Modules/Profile/Profile.csproj
new file mode 100644
index 0000000..b205ee6
--- /dev/null
+++ b/src/Modules/Profile/Profile.csproj
@@ -0,0 +1,4 @@
+
+net10.0enableenable
+
+
diff --git a/src/Modules/Profile/ProfileFacade.cs b/src/Modules/Profile/ProfileFacade.cs
new file mode 100644
index 0000000..fe554bf
--- /dev/null
+++ b/src/Modules/Profile/ProfileFacade.cs
@@ -0,0 +1,40 @@
+using System.ComponentModel.DataAnnotations;
+using HealthApp.Contracts;
+using HealthApp.Infrastructure;
+using HealthApp.Profile.Domain;
+using HealthApp.Profile.Persistence;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Npgsql;
+namespace HealthApp.Profile;
+internal sealed class ProfileFacade(PatientDbContext db,RequestTransaction tx) : ProfileQueries,ProfileCommands
+{
+ public async Task ResolveAccountAsync(string id,CancellationToken ct)
+ {await tx.EnlistAsync(db,ct);return await db.Patients.AsNoTracking().Where(p=>p.AccountId==id).Select(p=>(Guid?)p.PatientId).SingleOrDefaultAsync(ct);}
+ public async Task GetAsync(AuthorizedPatientContext scope,CancellationToken ct)
+ {await tx.EnlistAsync(db,ct);var p=await db.Patients.AsNoTracking().SingleOrDefaultAsync(p=>p.PatientId==scope.PatientId,ct);return p is null?null:Dto(p);}
+ public async Task CreateAsync(string trustedAccountId,CreatePatientRequest r,CancellationToken ct)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId);Validator.ValidateObject(r,new ValidationContext(r),true);
+ await tx.EnlistAsync(db,ct);if(await db.Patients.AnyAsync(p=>p.AccountId==trustedAccountId,ct))throw new ProfileAlreadyExistsException();
+ var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
+ var p=new Patient{PatientId=Guid.NewGuid(),AccountId=trustedAccountId,Name=r.Name!,DateOfBirth=r.DateOfBirth!.Value,ContactInfo=r.ContactInfo,CreatedAt=now,UpdatedAt=now};db.Patients.Add(p);
+ try{await db.SaveChangesAsync(ct);}catch(DbUpdateException e) when(e.InnerException is PostgresException {SqlState:"23505",ConstraintName:"IX_patient_account_id"}){throw new ProfileAlreadyExistsException();}
+ return Dto(p);
+ }
+ public async Task UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest r,CancellationToken ct)
+ {
+ scope.RequireWrite();Validator.ValidateObject(r,new ValidationContext(r),true);await tx.EnlistAsync(db,ct);
+ var p=await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
+ if(p is null)return null;p.Name=r.Name!;p.ContactInfo=r.ContactInfo;p.UpdatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);await db.SaveChangesAsync(ct);return Dto(p);
+ }
+ private static PatientDto Dto(Patient p)=>new(p.PatientId,p.Name,p.DateOfBirth,p.ContactInfo);
+}
+public static class ProfileModule
+{
+ public static IServiceCollection AddProfile(this IServiceCollection services)
+ {
+ services.AddScoped(sp=>new PatientDbContext(new DbContextOptionsBuilder().UseNpgsql(sp.GetRequiredService().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
+ services.AddScoped();services.AddScoped(sp=>sp.GetRequiredService());services.AddScoped(sp=>sp.GetRequiredService());return services;
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/CreatePatientTests.cs b/tests/HealthApp.AcceptanceTests/CreatePatientTests.cs
new file mode 100644
index 0000000..ae804c1
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/CreatePatientTests.cs
@@ -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
+{
+ // 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();
+ 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());
+
+ 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();
+ var secondProfile = await second.Content.ReadFromJsonAsync();
+ Assert.NotEqual(firstProfile!.PatientId, secondProfile!.PatientId);
+ Assert.Null(firstProfile.ContactInfo);
+ Assert.Equal(firstProfile, await fixture.Client.GetFromJsonAsync(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);
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs b/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs
new file mode 100644
index 0000000..c630e32
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs
@@ -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? 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 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().UseNpgsql(ConnectionString).Options);
+ private void Start()
+ {
+ host=new WebApplicationFactory().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{["ConnectionStrings:HealthDatabase"]=RuntimeConnectionString}));
+ b.ConfigureServices(s=>s.PostConfigure("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);
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/ProfileLifecycleTests.cs b/tests/HealthApp.AcceptanceTests/ProfileLifecycleTests.cs
new file mode 100644
index 0000000..d9309ab
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/ProfileLifecycleTests.cs
@@ -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
+{
+ [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 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(()=>new NpgsqlCommand("CREATE TABLE profile.forbidden(id integer)",c).ExecuteNonQueryAsync());Assert.Equal("42501",e.SqlState);
+ e=await Assert.ThrowsAsync(()=>new NpgsqlCommand("DROP TABLE profile.patient",c).ExecuteNonQueryAsync());Assert.Equal("42501",e.SqlState);
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/UpdatePatientTests.cs b/tests/HealthApp.AcceptanceTests/UpdatePatientTests.cs
new file mode 100644
index 0000000..60713a8
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/UpdatePatientTests.cs
@@ -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
+{
+ 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())!;
+ 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());
+
+ await fixture.RestartHostsAsync();
+ Assert.Equal(expected, await fixture.Client.GetFromJsonAsync(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())!;
+ 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(path));
+ }
+}