From 5996481081046ecc4a55605ac34c0e0199bf038f Mon Sep 17 00:00:00 2001 From: Steffen Date: Mon, 5 Oct 2026 11:40:34 +0200 Subject: [PATCH] Implement US-14 assigned professional read access --- deploy/api-gateway.env.example | 8 + src/AUTHENTICATION.md | 62 +++- .../Controllers/ProfessionalController.cs | 17 ++ src/ApiGateway/Program.cs | 10 +- .../Security/PatientAccessMiddleware.cs | 41 ++- .../Security/ProfessionalAssignments.cs | 24 ++ src/README.md | 6 +- .../ObservationApiFixture.cs | 3 +- .../ProfessionalAccessTests.cs | 275 ++++++++++++++++++ .../AuthenticationIntegrationTests.cs | 13 +- tests/Support/AuthenticatedTestClient.cs | 6 + 11 files changed, 441 insertions(+), 24 deletions(-) create mode 100644 src/ApiGateway/Controllers/ProfessionalController.cs create mode 100644 src/ApiGateway/Security/ProfessionalAssignments.cs create mode 100644 tests/Observation.AcceptanceTests/ProfessionalAccessTests.cs diff --git a/deploy/api-gateway.env.example b/deploy/api-gateway.env.example index bd42992..dbff8d4 100644 --- a/deploy/api-gateway.env.example +++ b/deploy/api-gateway.env.example @@ -19,3 +19,11 @@ Services__Observation__Key=REPLACE_ME Services__Insights__Key=REPLACE_ME InternalAccess__Observation__Key=REPLACE_ME InternalAccess__Insights__Key=REPLACE_ME + +# Pre-created professional credentials and read-only patient assignments. +Authentication__Accounts__1__AccountId=example_professional +Authentication__Accounts__1__Role=HealthcareProfessional +Authentication__Accounts__1__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH +# Replace the synthetic identifier below with a created patient's identifier. +# Restart the gateway after changing assignments. Omit assignments for an empty list. +Access__ProfessionalAssignments__example_professional__0=00000000-0000-0000-0000-000000000001 diff --git a/src/AUTHENTICATION.md b/src/AUTHENTICATION.md index c1c11c6..0bd5e69 100644 --- a/src/AUTHENTICATION.md +++ b/src/AUTHENTICATION.md @@ -81,9 +81,9 @@ API to obtain the actual patient, then compares that owner with the account's profile. Requests for another patient's information receive an empty `404`, the same as missing data, without forwarding writes or revealing existence. Failed ownership lookups fail closed with `502`/`504`. Tokens do not cache ownership. -Healthcare-professional logins establish a trusted role, but their access is denied -by default until US-14's assigned-patient read policies are implemented; US-14 is -not completed by this change. Trend/overview endpoints remain unimplemented; the +Healthcare-professional logins establish a trusted role. US-14 now permits reads +of assigned patients and the caller’s own assignment list; all professional writes +are rejected before forwarding. Trend/overview endpoints remain unimplemented; the gateway's default authentication policy also protects future patient endpoints, which must retain ownership checks when added. @@ -128,3 +128,59 @@ than a production authentication bypass. Framework reference: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0 + +## US-14 professional assignments + +Predefine assignments in the gateway's external `Access:ProfessionalAssignments` +configuration, keyed by the stable professional account identifier. For example: + +```json +{ + "Access": { + "ProfessionalAssignments": { + "example_professional": [ + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002" + ] + } + } +} +``` + +Use actual patient identifiers returned by authenticated profile creation. The +example UUIDs are placeholders. A professional can have several patients, and +several professionals can share a patient. Duplicate identifiers are treated as +one assignment. Empty identifiers are rejected at startup. An omitted account +entry means no assignments. Configure that account's role and password hash +separately under `Authentication:Accounts`; assignments never grant a role. + +`GET /api/professionals/me/patients` requires the HealthcareProfessional policy and +returns an array of `{ "patientId": "..." }` entries, in deterministic identifier +order. It lists only the caller's configured assignments, without fetching patient +records. No assignments returns `[]`. Missing profiles remain assigned identifiers; +retrieving their data follows the existing missing-resource behaviour. Caller +query parameters or identity headers cannot select another professional's list. +Patient accounts cannot use this endpoint. + +Professional GET requests to existing patient profiles, observations (including +recorded legacy context), history, latest observations and numerical insight +require membership in the caller's assignment set. Observation-ID requests resolve +the actual owning patient via the protected Observation API; a supplied patient ID +is not evidence of assignment. Unassigned reads return an empty `404`, preserving +the same non-disclosure convention as patient access. Assigned missing data follows +the existing retrieval contracts. All professional POST/PUT/PATCH/DELETE requests +are rejected with `403` before ownership lookups or forwarding. There is no +assignment-management API or additional database/service. + +Assignments are loaded at gateway startup, outside tokens and credential +validation. Restart the gateway after changing its external configuration. Existing +valid tokens then use the new assignment data. Empty lists need no upstream service; +observation-owner lookup failures fail closed with `502`/`504`. + +The US-14 tests exercise actual login, multiple and shared assignments, empty lists, +assigned/unassigned reads, preserved context, missing resources, every existing +write route, invalid and expired credentials, patient-role rejection, assignment +changes across restart and unavailable ownership lookup. Trend and overview +endpoints are still absent: their read routing and integration tests must be added +with US-11/US-12. Structured context remains work under US-04–US-08; professional +access already applies to whatever observation context those APIs expose. diff --git a/src/ApiGateway/Controllers/ProfessionalController.cs b/src/ApiGateway/Controllers/ProfessionalController.cs new file mode 100644 index 0000000..7572287 --- /dev/null +++ b/src/ApiGateway/Controllers/ProfessionalController.cs @@ -0,0 +1,17 @@ +using System.Security.Claims; +using ApiGateway.Security; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace ApiGateway.Controllers; + +[ApiController] +[Authorize(Policy = "HealthcareProfessional")] +[Route("api/professionals/me/patients")] +public sealed class ProfessionalController(ProfessionalAssignments assignments) : ControllerBase +{ + [HttpGet] + public IActionResult GetAssignedPatients() => + Ok(assignments.GetPatients(User.FindFirstValue(ClaimTypes.NameIdentifier)!) + .Select(patientId => new { patientId })); +} diff --git a/src/ApiGateway/Program.cs b/src/ApiGateway/Program.cs index 2af8b38..e65a512 100644 --- a/src/ApiGateway/Program.cs +++ b/src/ApiGateway/Program.cs @@ -15,6 +15,7 @@ public class Program builder.Services.AddControllers(); builder.Services.AddProblemDetails(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddAuthentication("ClientOrService") .AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context => context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer") @@ -23,7 +24,13 @@ public class Program options.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30)); }) .AddScheme("InternalService", null); - builder.Services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier)); }); + builder.Services.AddAuthorization(options => + { + options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); + options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier)); + options.AddPolicy("HealthcareProfessional", policy => policy.RequireRole("HealthcareProfessional") + .RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier)); + }); builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway"); builder.Services.AddOptions().Configure((options, configuration, logger) => { @@ -71,6 +78,7 @@ public class Program if (GetBaseUri(app.Configuration, service).Scheme != "https") throw new InvalidOperationException("Production service endpoints must use HTTPS."); _ = app.Services.GetRequiredService(); + _ = app.Services.GetRequiredService(); app.UseExceptionHandler(); app.Use(async (context, next) => { diff --git a/src/ApiGateway/Security/PatientAccessMiddleware.cs b/src/ApiGateway/Security/PatientAccessMiddleware.cs index e74cacc..d82e201 100644 --- a/src/ApiGateway/Security/PatientAccessMiddleware.cs +++ b/src/ApiGateway/Security/PatientAccessMiddleware.cs @@ -7,7 +7,8 @@ namespace ApiGateway.Security; public sealed class PatientAccessMiddleware(RequestDelegate next) { - public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization) + public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization, + ProfessionalAssignments assignments) { if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) { @@ -27,10 +28,21 @@ public sealed class PatientAccessMiddleware(RequestDelegate next) await next(context); return; } - // US-14's professional access is implemented separately; deny by default meanwhile. - if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded) { context.Response.StatusCode = 403; return; } - if ((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST") - || (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET")) + var professional = (await authorization.AuthorizeAsync(context.User, "HealthcareProfessional")).Succeeded; + if (professional) + { + if (context.Request.Method != "GET") { context.Response.StatusCode = 403; return; } + if (route.Equals("/api/professionals/me/patients", StringComparison.OrdinalIgnoreCase)) + { + await next(context); + return; + } + } + else if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded) + { context.Response.StatusCode = 403; return; } + if (!professional && + ((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST") + || (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET"))) { await next(context); return; @@ -38,12 +50,16 @@ public sealed class PatientAccessMiddleware(RequestDelegate next) try { var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!; - using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync( - "api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted); - if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; } - ownResponse.EnsureSuccessStatusCode(); - using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted)); - var patientId = own.RootElement.GetProperty("patientId").GetGuid(); + Guid? patientId = null; + if (!professional) + { + using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync( + "api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted); + if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; } + ownResponse.EnsureSuccessStatusCode(); + using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted)); + patientId = own.RootElement.GetProperty("patientId").GetGuid(); + } Guid requestedPatient; if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients" && Guid.TryParse(segments[2], out requestedPatient)) { } @@ -57,7 +73,8 @@ public sealed class PatientAccessMiddleware(RequestDelegate next) requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid(); } else { context.Response.StatusCode = 404; return; } - if (requestedPatient != patientId) { context.Response.StatusCode = 404; return; } + var permitted = professional ? assignments.IsAssigned(accountId, requestedPatient) : requestedPatient == patientId; + if (!permitted) { context.Response.StatusCode = 404; return; } await next(context); } catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); } diff --git a/src/ApiGateway/Security/ProfessionalAssignments.cs b/src/ApiGateway/Security/ProfessionalAssignments.cs new file mode 100644 index 0000000..a2af03c --- /dev/null +++ b/src/ApiGateway/Security/ProfessionalAssignments.cs @@ -0,0 +1,24 @@ +namespace ApiGateway.Security; + +// Application access data, separate from credentials and token contents. +public sealed class ProfessionalAssignments +{ + private readonly Dictionary assignments; + + public ProfessionalAssignments(IConfiguration configuration) + { + assignments = configuration.GetSection("Access:ProfessionalAssignments") + .Get>() ?? new(StringComparer.Ordinal); + foreach (var accountId in assignments.Keys.ToArray()) + { + if (string.IsNullOrWhiteSpace(accountId) || assignments[accountId].Any(id => id == Guid.Empty)) + throw new InvalidOperationException("Professional assignments require an account identifier and nonempty patient identifiers."); + assignments[accountId] = assignments[accountId].Distinct().Order().ToArray(); + } + } + + public IReadOnlyList GetPatients(string accountId) => + assignments.TryGetValue(accountId, out var patients) ? Array.AsReadOnly(patients) : Array.Empty(); + + public bool IsAssigned(string accountId, Guid patientId) => GetPatients(accountId).Contains(patientId); +} diff --git a/src/README.md b/src/README.md index 9573a74..cc19c5d 100644 --- a/src/README.md +++ b/src/README.md @@ -7,7 +7,7 @@ The controller calls `PatientApplicationService`, which uses `PatientRepository` US-13 now protects the patient-data APIs. Read [AUTHENTICATION.md](AUTHENTICATION.md) for login, persistent profile ownership, deployment credentials and token settings. Configure the required keys/accounts before startup. The revised US-01 creation -lifecycle is included; US-14 assigned-professional access remains pending. +lifecycle is included. US-14 now permits read-only access to assigned patients. ## Build and run @@ -92,8 +92,8 @@ US-10 tests use all four HTTP hosts and the existing separate patient/observatio US-13 authentication and patient ownership are implemented as described in [AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted -in the patient service. US-14 assigned-professional read access remains pending; -professional patient-data operations are denied until then. Updated context, tie +in the patient service. US-14 professional reads require predefined gateway assignments; professional +writes are rejected. Updated context, tie and rounding requirements in other stories remain to be implemented incrementally. ## Automated acceptance tests diff --git a/tests/Observation.AcceptanceTests/ObservationApiFixture.cs b/tests/Observation.AcceptanceTests/ObservationApiFixture.cs index 6315012..fcb91bf 100644 --- a/tests/Observation.AcceptanceTests/ObservationApiFixture.cs +++ b/tests/Observation.AcceptanceTests/ObservationApiFixture.cs @@ -29,6 +29,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime public HttpClient CreateDirectObservationClient() => observation!.CreateClient(); public HttpClient CreateDirectInsightsClient() => insights!.CreateClient(); public AuthenticatedTestClient Authentication { get; } = new(); + public Dictionary AdditionalGatewayConfiguration { get; } = new(); public async Task InitializeAsync() { @@ -76,7 +77,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime { builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); - builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection( + builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(AdditionalGatewayConfiguration).AddInMemoryCollection( new Dictionary { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(), ["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/", ["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })); diff --git a/tests/Observation.AcceptanceTests/ProfessionalAccessTests.cs b/tests/Observation.AcceptanceTests/ProfessionalAccessTests.cs new file mode 100644 index 0000000..39d8c4d --- /dev/null +++ b/tests/Observation.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.BadGateway, 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/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs b/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs index 588835f..1e3e5b2 100644 --- a/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs +++ b/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs @@ -42,14 +42,19 @@ public sealed class AuthenticationIntegrationTests finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } } - [Fact] - public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy() + [Theory] + [InlineData("Patient", "test-0")] + [InlineData("HealthcareProfessional", "professional")] + public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy(string role, string accountId) { var authentication = new AuthenticatedTestClient(); var patient = Guid.NewGuid(); try { var configuration = authentication.Configuration(); + configuration["TestIdentity:Role"] = role; + configuration["TestIdentity:AccountId"] = accountId; + configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString(); foreach (var service in new[] { "PatientProfile", "Observation", "Insights" }) configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/"; using var host = new WebApplicationFactory().WithWebHostBuilder(builder => @@ -73,13 +78,13 @@ public sealed class AuthenticationIntegrationTests finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } } - public sealed class ReplacementHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) + public sealed class ReplacementHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration) : AuthenticationHandler(options, logger, encoder) { protected override Task HandleAuthenticateAsync() => Task.FromResult( AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[] { - new Claim(ClaimTypes.NameIdentifier, "test-0"), new Claim(ClaimTypes.Role, "Patient") + new Claim(ClaimTypes.NameIdentifier, configuration["TestIdentity:AccountId"]!), new Claim(ClaimTypes.Role, configuration["TestIdentity:Role"]!) }, Scheme.Name)), Scheme.Name))); } diff --git a/tests/Support/AuthenticatedTestClient.cs b/tests/Support/AuthenticatedTestClient.cs index 3b0d911..876e19e 100644 --- a/tests/Support/AuthenticatedTestClient.cs +++ b/tests/Support/AuthenticatedTestClient.cs @@ -44,6 +44,12 @@ public sealed class AuthenticatedTestClient values["Authentication:Accounts:256:AccountId"] = "professional"; values["Authentication:Accounts:256:PasswordHash"] = hash; values["Authentication:Accounts:256:Role"] = "HealthcareProfessional"; + for (var i = 257; i <= 258; i++) + { + values[$"Authentication:Accounts:{i}:AccountId"] = i == 257 ? "professional-second" : "professional-empty"; + values[$"Authentication:Accounts:{i}:PasswordHash"] = hash; + values[$"Authentication:Accounts:{i}:Role"] = "HealthcareProfessional"; + } return values; }