diff --git a/HealthApp.slnx b/HealthApp.slnx
index db8a702..c6587c7 100644
--- a/HealthApp.slnx
+++ b/HealthApp.slnx
@@ -1 +1 @@
-
+
diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_03_58.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_03_58.trx
new file mode 100644
index 0000000..ac3121d
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_03_58.trx
@@ -0,0 +1,18873 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ [xUnit.net 00:00:03.07] Observation.AcceptanceTests.PatientAuthenticationTests.Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected [FAIL]
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_05_38.trx b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_05_38.trx
new file mode 100644
index 0000000..c6ade5c
--- /dev/null
+++ b/ImplementationPlan/evidence/b-trx/_Sil3ntDragon_2026-10-14_12_05_38.trx
@@ -0,0 +1,18516 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ImplementationPlan/implementation-log.md b/ImplementationPlan/implementation-log.md
index b4744f9..abf9703 100644
--- a/ImplementationPlan/implementation-log.md
+++ b/ImplementationPlan/implementation-log.md
@@ -39,3 +39,7 @@ Observation module owns its private EF context/entities and versioned schema SQL
### Stage 4 checkpoint — passed
SummaryPolicy, TrendPolicy, ClinicalPolicy and Guidance-owned versioned ReferenceCatalog extracted without changing formulas/rounding/thresholds/labels/explanations. Analytics captures one immutable series and releases the shared snapshot before calculation. All original numerical/trend tests retained, with shared namespaces and explicit catalog constructor injection; HTTP dependency failure expectations alone changed 502→503 under Q1. 207/207 tests passed, zero build warnings/errors. `src/TRENDS.md` preserves reproducible method details; `clinical-provenance.md` records unverified cautious inferences and narrative limits without altering outputs.
+
+### Stage 5 checkpoint — passed
+
+Overview composes typed Profile, Observation and Analytics queries; profile/latest/selected series share repeatable-read from authorization. Analytics releases capture before calculation. Deterministic interleaving commits Profile and Observation changes after Profile capture: in-flight overview stays old/coherent; next sees new values; selected query called once; transaction inactive before Analytics returns. All adopted Overview, patient and professional suites pass: 266/266 cases, zero warnings/errors. Ownership now checks route metadata before model validation to preserve denied empty-404 behaviour. Stage 4 commit `cab10c5`.
diff --git a/ImplementationPlan/test-adaptations.md b/ImplementationPlan/test-adaptations.md
index e5afd37..9c264d5 100644
--- a/ImplementationPlan/test-adaptations.md
+++ b/ImplementationPlan/test-adaptations.md
@@ -12,3 +12,11 @@ Authority: approval Q1. Unmodified originals remain under Reference/Architecture
| New concurrency checks | Hold row lock, prove both patches wait, release, verify both disjoint changes and unchanged owner/time/note; new architecture obligation |
Insight/context/trend/deletion-derived tests: service-stop helpers represent DB outage, expected 503 replaces 502; current data, no-write, no-false-insufficiency assertions unchanged. Pure calculation tests instantiate the identical mathematical implementation through its internal test-compatible entry and explicit Guidance reference catalog. No clinical assertion changed.
+
+| Additional original scenario | B replacement / preserved obligations |
+| --- | --- |
+| HealthOverviewTests.Overview_service_credential_is_restricted_to_required_reads | Sole edge rejects service-only headers with 401, replacing 403 from obsolete Service role. No protected data returned |
+| HealthOverviewTests.Unavailable_source_or_overview_is_a_failure_not_absent_insight | Each old service-stop example injects shared DB unavailability; 503 replaces 502. No false nullable-insight success |
+| PatientAuthenticationTests.Direct_services_reject_client_tokens_missing_keys_and_forged_keys / Service_credentials_are_limited_to_their_documented_read_calls | Replaced together by Sole_public_edge_accepts_client_ticket_but_service_headers_grant_no_access: valid client ticket works at sole edge, forged service headers grant nothing, internal by-account route absent. Originals remain baseline evidence. Patient/professional denial matrices unchanged |
+| PatientAuthenticationTests.Database_failure_rolls_back_profile_and_association_together | Same B-local trigger/no-row/retry assertions, search_path resolves owned Profile schema; unexpected write failure still 500 |
+| Original view/overview wire DTOs | Same JSON fields. Shared context DTO nullable annotation needs test null-forgiving operator after established setup; assertions unchanged |
diff --git a/src/HealthApp.Contracts/HealthOverviewDto.cs b/src/HealthApp.Contracts/HealthOverviewDto.cs
new file mode 100644
index 0000000..1ac7249
--- /dev/null
+++ b/src/HealthApp.Contracts/HealthOverviewDto.cs
@@ -0,0 +1,6 @@
+namespace HealthApp.Contracts;
+public sealed record HealthOverviewDto(PatientDto Patient,ObservationDto? LatestObservation,HealthInsight? Insight,DateTime PeriodStart,DateTime PeriodEnd,ContextSelection InsightSelection,int InsightContributingCount,string LatestObservationBasis,string InsightExplanation);
+public interface OverviewQueries
+{
+ Task GetAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
+}
diff --git a/src/HealthApp/Controllers/HealthOverviewController.cs b/src/HealthApp/Controllers/HealthOverviewController.cs
new file mode 100644
index 0000000..5cd14a0
--- /dev/null
+++ b/src/HealthApp/Controllers/HealthOverviewController.cs
@@ -0,0 +1,17 @@
+using HealthApp.Contracts;
+using HealthApp.Infrastructure;
+using HealthApp.Security;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.ModelBinding;
+namespace HealthApp.Controllers;
+[ApiController]
+public sealed class HealthOverviewController(OverviewQueries overview,AccessPolicy access,RequestTransaction tx) : ControllerBase
+{
+ [HttpGet("api/patients/{patientId:guid}/overview")]
+ public async Task Get(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)
+ {
+ var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null){Response.StatusCode=404;return new EmptyResult();}
+ try{var o=await overview.GetAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);return o is null?Problem(statusCode:404,title:"Patient does not exist."):Ok(o);}
+ catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
+ }
+}
diff --git a/src/HealthApp/HealthApp.csproj b/src/HealthApp/HealthApp.csproj
index 48a08ab..dfb9c51 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 9660fec..e43703c 100644
--- a/src/HealthApp/Program.cs
+++ b/src/HealthApp/Program.cs
@@ -3,6 +3,7 @@ using HealthApp.Infrastructure;
using HealthApp.Profile;
using HealthApp.Observations;
using HealthApp.Analytics;
+using HealthApp.Overview;
using HealthApp.Contracts;
using Npgsql;
using HealthApp.Security;
@@ -19,7 +20,7 @@ public class Program
builder.Services.AddProblemDetails();
builder.Services.AddSingleton();
builder.Services.AddSingleton();
- builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddAnalytics();
+ builder.Services.AddSingleton();builder.Services.AddSingleton();builder.Services.AddAnalytics();builder.Services.AddOverview();
builder.Services.AddSingleton(sp=> {
var c=sp.GetRequiredService();
var text=c.GetConnectionString("HealthDatabase");
@@ -57,7 +58,19 @@ public class Program
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);}
+ try{
+ var write=ctx.Request.Method!="GET";
+ await tx.BeginAsync(write,ctx.RequestAborted);
+ Guid? actual=null;
+ if(Guid.TryParse(ctx.Request.RouteValues["patientId"]?.ToString(),out var patientId))actual=patientId;
+ else if(Guid.TryParse(ctx.Request.RouteValues["observationId"]?.ToString(),out var observationId))actual=await ctx.RequestServices.GetRequiredService().ResolveOwnerAsync(observationId,ctx.RequestAborted);
+ if(ctx.Request.RouteValues.ContainsKey("patientId") || ctx.Request.RouteValues.ContainsKey("observationId"))
+ {
+ var approved=actual is null?null:await ctx.RequestServices.GetRequiredService().AuthorizeAsync(ctx.User,actual.Value,write,ctx.RequestAborted);
+ if(approved is null){ctx.Response.StatusCode=404;return;}
+ }
+ await next(ctx);
+ }
catch(NpgsqlException){if(ctx.Response.HasStarted)ctx.Abort();else {ctx.Response.Clear();await Results.Problem(statusCode:503,title:"Health data dependency is unavailable.").ExecuteAsync(ctx);}}
});app.MapControllers();
await app.RunAsync();
diff --git a/src/Modules/Overview/Overview.csproj b/src/Modules/Overview/Overview.csproj
new file mode 100644
index 0000000..bf83c0c
--- /dev/null
+++ b/src/Modules/Overview/Overview.csproj
@@ -0,0 +1,4 @@
+
+net10.0enableenable
+
+
diff --git a/src/Modules/Overview/OverviewFacade.cs b/src/Modules/Overview/OverviewFacade.cs
new file mode 100644
index 0000000..d4350c5
--- /dev/null
+++ b/src/Modules/Overview/OverviewFacade.cs
@@ -0,0 +1,24 @@
+using System.ComponentModel.DataAnnotations;
+using HealthApp.Contracts;
+using Microsoft.Extensions.DependencyInjection;
+namespace HealthApp.Overview;
+internal sealed class OverviewFacade(ProfileQueries patients,ObservationQueries observations,AnalyticsQueries analytics) : OverviewQueries
+{
+ public async Task GetAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
+ {
+ from=MeasurementPeriod.Normalize(from);to=MeasurementPeriod.Normalize(to);MeasurementPeriod.Validate(from,to);Validator.ValidateObject(selection,new ValidationContext(selection),true);
+ var patient=await patients.GetAsync(scope,ct);if(patient is null)return null;
+ var latest=await observations.LatestAsync(scope,ct);
+ // Analytics captures the selected series once and closes the shared snapshot before calculation.
+ var insight=await analytics.InsightAsync(scope,from,to,selection,ct);
+ return new(patient,latest,insight,from,to,selection,insight?.ContributingCount??0,
+ "Latest overall observation for the patient, independent of the insight period and context selections. "+
+ "Its recorded context applies only to that observation, not to the insight's contributing observations.",
+ insight is null?"No calculated insight is available: no observations match the requested period and insight selection.":
+ "The insight uses the requested period and context selection only. "+insight.ContextExplanation);
+ }
+}
+public static class OverviewModule
+{
+ public static IServiceCollection AddOverview(this IServiceCollection services)=>services.AddScoped();
+}
diff --git a/tests/HealthApp.AcceptanceTests/HealthOverviewTests.cs b/tests/HealthApp.AcceptanceTests/HealthOverviewTests.cs
new file mode 100644
index 0000000..5bc6ebf
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/HealthOverviewTests.cs
@@ -0,0 +1,249 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using HealthApp.TestSupport;
+using HealthApp.Contracts;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class HealthOverviewTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private sealed record Recorded(Guid ObservationId);
+ private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00";
+ private static string PathFor(Guid patient, string query = Period) => $"/api/patients/{patient}/overview?{query}";
+ private async Task Patient()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new
+ { name = "Overview patient", dateOfBirth = "1980-01-01", contactInfo = "Synthetic contact" });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.PatientId;
+ }
+ private async Task Record(Guid patient, string time, int systolic = 120,
+ string? setting = "Home", string? activity = "AtRest")
+ {
+ using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new
+ {
+ measuredAt = time, systolic, diastolic = 80, pulse = 65, context = "Preserved original context", note = "Preserved note",
+ measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5,
+ bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Morning" }
+ });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.ObservationId;
+ }
+ private async Task Overview(Guid patient, string query = Period)
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(patient, query));
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!;
+ }
+
+ [Fact]
+ public async Task Overview_preserves_profile_latest_context_and_selected_insight_with_different_bases()
+ {
+ var patient = await Patient();
+ await Record(patient, "2026-09-01T08:00:00", 120);
+ await Record(patient, "2026-09-10T08:00:00", 130);
+ await Record(patient, "2026-09-01T07:59:59", 200);
+ var latest = await Record(patient, "2026-09-11T08:00:00", 210, "Clinic", "AfterActivity");
+ await Record(await Patient(), "2026-09-05T08:00:00", 250);
+ var result = await Overview(patient, Period + "&setting=Home&activityCondition=AtRest");
+ Assert.Equal(patient, result.Patient.PatientId);
+ Assert.Equal("Overview patient", result.Patient.Name);
+ Assert.Equal(new DateOnly(1980, 1, 1), result.Patient.DateOfBirth);
+ Assert.Equal("Synthetic contact", result.Patient.ContactInfo);
+ Assert.Equal(latest, result.LatestObservation!.ObservationId);
+ Assert.Equal("AfterActivity", result.LatestObservation.MeasurementContext!.ActivityCondition);
+ Assert.Equal("Clinic", result.LatestObservation.MeasurementContext!.Setting);
+ Assert.Equal("Seated", result.LatestObservation.MeasurementContext!.BodyPosition);
+ Assert.Equal("Left", result.LatestObservation.MeasurementContext!.MeasuredArm);
+ Assert.Equal("Device", result.LatestObservation.MeasurementContext!.DeviceDetails);
+ Assert.Equal("Cuff", result.LatestObservation.MeasurementContext!.CuffDetails);
+ Assert.Equal(5m, result.LatestObservation.MeasurementContext!.RestDurationMinutes);
+ Assert.Equal("Morning", result.LatestObservation.MeasurementContext!.AdditionalCircumstances);
+ Assert.Equal("Preserved original context", result.LatestObservation.Context);
+ Assert.Equal("Preserved note", result.LatestObservation.Note);
+ Assert.Equal(125m, result.Insight!.AverageSystolic);
+ Assert.Equal(2, result.InsightContributingCount);
+ Assert.Equal(result.InsightSelection, result.Insight.AppliedSelection);
+ Assert.Equal("Home", result.InsightSelection.Setting);
+ Assert.Equal("AtRest", result.InsightSelection.ActivityCondition);
+ Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart);
+ Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd);
+ Assert.Contains("independent of the insight period and context selections", result.LatestObservationBasis);
+ Assert.Contains("not to the insight", result.LatestObservationBasis);
+ using var raw = await fixture.Client.GetAsync(PathFor(patient));
+ using var json = JsonDocument.Parse(await raw.Content.ReadAsStringAsync());
+ Assert.False(json.RootElement.TryGetProperty("trend", out _));
+ }
+
+ [Fact]
+ public async Task No_observations_returns_profile_and_explicit_insight_absence()
+ {
+ var result = await Overview(await Patient());
+ Assert.NotNull(result.Patient);
+ Assert.Null(result.LatestObservation);
+ Assert.Null(result.Insight);
+ Assert.Equal(0, result.InsightContributingCount);
+ Assert.Contains("No calculated insight is available", result.InsightExplanation);
+ }
+
+ [Theory]
+ [InlineData("&setting=Clinic")]
+ [InlineData("&activityCondition=AfterActivity")]
+ [InlineData("&setting=Unknown&activityCondition=Unknown")]
+ public async Task Empty_selected_insight_preserves_profile_latest_and_applied_selection(string selection)
+ {
+ var patient = await Patient();
+ var latest = await Record(patient, "2026-09-05T08:00:00");
+ var result = await Overview(patient, Period + selection);
+ Assert.Equal(patient, result.Patient.PatientId);
+ Assert.Equal(latest, result.LatestObservation!.ObservationId);
+ Assert.Null(result.Insight);
+ Assert.Equal(0, result.InsightContributingCount);
+ Assert.Contains("no observations match", result.InsightExplanation);
+ Assert.True(result.InsightSelection.Setting is not null || result.InsightSelection.ActivityCondition is not null);
+ }
+
+ [Fact]
+ public async Task Unfiltered_pooled_insight_preserves_mixed_and_unknown_context_explanations()
+ {
+ var patient = await Patient();
+ await Record(patient, "2026-09-02T08:00:00", 120);
+ await Record(patient, "2026-09-03T08:00:00", 130, "Clinic", "AfterActivity");
+ var latest = await Record(patient, "2026-09-04T08:00:00", 140, null, null);
+ var result = await Overview(patient);
+ Assert.Equal(latest, result.LatestObservation!.ObservationId);
+ Assert.Equal("Unknown", result.LatestObservation.MeasurementContext!.Setting);
+ Assert.Equal("Unknown", result.LatestObservation.MeasurementContext!.ActivityCondition);
+ Assert.Null(result.InsightSelection.Setting);
+ Assert.Null(result.InsightSelection.ActivityCondition);
+ Assert.Equal(3, result.InsightContributingCount);
+ Assert.Equal(130m, result.Insight!.AverageSystolic);
+ Assert.Contains("mixed settings or activity conditions", result.Insight.ContextExplanation);
+ Assert.Contains("unknown", result.InsightExplanation);
+ }
+
+ [Fact]
+ public async Task Equal_offset_instants_are_valid_and_single_observation_insight_is_sufficient()
+ {
+ var patient = await Patient();
+ await Record(patient, "2026-09-05T10:00:00+02:00", 121);
+ var result = await Overview(patient,
+ "from=2026-09-05T10%3A00%3A00%2B02%3A00&to=2026-09-05T08%3A00%3A00Z&setting=Home");
+ Assert.Equal(result.PeriodStart, result.PeriodEnd);
+ Assert.Equal(1, result.InsightContributingCount);
+ Assert.Equal(121m, result.Insight!.AverageSystolic);
+ }
+
+ [Fact]
+ public async Task Latest_tie_rules_and_current_corrections_deletions_and_profile_edits_survive_restart()
+ {
+ var patient = await Patient();
+ var first = await Record(patient, "2026-09-05T08:00:00", 120);
+ var second = await Record(patient, "2026-09-05T08:00:00", 130, "Clinic", "AfterActivity");
+ Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId);
+ using var patched = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}",
+ new { systolic = 140, measurementContext = new { setting = "Clinic" } });
+ Assert.Equal(HttpStatusCode.OK, patched.StatusCode);
+ Assert.Null((await Overview(patient, Period + "&setting=Home")).Insight);
+ Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId);
+ using var edited = await fixture.Client.PutAsJsonAsync($"/api/patients/{patient}",
+ new { name = "Updated overview", dateOfBirth = "1980-01-01", contactInfo = "Updated contact" });
+ Assert.Equal(HttpStatusCode.OK, edited.StatusCode);
+ using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}");
+ Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
+ await fixture.RestartHostsAsync();
+ var result = await Overview(patient);
+ Assert.Equal("Updated overview", result.Patient.Name);
+ Assert.Equal(first, result.LatestObservation!.ObservationId);
+ Assert.Equal(140m, result.Insight!.AverageSystolic);
+ Assert.Equal(1, result.InsightContributingCount);
+ }
+
+ [Theory]
+ [InlineData("from=2026-09-10&to=2026-09-01")]
+ [InlineData("from=bad&to=2026-09-10")]
+ [InlineData("from=2026-09-01&to=bad")]
+ [InlineData("from=2026-09-01")]
+ [InlineData("to=2026-09-10")]
+ [InlineData("")]
+ [InlineData(Period + "&setting=Invalid")]
+ [InlineData(Period + "&activityCondition=Invalid")]
+ public async Task Invalid_period_or_context_is_rejected_with_details(string query)
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(await Patient(), query));
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.True(problem.RootElement.TryGetProperty("errors", out _));
+ }
+
+ [Fact]
+ public async Task Assigned_missing_patient_reports_absence_without_exposing_other_patients()
+ {
+ var missing = Guid.NewGuid();
+ fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = missing.ToString();
+ await fixture.RestartHostsAsync();
+ using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(missing));
+ request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional"));
+ using var response = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ Assert.Contains("Patient does not exist", await response.Content.ReadAsStringAsync());
+ }
+
+ [Fact]
+ public async Task Overview_requires_owner_or_assigned_professional_and_blocks_direct_bypass()
+ {
+ var patient = await Patient();
+ await Record(patient, "2026-09-05T08:00:00");
+ var other = await Patient();
+ fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString();
+ await fixture.RestartHostsAsync();
+ using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient));
+ Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode);
+ foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK),
+ ("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) })
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient));
+ request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account));
+ using var response = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(status, response.StatusCode);
+ if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync());
+ }
+ using var direct = fixture.CreateDirectOverviewClient();
+ using var bypass = await direct.GetAsync(PathFor(patient));
+ Assert.Equal(HttpStatusCode.Unauthorized, bypass.StatusCode);
+ Assert.Empty(await bypass.Content.ReadAsStringAsync());
+ }
+
+ [Theory]
+ [InlineData("overview")]
+ [InlineData("trends")]
+ [InlineData("observations")]
+ public async Task Overview_service_credential_is_restricted_to_required_reads(string route)
+ {
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{await Patient()}/{route}?{Period}");
+ request.Headers.Add("X-Service-Key", fixture.Authentication.OverviewServiceKey);
+ using var response = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ [Theory]
+ [InlineData("Observation")]
+ [InlineData("Insights")]
+ [InlineData("Overview")]
+ public async Task Unavailable_source_or_overview_is_a_failure_not_absent_insight(string service)
+ {
+ var patient = await Patient();
+ if (service == "Observation") await fixture.StopObservationServiceAsync();
+ if (service == "Insights") await fixture.StopInsightsServiceAsync();
+ if (service == "Overview") await fixture.StopOverviewServiceAsync();
+ try
+ {
+ using var response = await fixture.Client.GetAsync(PathFor(patient));
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
+ }
+ finally { await fixture.RestartHostsAsync(); }
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs b/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs
index c2e04e8..1ef213a 100644
--- a/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs
+++ b/tests/HealthApp.AcceptanceTests/PatientApiFixture.cs
@@ -22,6 +22,7 @@ public class PatientApiFixture : IAsyncLifetime
public HttpClient Client {get;private set;}=null!;
public HttpClient RawClient {get;private set;}=null!;
public AuthenticatedTestClient Authentication {get;}=new();
+ public Action? ConfigureServices {get;set;}
public Dictionary AdditionalGatewayConfiguration {get;}=new();
public async Task InitializeAsync()
{
@@ -50,7 +51,7 @@ public class PatientApiFixture : IAsyncLifetime
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));
+ b.ConfigureServices(s=>{s.PostConfigure("Bearer",o=>o.TimeProvider=Authentication.Clock);ConfigureServices?.Invoke(s);});
});
host.UseKestrel(0);RawClient=host.CreateClient();Client=Authentication.Wrap(RawClient);
}
diff --git a/tests/HealthApp.AcceptanceTests/PatientAuthenticationTests.cs b/tests/HealthApp.AcceptanceTests/PatientAuthenticationTests.cs
new file mode 100644
index 0000000..4d19666
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/PatientAuthenticationTests.cs
@@ -0,0 +1,262 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using HealthApp.TestSupport;
+using Microsoft.EntityFrameworkCore;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class PatientAuthenticationTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private static int nextAccount = 150;
+ private sealed record Profile(Guid PatientId);
+ private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic);
+ private static object ProfileRequest => new { name = "Patient", dateOfBirth = "1980-01-01" };
+ private static object ObservationRequest => new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
+
+ private async Task Send(HttpMethod method, string path, string? token = null, object? body = null)
+ {
+ using var request = new HttpRequestMessage(method, path);
+ if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ if (body is not null) request.Content = JsonContent.Create(body);
+ return await fixture.RawClient.SendAsync(request);
+ }
+
+ private async Task<(string Token, Guid PatientId, string Account)> Patient()
+ {
+ var account = "test-" + Interlocked.Increment(ref nextAccount);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (token, (await response.Content.ReadFromJsonAsync())!.PatientId, account);
+ }
+
+ [Fact]
+ public async Task Login_without_profile_returns_normalized_identity_and_no_patient_data()
+ {
+ using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
+ new { accountId = "test-0", password = AuthenticatedTestClient.Password, role = "HealthcareProfessional" });
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Contains("no-store", response.Headers.CacheControl!.ToString());
+ using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.Equal("test-0", json.RootElement.GetProperty("accountId").GetString());
+ Assert.Equal("Patient", json.RootElement.GetProperty("role").GetString());
+ Assert.Equal(1800, json.RootElement.GetProperty("expiresIn").GetInt32());
+ Assert.False(json.RootElement.TryGetProperty("patientId", out _));
+ Assert.False(json.RootElement.TryGetProperty("refreshToken", out _));
+ using var unavailable = await Send(HttpMethod.Get, $"/api/patients/{Guid.NewGuid()}", json.RootElement.GetProperty("accessToken").GetString());
+ Assert.Equal(HttpStatusCode.NotFound, unavailable.StatusCode);
+ }
+
+ [Fact]
+ public async Task Invalid_account_and_invalid_password_have_same_rejection()
+ {
+ using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "absent", password = AuthenticatedTestClient.Password });
+ using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "test-0", password = "incorrect" });
+ Assert.Equal(HttpStatusCode.Unauthorized, unknown.StatusCode);
+ Assert.Equal(unknown.StatusCode, incorrect.StatusCode);
+ Assert.Equal(await unknown.Content.ReadAsStringAsync(), await incorrect.Content.ReadAsStringAsync());
+ }
+
+ [Theory]
+ [InlineData("GET", "patients/00000000-0000-0000-0000-000000000001")]
+ [InlineData("POST", "patients")]
+ [InlineData("GET", "patients/me")]
+ [InlineData("PUT", "patients/00000000-0000-0000-0000-000000000001")]
+ [InlineData("GET", "observations/00000000-0000-0000-0000-000000000001")]
+ [InlineData("PUT", "observations/00000000-0000-0000-0000-000000000001")]
+ [InlineData("DELETE", "observations/00000000-0000-0000-0000-000000000001")]
+ [InlineData("POST", "patients/00000000-0000-0000-0000-000000000001/observations")]
+ [InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations/latest")]
+ [InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations")]
+ [InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/insights")]
+ public async Task Missing_and_invalid_tokens_reject_every_existing_patient_operation(string method, string path)
+ {
+ await using var patients = fixture.CreateDbContext();
+ await using var observations = fixture.CreateObservationDbContext();
+ var patientCount = await patients.Patients.CountAsync();
+ var observationCount = await observations.Observations.CountAsync();
+ foreach (var token in new string?[] { null, "unverifiable" })
+ {
+ using var response = await Send(new HttpMethod(method), "/api/" + path, token, method == "GET" ? null : ProfileRequest);
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.DoesNotContain("Patient", await response.Content.ReadAsStringAsync());
+ }
+ Assert.Equal(patientCount, await patients.Patients.CountAsync());
+ Assert.Equal(observationCount, await observations.Observations.CountAsync());
+ }
+
+ [Fact]
+ public async Task Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected()
+ {
+ var first = await Patient();
+ var second = await Patient();
+ using var record = await Send(HttpMethod.Post, $"/api/patients/{first.PatientId}/observations", first.Token, ObservationRequest);
+ Assert.Equal(HttpStatusCode.Created, record.StatusCode);
+ var observation = (await record.Content.ReadFromJsonAsync())!;
+ var paths = new[] { $"patients/{first.PatientId}", $"patients/{first.PatientId}/observations",
+ $"patients/{first.PatientId}/observations/latest", $"patients/{first.PatientId}/insights", $"observations/{observation.ObservationId}" };
+ foreach (var path in paths)
+ {
+ var query = path.EndsWith("/observations") || path.EndsWith("/insights") ? "?from=2026-09-01&to=2026-10-01" : "";
+ using var own = await Send(HttpMethod.Get, "/api/" + path + query, first.Token);
+ Assert.Equal(HttpStatusCode.OK, own.StatusCode);
+ using var other = await Send(HttpMethod.Get, "/api/" + path + query, second.Token);
+ Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
+ Assert.Empty(await other.Content.ReadAsStringAsync());
+ }
+ foreach (var (method, path, body) in new[]
+ {
+ (HttpMethod.Put, $"patients/{first.PatientId}", ProfileRequest),
+ (HttpMethod.Post, $"patients/{first.PatientId}/observations", ObservationRequest),
+ (HttpMethod.Put, $"observations/{observation.ObservationId}", ObservationRequest),
+ (HttpMethod.Delete, $"observations/{observation.ObservationId}", (object?)null)
+ })
+ {
+ using var response = await Send(method, "/api/" + path, second.Token, body);
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+ using var retained = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", first.Token);
+ Assert.Equal(128, (await retained.Content.ReadFromJsonAsync())!.Systolic);
+ await using var db = fixture.CreateObservationDbContext();
+ Assert.Single(await db.Observations.Where(o => o.PatientId == first.PatientId).ToListAsync());
+ }
+
+ [Fact]
+ public async Task Caller_supplied_account_identity_cannot_replace_authenticated_identity()
+ {
+ var account = "test-" + Interlocked.Increment(ref nextAccount);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
+ request.Headers.Authorization = new("Bearer", token);
+ request.Headers.Add("X-Account-Id", "test-0");
+ using var response = await fixture.RawClient.SendAsync(request);
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ await using var db = fixture.CreateDbContext();
+ var id = (await response.Content.ReadFromJsonAsync())!.PatientId;
+ Assert.Equal(account, (await db.Patients.SingleAsync(p => p.PatientId == id)).AccountId);
+ }
+
+ [Fact]
+ public async Task Profile_creation_retries_and_concurrency_preserve_one_persistent_association()
+ {
+ var account = "test-" + Interlocked.Increment(ref nextAccount);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ var responses = await Task.WhenAll(Send(HttpMethod.Post, "/api/patients", token, ProfileRequest), Send(HttpMethod.Post, "/api/patients", token, ProfileRequest));
+ try
+ {
+ Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
+ Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
+ var profile = (await responses.Single(r => r.StatusCode == HttpStatusCode.Created).Content.ReadFromJsonAsync())!;
+ using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
+ Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
+ await fixture.RestartHostsAsync();
+ using var read = await Send(HttpMethod.Get, "/api/patients/me", token);
+ Assert.Equal(HttpStatusCode.OK, read.StatusCode);
+ Assert.Equal(profile.PatientId, (await read.Content.ReadFromJsonAsync())!.PatientId);
+ await using var db = fixture.CreateDbContext();
+ Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
+ }
+ finally { foreach (var response in responses) response.Dispose(); }
+ }
+
+ [Fact]
+ public async Task Failed_creation_can_be_retried_without_an_orphan_profile()
+ {
+ var account = "test-" + Interlocked.Increment(ref nextAccount);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ await fixture.StopPatientServiceAsync();
+ using var failed = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, failed.StatusCode);
+ await fixture.RestartHostsAsync();
+ using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
+ Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
+ await using var db = fixture.CreateDbContext();
+ Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
+ }
+
+ [Fact]
+ public async Task Expired_token_is_rejected_and_login_produces_a_fresh_token()
+ {
+ var patient = await Patient();
+ fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
+ try
+ {
+ using var expired = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", patient.Token);
+ Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, patient.Account);
+ using var renewed = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", token);
+ Assert.Equal(HttpStatusCode.OK, renewed.StatusCode);
+ }
+ finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
+ }
+
+ [Fact]
+ public async Task Tampering_with_a_valid_token_is_rejected()
+ {
+ var patient = await Patient();
+ var token = patient.Token.ToCharArray();
+ var position = token.Length / 2;
+ token[position] = token[position] == 'A' ? 'B' : 'A';
+ using var response = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", new string(token));
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ [Fact]
+ public async Task Database_failure_rolls_back_profile_and_association_together()
+ {
+ var account = "test-" + Interlocked.Increment(ref nextAccount);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ await using var db = fixture.CreateDbContext();
+ await db.Database.ExecuteSqlRawAsync("""
+ CREATE FUNCTION fail_profile_test() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF NEW.name = 'simulate-write-failure' THEN RAISE EXCEPTION 'test write failure'; END IF;
+ RETURN NEW;
+ END; $$;
+ CREATE TRIGGER fail_profile_test BEFORE INSERT ON patient FOR EACH ROW EXECUTE FUNCTION fail_profile_test();
+ """);
+ try
+ {
+ using var failed = await Send(HttpMethod.Post, "/api/patients", token,
+ new { name = "simulate-write-failure", dateOfBirth = "1980-01-01" });
+ Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
+ Assert.Empty(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
+ using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
+ Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
+ Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
+ }
+ finally
+ {
+ await db.Database.ExecuteSqlRawAsync("DROP TRIGGER fail_profile_test ON patient; DROP FUNCTION fail_profile_test();");
+ }
+ }
+
+ [Fact]
+ public async Task Sole_public_edge_accepts_client_ticket_but_service_headers_grant_no_access()
+ {
+ var patient = await Patient();
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{patient.PatientId}");
+ request.Headers.Authorization=new("Bearer",patient.Token);request.Headers.Add("X-Gateway-Key","forged");
+ using var own=await fixture.RawClient.SendAsync(request);Assert.Equal(HttpStatusCode.OK,own.StatusCode);
+ using var bypass=new HttpRequestMessage(HttpMethod.Get,"/api/patients/by-account/"+patient.Account);
+ bypass.Headers.Authorization=new("Bearer",patient.Token);
+ using var absent=await fixture.RawClient.SendAsync(bypass);Assert.Equal(HttpStatusCode.NotFound,absent.StatusCode);
+ foreach(var path in new[]{"/api/patients","/api/patients/by-account/test-0"})
+ {
+ using var forged=new HttpRequestMessage(path=="/api/patients"?HttpMethod.Post:HttpMethod.Get,path){Content=path=="/api/patients"?JsonContent.Create(ProfileRequest):null};
+ forged.Headers.Add("X-Service-Key",fixture.Authentication.ObservationServiceKey);
+ using var denied=await fixture.RawClient.SendAsync(forged);Assert.Equal(HttpStatusCode.Unauthorized,denied.StatusCode);
+ }
+ }
+
+ [Fact]
+ public async Task Healthcare_professional_cannot_create_profiles()
+ {
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/ProfessionalAccessTests.cs b/tests/HealthApp.AcceptanceTests/ProfessionalAccessTests.cs
new file mode 100644
index 0000000..ef64e80
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/ProfessionalAccessTests.cs
@@ -0,0 +1,275 @@
+using System.Net;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text.Json;
+using HealthApp.TestSupport;
+using Microsoft.EntityFrameworkCore;
+using Xunit;
+
+namespace Observation.AcceptanceTests;
+
+public sealed class ProfessionalAccessTests(ObservationApiFixture fixture) : IClassFixture
+{
+ private const string AssignmentPath = "/api/professionals/me/patients";
+ private sealed record Profile(Guid PatientId, string Name);
+ private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic, string? Context, string? Note);
+ private sealed record AssignedPatient(Guid PatientId);
+
+ private async Task CreatePatient()
+ {
+ using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Assigned Patient", dateOfBirth = "1980-01-01" });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!.PatientId;
+ }
+
+ private async Task Record(Guid patientId)
+ {
+ using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
+ {
+ measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68,
+ context = "Resting", note = "Actual conditions"
+ });
+ Assert.Equal(HttpStatusCode.Created, response.StatusCode);
+ return (await response.Content.ReadFromJsonAsync())!;
+ }
+
+ private async Task Assign(Guid[] first, Guid[]? second = null)
+ {
+ fixture.AdditionalGatewayConfiguration.Clear();
+ for (var i = 0; i < first.Length; i++)
+ fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional:{i}"] = first[i].ToString();
+ for (var i = 0; i < (second?.Length ?? 0); i++)
+ fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional-second:{i}"] = second![i].ToString();
+ await fixture.RestartHostsAsync();
+ }
+
+ private async Task Send(HttpMethod method, string path, string? token, object? body = null)
+ {
+ using var request = new HttpRequestMessage(method, path);
+ if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ if (body is not null) request.Content = JsonContent.Create(body);
+ return await fixture.RawClient.SendAsync(request);
+ }
+
+ [Fact]
+ public async Task Login_recognizes_professional_identity_and_does_not_put_assignments_in_the_token_response()
+ {
+ using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
+ new { accountId = "professional", password = AuthenticatedTestClient.Password, role = "Patient" });
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ Assert.Equal("HealthcareProfessional", json.RootElement.GetProperty("role").GetString());
+ Assert.Equal("professional", json.RootElement.GetProperty("accountId").GetString());
+ Assert.False(json.RootElement.TryGetProperty("patientId", out _));
+ Assert.False(json.RootElement.TryGetProperty("assignments", out _));
+ }
+
+ [Fact]
+ public async Task Professionals_list_only_their_own_assignments_and_can_share_patients()
+ {
+ var first = await CreatePatient();
+ var shared = await CreatePatient();
+ var second = await CreatePatient();
+ var excluded = await CreatePatient();
+ await Assign([first, shared, first], [shared, second]);
+ foreach (var (account, expected) in new[]
+ {
+ ("professional", new[] { first, shared }),
+ ("professional-second", new[] { shared, second }),
+ ("professional-empty", Array.Empty())
+ })
+ {
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ using var response = await Send(HttpMethod.Get, AssignmentPath + "?accountId=professional-second", token);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ var patients = (await response.Content.ReadFromJsonAsync())!;
+ Assert.Equal(expected.Order(), patients.Select(p => p.PatientId).Order());
+ Assert.DoesNotContain(patients, p => p.PatientId == excluded);
+ }
+ var sharedToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-second");
+ using var read = await Send(HttpMethod.Get, $"/api/patients/{shared}", sharedToken);
+ Assert.Equal(HttpStatusCode.OK, read.StatusCode);
+ }
+
+ [Fact]
+ public async Task Assigned_profiles_observations_context_history_latest_and_insights_are_readable()
+ {
+ var patient = await CreatePatient();
+ var observation = await Record(patient);
+ await Assign([patient]);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ foreach (var path in new[]
+ {
+ $"/api/patients/{patient}", $"/api/observations/{observation.ObservationId}",
+ $"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01",
+ $"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
+ })
+ {
+ using var response = await Send(HttpMethod.Get, path, token);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using var own = await fixture.Client.GetAsync(path);
+ Assert.Equal(await own.Content.ReadAsStringAsync(), await response.Content.ReadAsStringAsync());
+ }
+ using var specific = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
+ Assert.Equal(observation, await specific.Content.ReadFromJsonAsync());
+ }
+
+ [Fact]
+ public async Task Unassigned_patients_and_observations_are_rejected_even_with_a_supplied_assigned_patient_id()
+ {
+ var assigned = await CreatePatient();
+ var unassigned = await CreatePatient();
+ var observation = await Record(unassigned);
+ await Assign([assigned]);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ foreach (var path in new[]
+ {
+ $"/api/patients/{unassigned}", $"/api/observations/{observation.ObservationId}?patientId={assigned}",
+ $"/api/patients/{unassigned}/observations/latest", $"/api/patients/{unassigned}/observations?from=2026-09-01&to=2026-10-01",
+ $"/api/patients/{unassigned}/insights?from=2026-09-01&to=2026-10-01"
+ })
+ {
+ using var response = await Send(HttpMethod.Get, path, token);
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ Assert.Empty(await response.Content.ReadAsStringAsync());
+ }
+ }
+
+ [Fact]
+ public async Task Missing_information_for_assigned_patients_follows_existing_retrieval_behaviour()
+ {
+ var patient = await CreatePatient();
+ var missingPatient = Guid.NewGuid();
+ await Assign([patient, missingPatient]);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ foreach (var path in new[]
+ {
+ $"/api/patients/{missingPatient}", $"/api/observations/{Guid.NewGuid()}",
+ $"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
+ })
+ {
+ using var response = await Send(HttpMethod.Get, path, token);
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+ using var history = await Send(HttpMethod.Get, $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01", token);
+ Assert.Equal(HttpStatusCode.OK, history.StatusCode);
+ Assert.Equal("[]", await history.Content.ReadAsStringAsync());
+ }
+
+ [Theory]
+ [InlineData("professional")]
+ [InlineData("professional-empty")]
+ public async Task Professionals_cannot_create_update_or_delete_any_patient_information(string account)
+ {
+ var patient = await CreatePatient();
+ var observation = await Record(patient);
+ await Assign([patient]);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ await using var patients = fixture.CreateDbContext();
+ await using var observations = fixture.CreateObservationDbContext();
+ var before = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
+ var count = await patients.Patients.CountAsync();
+ foreach (var (method, path, body) in new[]
+ {
+ (HttpMethod.Post, "/api/patients", (object?)new { name = "Forbidden", dateOfBirth = "1980-01-01" }),
+ (HttpMethod.Put, $"/api/patients/{patient}", (object?)new { name = "Forbidden" }),
+ (HttpMethod.Post, $"/api/patients/{patient}/observations", (object?)new { measuredAt = "2026-09-12T08:00:00", systolic = 190, diastolic = 90, pulse = 80 }),
+ (HttpMethod.Put, $"/api/observations/{observation.ObservationId}", (object?)new { systolic = 190, diastolic = 90, pulse = 80 }),
+ (HttpMethod.Delete, $"/api/observations/{observation.ObservationId}", (object?)null)
+ })
+ {
+ using var response = await Send(method, path, token, body);
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Assert.Empty(await response.Content.ReadAsStringAsync());
+ }
+ Assert.Equal(count, await patients.Patients.CountAsync());
+ var after = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
+ Assert.Equal(before.Name, after.Name);
+ Assert.Equal(before.UpdatedAt, after.UpdatedAt);
+ var saved = await observations.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == observation.ObservationId);
+ Assert.Equal(128, saved.Systolic);
+ Assert.Equal("Resting", saved.Context);
+ Assert.Equal("Actual conditions", saved.Note);
+ Assert.Single(await observations.Observations.Where(o => o.PatientId == patient).ToListAsync());
+ }
+
+ [Fact]
+ public async Task Missing_invalid_and_expired_tokens_do_not_disclose_assignments_or_patient_data()
+ {
+ var patient = await CreatePatient();
+ await Assign([patient]);
+ foreach (var token in new string?[] { null, "invalid" })
+ {
+ using var list = await Send(HttpMethod.Get, AssignmentPath, token);
+ using var read = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
+ Assert.Equal(HttpStatusCode.Unauthorized, list.StatusCode);
+ Assert.Equal(HttpStatusCode.Unauthorized, read.StatusCode);
+ Assert.Empty(await list.Content.ReadAsStringAsync());
+ Assert.Empty(await read.Content.ReadAsStringAsync());
+ }
+ var valid = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
+ try
+ {
+ using var expired = await Send(HttpMethod.Get, AssignmentPath, valid);
+ Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
+ }
+ finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
+ }
+
+ [Fact]
+ public async Task Incorrect_professional_secret_and_unknown_account_have_identical_login_rejections()
+ {
+ using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "professional", password = "wrong" });
+ using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "unknown-professional", password = AuthenticatedTestClient.Password });
+ Assert.Equal(HttpStatusCode.Unauthorized, incorrect.StatusCode);
+ Assert.Equal(incorrect.StatusCode, unknown.StatusCode);
+ Assert.Equal(await incorrect.Content.ReadAsStringAsync(), await unknown.Content.ReadAsStringAsync());
+ }
+
+ [Fact]
+ public async Task Patient_cannot_list_professional_assignments_and_retains_own_access()
+ {
+ var patient = await CreatePatient();
+ await Assign([patient]);
+ var account = fixture.Authentication.PatientAccounts[patient];
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
+ using var rejected = await Send(HttpMethod.Get, AssignmentPath, token);
+ Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
+ using var own = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
+ Assert.Equal(HttpStatusCode.OK, own.StatusCode);
+ }
+
+ [Fact]
+ public async Task Assignment_removal_is_used_after_restart_even_with_an_existing_token()
+ {
+ var patient = await CreatePatient();
+ await Assign([patient]);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ using var allowed = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
+ Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
+ await Assign([]);
+ using var rejected = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
+ Assert.Equal(HttpStatusCode.NotFound, rejected.StatusCode);
+ using var list = await Send(HttpMethod.Get, AssignmentPath, token);
+ Assert.Equal("[]", await list.Content.ReadAsStringAsync());
+ }
+
+ [Fact]
+ public async Task Observation_ownership_lookup_failure_fails_closed_while_assignment_list_remains_available()
+ {
+ var patient = await CreatePatient();
+ var observation = await Record(patient);
+ await Assign([patient]);
+ var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
+ await fixture.StopObservationServiceAsync();
+ try
+ {
+ using var read = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
+ Assert.Equal(HttpStatusCode.ServiceUnavailable, read.StatusCode);
+ using var list = await Send(HttpMethod.Get, AssignmentPath, token);
+ Assert.Equal(HttpStatusCode.OK, list.StatusCode);
+ }
+ finally { await fixture.RestartHostsAsync(); }
+ }
+}
diff --git a/tests/HealthApp.AcceptanceTests/SnapshotTests.cs b/tests/HealthApp.AcceptanceTests/SnapshotTests.cs
new file mode 100644
index 0000000..91d5b69
--- /dev/null
+++ b/tests/HealthApp.AcceptanceTests/SnapshotTests.cs
@@ -0,0 +1,57 @@
+using System.Net.Http.Json;
+using HealthApp.Contracts;
+using HealthApp.Infrastructure;
+using Microsoft.Extensions.DependencyInjection;
+using Npgsql;
+using Observation.AcceptanceTests;
+using Xunit;
+namespace HealthApp.AcceptanceTests;
+public sealed class SnapshotTests(ObservationApiFixture fixture) : IClassFixture
+{
+ [Fact]
+ public async Task Overview_is_coherent_and_next_snapshot_sees_commits()
+ {
+ using var create=await fixture.Client.PostAsJsonAsync("/api/patients",new{name="Before",dateOfBirth="1980-01-01"});var p=(await create.Content.ReadFromJsonAsync())!;
+ using var record=await fixture.Client.PostAsJsonAsync($"/api/patients/{p.PatientId}/observations",new{measuredAt="2026-09-12T08:00:00",systolic=120,diastolic=80,pulse=60});var o=(await record.Content.ReadFromJsonAsync())!;
+ var captured=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);var resume=new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ var armed=1;var selectedCount=0;var releasedBeforeReturn=false;
+ fixture.ConfigureServices=services=>{
+ var pd=services.Last(d=>d.ServiceType==typeof(ProfileQueries));services.Remove(pd);
+ services.AddScoped(sp=>new PausingProfile((ProfileQueries)pd.ImplementationFactory!(sp),async()=>{if(Interlocked.Exchange(ref armed,0)==1){captured.SetResult();await resume.Task;}}));
+ var od=services.Last(d=>d.ServiceType==typeof(ObservationQueries));services.Remove(od);
+ services.AddScoped(sp=>new CountingObservations((ObservationQueries)od.ImplementationFactory!(sp),()=>Interlocked.Increment(ref selectedCount)));
+ var ad=services.Last(d=>d.ServiceType==typeof(AnalyticsQueries));services.Remove(ad);
+ services.AddScoped(sp=>new CheckingAnalytics((AnalyticsQueries)ActivatorUtilities.CreateInstance(sp,ad.ImplementationType!),()=>releasedBeforeReturn=!sp.GetRequiredService().Active));
+ };
+ await fixture.RestartHostsAsync();
+ try
+ {
+ var path=$"/api/patients/{p.PatientId}/overview?from=2026-09-01&to=2026-09-30";
+ var reading=fixture.Client.GetFromJsonAsync(path);
+ await captured.Task.WaitAsync(TimeSpan.FromSeconds(10));
+ await using(var c=new NpgsqlConnection(fixture.ConnectionString))
+ {await c.OpenAsync();await using var t=await c.BeginTransactionAsync();var cmd=new NpgsqlCommand("UPDATE profile.patient SET name='After' WHERE patient_id=@p; UPDATE observations.observation SET systolic=180 WHERE observation_id=@o",c,t);cmd.Parameters.AddWithValue("p",p.PatientId);cmd.Parameters.AddWithValue("o",o.ObservationId);await cmd.ExecuteNonQueryAsync();await t.CommitAsync();}
+ resume.SetResult();var first=(await reading)!;
+ Assert.Equal("Before",first.Patient.Name);Assert.Equal(120,first.LatestObservation!.Systolic);Assert.Equal(120m,first.Insight!.AverageSystolic);Assert.Equal(1,selectedCount);Assert.True(releasedBeforeReturn);
+ var next=(await fixture.Client.GetFromJsonAsync(path))!;Assert.Equal("After",next.Patient.Name);Assert.Equal(180,next.LatestObservation!.Systolic);Assert.Equal(180m,next.Insight!.AverageSystolic);
+ }
+ finally{resume.TrySetResult();fixture.ConfigureServices=null;await fixture.RestartHostsAsync();}
+ }
+ private sealed class PausingProfile(ProfileQueries inner,Func pause) : ProfileQueries
+ {
+ public Task ResolveAccountAsync(string a,CancellationToken ct)=>inner.ResolveAccountAsync(a,ct);
+ public async Task GetAsync(AuthorizedPatientContext s,CancellationToken ct){var p=await inner.GetAsync(s,ct);await pause();return p;}
+ }
+ private sealed class CountingObservations(ObservationQueries inner,Action count) : ObservationQueries
+ {
+ public Task ResolveOwnerAsync(Guid id,CancellationToken ct)=>inner.ResolveOwnerAsync(id,ct);
+ public Task GetAsync(AuthorizedPatientContext s,Guid id,CancellationToken ct)=>inner.GetAsync(s,id,ct);
+ public Task LatestAsync(AuthorizedPatientContext s,CancellationToken ct)=>inner.LatestAsync(s,ct);
+ public Task> SelectedAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct){count();return inner.SelectedAsync(s,f,t,c,ct);}
+ }
+ private sealed class CheckingAnalytics(AnalyticsQueries inner,Action check) : AnalyticsQueries
+ {
+ public async Task InsightAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct){var v=await inner.InsightAsync(s,f,t,c,ct);check();return v;}
+ public Task TrendAsync(AuthorizedPatientContext s,DateTime f,DateTime t,ContextSelection c,CancellationToken ct)=>inner.TrendAsync(s,f,t,c,ct);
+ }
+}