Implement US-14 assigned professional read access

This commit is contained in:
Steffen committed 2026-10-05 11:40:34 +02:00
1 parent 0ce9b2b168
commit 5996481081
11 files changed
+441 -24

No files matched your search

+8
View File
@@ -19,3 +19,11 @@ Services__Observation__Key=REPLACE_ME
Services__Insights__Key=REPLACE_ME Services__Insights__Key=REPLACE_ME
InternalAccess__Observation__Key=REPLACE_ME InternalAccess__Observation__Key=REPLACE_ME
InternalAccess__Insights__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
+59 -3
View File
@@ -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 profile. Requests for another patient's information receive an empty `404`, the
same as missing data, without forwarding writes or revealing existence. Failed same as missing data, without forwarding writes or revealing existence. Failed
ownership lookups fail closed with `502`/`504`. Tokens do not cache ownership. ownership lookups fail closed with `502`/`504`. Tokens do not cache ownership.
Healthcare-professional logins establish a trusted role, but their access is denied Healthcare-professional logins establish a trusted role. US-14 now permits reads
by default until US-14's assigned-patient read policies are implemented; US-14 is of assigned patients and the caller’s own assignment list; all professional writes
not completed by this change. Trend/overview endpoints remain unimplemented; the are rejected before forwarding. Trend/overview endpoints remain unimplemented; the
gateway's default authentication policy also protects future patient endpoints, gateway's default authentication policy also protects future patient endpoints,
which must retain ownership checks when added. which must retain ownership checks when added.
@@ -128,3 +128,59 @@ than a production authentication bypass.
Framework reference: Framework reference:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0 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.
@@ -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 }));
}
+9 -1
View File
@@ -15,6 +15,7 @@ public class Program
builder.Services.AddControllers(); builder.Services.AddControllers();
builder.Services.AddProblemDetails(); builder.Services.AddProblemDetails();
builder.Services.AddSingleton<PrototypeAccounts>(); builder.Services.AddSingleton<PrototypeAccounts>();
builder.Services.AddSingleton<ProfessionalAssignments>();
builder.Services.AddAuthentication("ClientOrService") builder.Services.AddAuthentication("ClientOrService")
.AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context => .AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context =>
context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer") 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)); options.BearerTokenExpiration = TimeSpan.FromMinutes(builder.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30));
}) })
.AddScheme<AuthenticationSchemeOptions, InternalServiceAuthenticationHandler>("InternalService", null); .AddScheme<AuthenticationSchemeOptions, InternalServiceAuthenticationHandler>("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.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
builder.Services.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((options, configuration, logger) => builder.Services.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((options, configuration, logger) =>
{ {
@@ -71,6 +78,7 @@ public class Program
if (GetBaseUri(app.Configuration, service).Scheme != "https") if (GetBaseUri(app.Configuration, service).Scheme != "https")
throw new InvalidOperationException("Production service endpoints must use HTTPS."); throw new InvalidOperationException("Production service endpoints must use HTTPS.");
_ = app.Services.GetRequiredService<PrototypeAccounts>(); _ = app.Services.GetRequiredService<PrototypeAccounts>();
_ = app.Services.GetRequiredService<ProfessionalAssignments>();
app.UseExceptionHandler(); app.UseExceptionHandler();
app.Use(async (context, next) => app.Use(async (context, next) =>
{ {
@@ -7,7 +7,8 @@ namespace ApiGateway.Security;
public sealed class PatientAccessMiddleware(RequestDelegate next) 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<IAllowAnonymous>() is not null) if (context.GetEndpoint()?.Metadata.GetMetadata<IAllowAnonymous>() is not null)
{ {
@@ -27,10 +28,21 @@ public sealed class PatientAccessMiddleware(RequestDelegate next)
await next(context); await next(context);
return; return;
} }
// US-14's professional access is implemented separately; deny by default meanwhile. var professional = (await authorization.AuthorizeAsync(context.User, "HealthcareProfessional")).Succeeded;
if (!(await authorization.AuthorizeAsync(context.User, "Patient")).Succeeded) { context.Response.StatusCode = 403; return; } if (professional)
if ((route.Equals("/api/patients", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "POST") {
|| (route.Equals("/api/patients/me", StringComparison.OrdinalIgnoreCase) && context.Request.Method == "GET")) 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); await next(context);
return; return;
@@ -38,12 +50,16 @@ public sealed class PatientAccessMiddleware(RequestDelegate next)
try try
{ {
var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!; var accountId = context.User.FindFirstValue(ClaimTypes.NameIdentifier)!;
using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync( Guid? patientId = null;
"api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted); if (!professional)
if (ownResponse.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; } {
ownResponse.EnsureSuccessStatusCode(); using var ownResponse = await clients.CreateClient("PatientProfile").GetAsync(
using var own = JsonDocument.Parse(await ownResponse.Content.ReadAsStringAsync(context.RequestAborted)); "api/patients/by-account/" + Uri.EscapeDataString(accountId), context.RequestAborted);
var patientId = own.RootElement.GetProperty("patientId").GetGuid(); 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; Guid requestedPatient;
if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients" if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients"
&& Guid.TryParse(segments[2], out requestedPatient)) { } && Guid.TryParse(segments[2], out requestedPatient)) { }
@@ -57,7 +73,8 @@ public sealed class PatientAccessMiddleware(RequestDelegate next)
requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid(); requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid();
} }
else { context.Response.StatusCode = 404; return; } 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); await next(context);
} }
catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); } catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); }
@@ -0,0 +1,24 @@
namespace ApiGateway.Security;
// Application access data, separate from credentials and token contents.
public sealed class ProfessionalAssignments
{
private readonly Dictionary<string, Guid[]> assignments;
public ProfessionalAssignments(IConfiguration configuration)
{
assignments = configuration.GetSection("Access:ProfessionalAssignments")
.Get<Dictionary<string, Guid[]>>() ?? 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<Guid> GetPatients(string accountId) =>
assignments.TryGetValue(accountId, out var patients) ? Array.AsReadOnly(patients) : Array.Empty<Guid>();
public bool IsAssigned(string accountId, Guid patientId) => GetPatients(accountId).Contains(patientId);
}
+3 -3
View File
@@ -7,7 +7,7 @@ The controller calls `PatientApplicationService`, which uses `PatientRepository`
US-13 now protects the patient-data APIs. Read [AUTHENTICATION.md](AUTHENTICATION.md) US-13 now protects the patient-data APIs. Read [AUTHENTICATION.md](AUTHENTICATION.md)
for login, persistent profile ownership, deployment credentials and token settings. for login, persistent profile ownership, deployment credentials and token settings.
Configure the required keys/accounts before startup. The revised US-01 creation 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 ## 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 US-13 authentication and patient ownership are implemented as described in
[AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted [AUTHENTICATION.md](AUTHENTICATION.md). The account-to-profile association is persisted
in the patient service. US-14 assigned-professional read access remains pending; in the patient service. US-14 professional reads require predefined gateway assignments; professional
professional patient-data operations are denied until then. Updated context, tie writes are rejected. Updated context, tie
and rounding requirements in other stories remain to be implemented incrementally. and rounding requirements in other stories remain to be implemented incrementally.
## Automated acceptance tests ## Automated acceptance tests
@@ -29,6 +29,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
public HttpClient CreateDirectObservationClient() => observation!.CreateClient(); public HttpClient CreateDirectObservationClient() => observation!.CreateClient();
public HttpClient CreateDirectInsightsClient() => insights!.CreateClient(); public HttpClient CreateDirectInsightsClient() => insights!.CreateClient();
public AuthenticatedTestClient Authentication { get; } = new(); public AuthenticatedTestClient Authentication { get; } = new();
public Dictionary<string, string?> AdditionalGatewayConfiguration { get; } = new();
public async Task InitializeAsync() public async Task InitializeAsync()
{ {
@@ -76,7 +77,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
{ {
builder.UseEnvironment("Development"); builder.UseEnvironment("Development");
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); 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<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(), new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/", ["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })); ["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }));
@@ -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<ObservationApiFixture>
{
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<Guid> 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<Profile>())!.PatientId;
}
private async Task<Observation> 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<Observation>())!;
}
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<HttpResponseMessage> 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<Guid>())
})
{
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<AssignedPatient[]>())!;
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<Observation>());
}
[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(); }
}
}
@@ -42,14 +42,19 @@ public sealed class AuthenticationIntegrationTests
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
} }
[Fact] [Theory]
public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy() [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 authentication = new AuthenticatedTestClient();
var patient = Guid.NewGuid(); var patient = Guid.NewGuid();
try try
{ {
var configuration = authentication.Configuration(); 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" }) foreach (var service in new[] { "PatientProfile", "Observation", "Insights" })
configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/"; configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/";
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder => using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
@@ -73,13 +78,13 @@ public sealed class AuthenticationIntegrationTests
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
} }
public sealed class ReplacementHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) public sealed class ReplacementHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{ {
protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult( protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(
AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[] 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))); }, Scheme.Name)), Scheme.Name)));
} }
+6
View File
@@ -44,6 +44,12 @@ public sealed class AuthenticatedTestClient
values["Authentication:Accounts:256:AccountId"] = "professional"; values["Authentication:Accounts:256:AccountId"] = "professional";
values["Authentication:Accounts:256:PasswordHash"] = hash; values["Authentication:Accounts:256:PasswordHash"] = hash;
values["Authentication:Accounts:256:Role"] = "HealthcareProfessional"; 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; return values;
} }