Implement owned Profile schema and atomic authorized lifecycle
This commit is contained in:
1 parent
523cfbf42e
commit
bfe6ebf5af
24 files changed
+3056
-3
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
<Solution><Folder Name="/src/"><Project Path="src/HealthApp/HealthApp.csproj" /><Project Path="src/HealthApp.Contracts/HealthApp.Contracts.csproj" /><Project Path="src/Modules/Guidance/Guidance.csproj" /></Folder><Folder Name="/tests/"><Project Path="tests/HealthApp.AcceptanceTests/HealthApp.AcceptanceTests.csproj" /></Folder></Solution>
|
||||
<Solution><Folder Name="/src/"><Project Path="src/HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><Project Path="src/Modules/Profile/Profile.csproj"/><Project Path="src/HealthApp/HealthApp.csproj" /><Project Path="src/HealthApp.Contracts/HealthApp.Contracts.csproj" /><Project Path="src/Modules/Guidance/Guidance.csproj" /></Folder><Folder Name="/tests/"><Project Path="tests/HealthApp.AcceptanceTests/HealthApp.AcceptanceTests.csproj" /></Folder></Solution>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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`.
|
||||
@@ -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<Guid?> ResolveAccountAsync(string accountId,CancellationToken ct);
|
||||
Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct);
|
||||
}
|
||||
public interface ProfileCommands
|
||||
{
|
||||
Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest request,CancellationToken ct);
|
||||
Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest request,CancellationToken ct);
|
||||
}
|
||||
public sealed class ProfileAlreadyExistsException : Exception;
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3"/><PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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);}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /></ItemGroup>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -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<PrototypeAccounts>();
|
||||
builder.Services.AddSingleton<ProfessionalAssignments>();
|
||||
builder.Services.AddSingleton<GuidanceQueries>();
|
||||
builder.Services.AddSingleton(sp=> {
|
||||
var c=sp.GetRequiredService<IConfiguration>();
|
||||
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<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||
builder.Services.AddOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((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<Microsoft.AspNetCore.Authorization.IAllowAnonymous>() 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<RequestTransaction>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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<AuthorizedPatientContext?> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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;
|
||||
@@ -0,0 +1,24 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using HealthApp.Profile.Domain;
|
||||
|
||||
namespace HealthApp.Profile.Persistence;
|
||||
|
||||
internal sealed class PatientDbContext(DbContextOptions<PatientDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<Patient> Patients => Set<Patient>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var patient = modelBuilder.Entity<Patient>();
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -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<Guid?> 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<PatientDto?> 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<PatientDto> 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<PatientDto?> 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<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
|
||||
services.AddScoped<ProfileFacade>();services.AddScoped<ProfileQueries>(sp=>sp.GetRequiredService<ProfileFacade>());services.AddScoped<ProfileCommands>(sp=>sp.GetRequiredService<ProfileFacade>());return services;
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user