Implement US-14 assigned professional read access
This commit is contained in:
1 parent
0ce9b2b168
commit
5996481081
11 files changed
+441
-24
No files matched your search
+59
-3
@@ -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.
|
||||
@@ -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 }));
|
||||
}
|
||||
@@ -15,6 +15,7 @@ public class Program
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddSingleton<PrototypeAccounts>();
|
||||
builder.Services.AddSingleton<ProfessionalAssignments>();
|
||||
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<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.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((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<PrototypeAccounts>();
|
||||
_ = app.Services.GetRequiredService<ProfessionalAssignments>();
|
||||
app.UseExceptionHandler();
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
|
||||
@@ -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<IAllowAnonymous>() 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); }
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user