From 0ce9b2b168fdb85fb14ed6490fc50d7aedaf3d35 Mon Sep 17 00:00:00 2001 From: Steffen Date: Mon, 5 Oct 2026 11:10:22 +0200 Subject: [PATCH] Implement US-13 patient authentication and persistent ownership --- deploy/api-gateway.env.example | 19 +- deploy/insights.env.example | 7 +- deploy/observation.env.example | 7 +- deploy/patient-profile.env.example | 6 +- deploy/systemd/healthapp-api-gateway.service | 2 + src/AUTHENTICATION.md | 130 ++++++++ .../Controllers/AuthenticationController.cs | 39 +++ .../Controllers/PatientController.cs | 7 + src/ApiGateway/Program.cs | 63 +++- .../InternalServiceAuthenticationHandler.cs | 29 ++ .../Security/PatientAccessMiddleware.cs | 67 +++++ src/ApiGateway/Security/PrototypeAccounts.cs | 39 +++ src/InsightsService/Program.cs | 27 +- src/ObservationService/Program.cs | 27 +- .../Application/PatientApplicationService.cs | 11 +- .../Application/PatientRepository.cs | 1 + .../ProfileAlreadyExistsException.cs | 5 + .../Controllers/PatientController.cs | 20 +- src/PatientProfileService/Domain/Patient.cs | 1 + ...2209_AccountProfileAssociation.Designer.cs | 69 +++++ ...0261005082209_AccountProfileAssociation.cs | 38 +++ .../PatientDbContextModelSnapshot.cs | 7 + .../Persistence/PatientDbContext.cs | 2 + .../Persistence/SqlPatientRepository.cs | 10 +- src/PatientProfileService/Program.cs | 13 + src/README.md | 27 +- .../Observation.AcceptanceTests.csproj | 3 + .../ObservationApiFixture.cs | 29 +- .../PatientAuthenticationTests.cs | 277 ++++++++++++++++++ .../AuthenticationIntegrationTests.cs | 97 ++++++ .../MeasurementGuidanceTests.cs | 7 +- .../PatientApiFixture.cs | 18 +- .../PatientProfile.AcceptanceTests.csproj | 3 + tests/Support/AuthenticatedTestClient.cs | 102 +++++++ tools/PasswordHash/PasswordHash.csproj | 11 + tools/PasswordHash/Program.cs | 11 + 36 files changed, 1203 insertions(+), 28 deletions(-) create mode 100644 src/AUTHENTICATION.md create mode 100644 src/ApiGateway/Controllers/AuthenticationController.cs create mode 100644 src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs create mode 100644 src/ApiGateway/Security/PatientAccessMiddleware.cs create mode 100644 src/ApiGateway/Security/PrototypeAccounts.cs create mode 100644 src/PatientProfileService/Application/ProfileAlreadyExistsException.cs create mode 100644 src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.Designer.cs create mode 100644 src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.cs create mode 100644 tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs create mode 100644 tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs create mode 100644 tests/Support/AuthenticatedTestClient.cs create mode 100644 tools/PasswordHash/PasswordHash.csproj create mode 100644 tools/PasswordHash/Program.cs diff --git a/deploy/api-gateway.env.example b/deploy/api-gateway.env.example index 976cf3b..bd42992 100644 --- a/deploy/api-gateway.env.example +++ b/deploy/api-gateway.env.example @@ -1,8 +1,21 @@ ASPNETCORE_ENVIRONMENT=Production -Services__PatientProfile__BaseUrl=http://patient-profile.example.test:5081/ +Services__PatientProfile__BaseUrl=https://patient-profile.example.test:5081/ ASPNETCORE_URLS=https://0.0.0.0:5443 Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx Kestrel__Certificates__Default__Password=REPLACE_ME -Services__Observation__BaseUrl=http://observation.example.test:5082/ +Services__Observation__BaseUrl=https://observation.example.test:5082/ -Services__Insights__BaseUrl=http://insights.example.test:5083/ +Services__Insights__BaseUrl=https://insights.example.test:5083/ + +Authentication__KeyDirectory=/var/lib/healthapp-api-gateway/keys +Authentication__TokenLifetimeMinutes=30 +# Account identifiers support ASCII letters, digits, hyphen and underscore. +Authentication__Accounts__0__AccountId=example-patient +Authentication__Accounts__0__Role=Patient +Authentication__Accounts__0__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH +# Use distinct randomly generated credentials of at least 32 characters. +Services__PatientProfile__Key=REPLACE_ME +Services__Observation__Key=REPLACE_ME +Services__Insights__Key=REPLACE_ME +InternalAccess__Observation__Key=REPLACE_ME +InternalAccess__Insights__Key=REPLACE_ME diff --git a/deploy/insights.env.example b/deploy/insights.env.example index a2fb415..4dbc642 100644 --- a/deploy/insights.env.example +++ b/deploy/insights.env.example @@ -1,3 +1,8 @@ ASPNETCORE_ENVIRONMENT=Production -ASPNETCORE_URLS=http://0.0.0.0:5083 +ASPNETCORE_URLS=https://0.0.0.0:5083 Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/ + +InternalAccess__GatewayKey=REPLACE_ME +Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx +Kestrel__Certificates__Default__Password=REPLACE_ME +Services__ApiGateway__Key=REPLACE_ME diff --git a/deploy/observation.env.example b/deploy/observation.env.example index feca36b..c68b9d2 100644 --- a/deploy/observation.env.example +++ b/deploy/observation.env.example @@ -1,4 +1,9 @@ ASPNETCORE_ENVIRONMENT=Production -ASPNETCORE_URLS=http://0.0.0.0:5082 +ASPNETCORE_URLS=https://0.0.0.0:5082 ConnectionStrings__ObservationDatabase="Host=database.example.test;Port=5432;Database=observations;Username=observations;Password=REPLACE_ME" Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/ + +InternalAccess__GatewayKey=REPLACE_ME +Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx +Kestrel__Certificates__Default__Password=REPLACE_ME +Services__ApiGateway__Key=REPLACE_ME diff --git a/deploy/patient-profile.env.example b/deploy/patient-profile.env.example index d585d46..fa2fe9f 100644 --- a/deploy/patient-profile.env.example +++ b/deploy/patient-profile.env.example @@ -1,3 +1,7 @@ ASPNETCORE_ENVIRONMENT=Production -ASPNETCORE_URLS=http://0.0.0.0:5081 +ASPNETCORE_URLS=https://0.0.0.0:5081 ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME" + +InternalAccess__GatewayKey=REPLACE_ME +Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx +Kestrel__Certificates__Default__Password=REPLACE_ME diff --git a/deploy/systemd/healthapp-api-gateway.service b/deploy/systemd/healthapp-api-gateway.service index 05911a3..52a6db7 100644 --- a/deploy/systemd/healthapp-api-gateway.service +++ b/deploy/systemd/healthapp-api-gateway.service @@ -4,6 +4,8 @@ Wants=network-online.target After=network-online.target [Service] +StateDirectory=healthapp-api-gateway +StateDirectoryMode=0700 Type=simple User=healthapp Group=healthapp diff --git a/src/AUTHENTICATION.md b/src/AUTHENTICATION.md new file mode 100644 index 0000000..c1c11c6 --- /dev/null +++ b/src/AUTHENTICATION.md @@ -0,0 +1,130 @@ +# US-13 prototype authentication + +The API gateway authenticates pre-created externally configured accounts. Login is +`POST /api/authentication/login` with `accountId` and `password`. A successful JSON +response contains `accessToken`, `tokenType: Bearer`, `expiresIn`, `accountId` and +trusted `role`; it contains no patient data or refresh token. Send the access token +as `Authorization: Bearer ` on subsequent patient-data requests. Invalid +credentials return the same `401` response for unknown accounts and wrong passwords. +Login responses cannot be cached. General measurement guidance remains public. + +## Mechanism and configuration + +Use ASP.NET Core's built-in bearer authentication and ticket protection, with +Data Protection's application name `HealthApp.ApiGateway` and the bearer purpose. +Tokens are opaque protected authentication tickets, not JWTs. The configured key +ring and framework purpose enforce the gateway trust boundary; only account ID, +role and authentication properties are protected inside a token. Do not share the +key ring with other applications/services. No custom cryptography, identity +microservice, account database or refresh-token mechanism is introduced. + +The gateway verifies passwords with ASP.NET Core `PasswordHasher` against +`Authentication:Accounts::{AccountId,Role,PasswordHash}`. Roles are `Patient` +or `HealthcareProfessional`, from trusted configuration. IDs support ASCII letters, +digits, hyphen and underscore, up to 128 characters. This keeps the internal account +lookup contract unambiguous. Provision credentials externally; no registration or +administration API is exposed. For provisioning, `tools/PasswordHash` reads a +password from standard input and emits its ASP.NET Core hash. Supply input securely +(e.g. redirect a permission-restricted temporary file), and protect the resulting +hash/configuration; neither belongs in Git. The tool needs no NuGet dependency. + +`Authentication:TokenLifetimeMinutes` defaults to 30; supported range is 1–1440. +`Authentication:KeyDirectory` is required. Keep its contents persistent through +restart/deployment and readable only by the gateway service account. The systemd +unit provides a mode-0700 state directory; example configuration points into it. +Keys are protected by filesystem permissions in this Linux prototype. Removing +keys invalidates tokens; preserve them for restart continuity. Accounts and +configuration are loaded at startup; after disabling accounts or changing roles, +old tokens can remain valid until their expiry. Immediate revocation is outside +this story. Missing/invalid/expired tokens return `401`; authenticate again after +expiry. Credential validation is not repeated for each operation. + +Before thesis measurement, record the lifetime, account/role mix, key persistence, +login frequency and expiry handling. Normally obtain tokens during workload setup +and reuse them; state explicitly whether login is measured. If tokens expire, +re-authentication is required. Keep these choices identical across variants. The +automated test helper logs in using real password verification and caches tokens; +its account-per-resource setup is not a prescribed measurement workload. + +## Ownership and profile creation + +The patient service owns the account association as `patient.account_id` with a +unique index. It remains application access data, outside tokens. The gateway +queries its protected `GET /api/patients/by-account/{accountId}` service API on each +request; that API is not forwarded as a public account-lookup route. An account +without a profile may log in and create one; its other own-data requests return +`404`. Patient operations are subject to the standard Patient authorization policy. + +`GET /api/patients/me` retrieves the caller’s own associated profile without needing +to know its generated identifier, including after a creation response was lost. +It returns `404` before profile creation. + +Profile creation derives `X-Account-Id` from the authenticated principal. The +gateway overwrites client input; the service accepts it only behind its gateway +credential. The profile and association are inserted in one atomic database save, +so failure rolls both back. The unique index arbitrates concurrent creation. A +completed creation, a retry after a lost response and a competing request cannot +create another profile; later attempts receive `409`. A retry after a failed +transaction may create the first profile. Profile identity remains persistent +through restarts. US-01's authenticated creation is included because US-13 depends +on a persistent, recoverable association. + +Apply the new patient migration before startup. Existing profiles retain a null +account association rather than being assigned to an arbitrary account. They are +not accessible to patient accounts until a trusted deployment operator explicitly +associates them with pre-created accounts. For synthetic experiments, provision a +fresh database via the authenticated creation flow. Do not infer ownership from +caller-supplied IDs or automatically assign historical profiles. + +For observation-ID requests, the gateway reads the observation through its service +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 +gateway's default authentication policy also protects future patient endpoints, +which must retain ownership checks when added. + +## Service and transport protection + +Use HTTPS for client and service traffic. Outside Development, gateway and service +requests over HTTP are rejected and outgoing service endpoints must be HTTPS. +Certificates use ordinary Kestrel configuration and normal platform validation; +no insecure certificate handler is provided. Configure DNS names/certificates for +separate machines. Development permits plain HTTP for local automated tests only. +Use network firewall rules to restrict service ports to trusted hosts as an +additional deployment control; the application credential checks still enforce +protection if a client reaches a service directly. + +Each service requires `InternalAccess:GatewayKey`, a random credential of at least +32 characters, matched by the gateway's `Services::Key`. Services reject +missing/wrong keys and client bearer tokens. Use distinct per-service gateway keys +in deployment. The gateway forwards only its own configured key; arbitrary client +identity headers are not propagated. Do not log these headers or tokens. + +Observation and Insights each have a separate `Services:ApiGateway:Key`, matched +by the gateway's `InternalAccess:Observation:Key` or `InternalAccess:Insights:Key`. +Their `X-Service-Key` authenticates an internal principal using an ASP.NET Core +handler. The Observation principal can only GET a patient profile by patient ID; +the Insights principal can only GET observation history by patient ID. Neither +can create/update/delete profiles or observations, query account associations or +call other protected routes. Both internal read paths still pass through the +gateway. Service credentials are separate from patient tokens and token keys. +Use independent random values, restrictive configuration-file permissions and +HTTPS; placeholder values in deployment examples deliberately fail validation. + +## Verification + +The acceptance suite exercises real HTTP hosts and PostgreSQL migrations. It covers +US-13's login, own access, missing/invalid/expired tokens, no-profile behaviour, +cross-patient reads/writes and observation ownership. Additional checks cover +caller-supplied account spoofing, persistent tokens/associations after restart, +duplicate/concurrent creation, unavailable-service recovery, direct service bypass, +internal-credential route restrictions, professional creation rejection and public +US-15 guidance. Existing functional assertions run through real token login rather +than a production authentication bypass. + +Framework reference: +https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.bearertoken.bearertokenoptions?view=aspnetcore-10.0 diff --git a/src/ApiGateway/Controllers/AuthenticationController.cs b/src/ApiGateway/Controllers/AuthenticationController.cs new file mode 100644 index 0000000..9cb0d1d --- /dev/null +++ b/src/ApiGateway/Controllers/AuthenticationController.cs @@ -0,0 +1,39 @@ +using System.ComponentModel.DataAnnotations; +using System.Security.Claims; +using ApiGateway.Security; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.BearerToken; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; + +namespace ApiGateway.Controllers; + +[ApiController] +[Route("api/authentication")] +public sealed class AuthenticationController(PrototypeAccounts accounts, + IOptionsMonitor options) : ControllerBase +{ + [AllowAnonymous] + [HttpPost("login")] + public IActionResult Login(LoginRequest request) + { + var account = accounts.Verify(request.AccountId, request.Password); + if (account is null) return Unauthorized(new { title = "Invalid credentials." }); + var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(ClaimTypes.NameIdentifier, account.AccountId), + new Claim(ClaimTypes.Role, account.Role) + }, "Bearer")); + var settings = options.Get("Bearer"); + var expiry = settings.TimeProvider!.GetUtcNow().Add(settings.BearerTokenExpiration); + // Use the framework's ticket protector and bearer validation. No refresh endpoint/token. + var ticket = new AuthenticationTicket(principal, new AuthenticationProperties { ExpiresUtc = expiry }, "Bearer"); + Response.Headers.CacheControl = "no-store"; + Response.Headers.Pragma = "no-cache"; + return Ok(new { accessToken = settings.BearerTokenProtector.Protect(ticket), tokenType = "Bearer", + expiresIn = (long)settings.BearerTokenExpiration.TotalSeconds, accountId = account.AccountId, role = account.Role }); + } + + public sealed record LoginRequest([Required] string AccountId, [Required] string Password); +} diff --git a/src/ApiGateway/Controllers/PatientController.cs b/src/ApiGateway/Controllers/PatientController.cs index 84e5920..9a4032b 100644 --- a/src/ApiGateway/Controllers/PatientController.cs +++ b/src/ApiGateway/Controllers/PatientController.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Mvc; +using System.Security.Claims; namespace ApiGateway.Controllers; @@ -10,6 +11,10 @@ public sealed class PatientController(IHttpClientFactory clients) : ControllerBa public Task CreatePatient(CancellationToken cancellationToken) => ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken); + [HttpGet("me")] + public Task GetOwnPatient(CancellationToken cancellationToken) => + ForwardAsync(HttpMethod.Get, "api/patients/by-account/" + Uri.EscapeDataString(User.FindFirstValue(ClaimTypes.NameIdentifier)!), cancellationToken); + [HttpGet("{patientId:guid}")] public Task GetPatient(Guid patientId, CancellationToken cancellationToken) => ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken); @@ -21,6 +26,8 @@ public sealed class PatientController(IHttpClientFactory clients) : ControllerBa private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken) { using var request = new HttpRequestMessage(method, path); + if (method == HttpMethod.Post) + request.Headers.Add("X-Account-Id", User.FindFirstValue(ClaimTypes.NameIdentifier)); if (method == HttpMethod.Post || method == HttpMethod.Put) { request.Content = new StreamContent(Request.Body); diff --git a/src/ApiGateway/Program.cs b/src/ApiGateway/Program.cs index b8fd876..2af8b38 100644 --- a/src/ApiGateway/Program.cs +++ b/src/ApiGateway/Program.cs @@ -1,3 +1,10 @@ +using ApiGateway.Security; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.BearerToken; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.DataProtection.KeyManagement; +using Microsoft.AspNetCore.DataProtection.Repositories; namespace ApiGateway; public class Program @@ -7,23 +14,73 @@ public class Program var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddProblemDetails(); + builder.Services.AddSingleton(); + builder.Services.AddAuthentication("ClientOrService") + .AddPolicyScheme("ClientOrService", null, options => options.ForwardDefaultSelector = context => + context.Request.Headers.ContainsKey("X-Service-Key") ? "InternalService" : "Bearer") + .AddBearerToken("Bearer", options => + { + 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.AddDataProtection().SetApplicationName("HealthApp.ApiGateway"); + builder.Services.AddOptions().Configure((options, configuration, logger) => + { + var keyDirectory = configuration["Authentication:KeyDirectory"]; + if (string.IsNullOrWhiteSpace(keyDirectory)) throw new InvalidOperationException("Authentication:KeyDirectory is required."); + options.XmlRepository = new FileSystemXmlRepository(new DirectoryInfo(keyDirectory), logger); + }); builder.Services.AddHttpClient("PatientProfile", (services, client) => - client.BaseAddress = GetBaseUri(services.GetRequiredService(), "PatientProfile")) + { + var configuration = services.GetRequiredService(); + client.BaseAddress = GetBaseUri(configuration, "PatientProfile"); + client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:PatientProfile:Key"]); + }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddHttpClient("Observation", (services, client) => - client.BaseAddress = GetBaseUri(services.GetRequiredService(), "Observation")) + { + var configuration = services.GetRequiredService(); + client.BaseAddress = GetBaseUri(configuration, "Observation"); + client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Observation:Key"]); + }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddHttpClient("Insights", (services, client) => - client.BaseAddress = GetBaseUri(services.GetRequiredService(), "Insights")) + { + var configuration = services.GetRequiredService(); + client.BaseAddress = GetBaseUri(configuration, "Insights"); + client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:Insights:Key"]); + }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); var app = builder.Build(); _ = GetBaseUri(app.Configuration, "PatientProfile"); _ = GetBaseUri(app.Configuration, "Observation"); _ = GetBaseUri(app.Configuration, "Insights"); + foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "InternalAccess:Observation:Key", "InternalAccess:Insights:Key" }) + if (string.IsNullOrWhiteSpace(app.Configuration[key]) || app.Configuration[key]!.Length < 32) + throw new InvalidOperationException($"{key} must contain at least 32 characters."); + if (string.IsNullOrWhiteSpace(app.Configuration["Authentication:KeyDirectory"])) + throw new InvalidOperationException("Authentication:KeyDirectory is required."); + var lifetime = app.Configuration.GetValue("Authentication:TokenLifetimeMinutes", 30); + if (lifetime <= 0 || lifetime > 1440) throw new InvalidOperationException("Token lifetime must be between 1 and 1440 minutes."); + if (!app.Environment.IsDevelopment()) + foreach (var service in new[] { "PatientProfile", "Observation", "Insights" }) + if (GetBaseUri(app.Configuration, service).Scheme != "https") + throw new InvalidOperationException("Production service endpoints must use HTTPS."); + _ = app.Services.GetRequiredService(); app.UseExceptionHandler(); + app.Use(async (context, next) => + { + if (!app.Environment.IsDevelopment() && !context.Request.IsHttps) { context.Response.StatusCode = 400; return; } + await next(context); + }); + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseMiddleware(); app.MapControllers(); app.Run(); } diff --git a/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs b/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs new file mode 100644 index 0000000..1fa7fac --- /dev/null +++ b/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs @@ -0,0 +1,29 @@ +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; + +namespace ApiGateway.Security; + +public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor options, + ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration) + : AuthenticationHandler(options, logger, encoder) +{ + protected override Task HandleAuthenticateAsync() + { + var supplied = Request.Headers["X-Service-Key"].ToString(); + foreach (var service in new[] { "Observation", "Insights" }) + { + var expected = configuration[$"InternalAccess:{service}:Key"]!; + if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected))) + { + var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Role, "Service"), + new Claim(ClaimTypes.NameIdentifier, service) }, Scheme.Name); + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name))); + } + } + return Task.FromResult(AuthenticateResult.Fail("Invalid service credential.")); + } +} diff --git a/src/ApiGateway/Security/PatientAccessMiddleware.cs b/src/ApiGateway/Security/PatientAccessMiddleware.cs new file mode 100644 index 0000000..e74cacc --- /dev/null +++ b/src/ApiGateway/Security/PatientAccessMiddleware.cs @@ -0,0 +1,67 @@ +using System.Net; +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Authorization; + +namespace ApiGateway.Security; + +public sealed class PatientAccessMiddleware(RequestDelegate next) +{ + public async Task InvokeAsync(HttpContext context, IHttpClientFactory clients, IAuthorizationService authorization) + { + if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) + { + await next(context); + return; + } + if (context.User.Identity?.IsAuthenticated != true) { context.Response.StatusCode = 401; return; } + var route = context.Request.Path.Value ?? ""; + var segments = route.Trim('/').Split('/'); + if (context.User.IsInRole("Service")) + { + var service = context.User.FindFirstValue(ClaimTypes.NameIdentifier); + var allowed = context.Request.Method == "GET" && segments.Length == (service == "Observation" ? 3 : 4) + && segments[0] == "api" && segments[1] == "patients" && Guid.TryParse(segments[2], out _) + && (service == "Observation" || segments[3] == "observations"); + if (!allowed) { context.Response.StatusCode = 403; return; } + 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")) + { + await next(context); + return; + } + 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 requestedPatient; + if (segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients" + && Guid.TryParse(segments[2], out requestedPatient)) { } + else if (segments.Length == 3 && segments[0] == "api" && segments[1] == "observations" + && Guid.TryParse(segments[2], out var observationId)) + { + using var response = await clients.CreateClient("Observation").GetAsync($"api/observations/{observationId}", context.RequestAborted); + if (response.StatusCode == HttpStatusCode.NotFound) { context.Response.StatusCode = 404; return; } + response.EnsureSuccessStatusCode(); + using var observation = JsonDocument.Parse(await response.Content.ReadAsStringAsync(context.RequestAborted)); + requestedPatient = observation.RootElement.GetProperty("patientId").GetGuid(); + } + else { context.Response.StatusCode = 404; return; } + if (requestedPatient != patientId) { context.Response.StatusCode = 404; return; } + await next(context); + } + catch (HttpRequestException) { await Results.Problem(statusCode: 502, title: "Ownership lookup is unavailable.").ExecuteAsync(context); } + catch (OperationCanceledException) when (!context.RequestAborted.IsCancellationRequested) + { await Results.Problem(statusCode: 504, title: "Ownership lookup timed out.").ExecuteAsync(context); } + } +} diff --git a/src/ApiGateway/Security/PrototypeAccounts.cs b/src/ApiGateway/Security/PrototypeAccounts.cs new file mode 100644 index 0000000..cbecf2e --- /dev/null +++ b/src/ApiGateway/Security/PrototypeAccounts.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Identity; + +namespace ApiGateway.Security; + +public sealed class PrototypeAccount +{ + public string AccountId { get; set; } = ""; + public string Role { get; set; } = "Patient"; + public string PasswordHash { get; set; } = ""; +} + +public sealed class PrototypeAccounts +{ + private readonly Dictionary accounts; + private readonly PasswordHasher hasher = new(); + private readonly PrototypeAccount dummy = new() { AccountId = "invalid" }; + + public PrototypeAccounts(IConfiguration configuration) + { + var configured = configuration.GetSection("Authentication:Accounts").Get() ?? []; + if (configured.Length == 0 || configured.Any(a => string.IsNullOrWhiteSpace(a.AccountId) || a.AccountId.Length > 128 || a.AccountId.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('-' or '_')) || string.IsNullOrWhiteSpace(a.PasswordHash) + || a.Role is not ("Patient" or "HealthcareProfessional"))) + throw new InvalidOperationException("Authentication accounts require an identifier, password hash and supported role."); + accounts = configured.ToDictionary(a => a.AccountId, StringComparer.Ordinal); + dummy.PasswordHash = hasher.HashPassword(dummy, Guid.NewGuid().ToString()); + } + + public PrototypeAccount? Verify(string accountId, string password) + { + var known = accounts.TryGetValue(accountId, out var account); + account ??= dummy; + try + { + var result = hasher.VerifyHashedPassword(account, account.PasswordHash, password); + return known && result != PasswordVerificationResult.Failed ? account : null; + } + catch (FormatException) { return null; } + } +} diff --git a/src/InsightsService/Program.cs b/src/InsightsService/Program.cs index 5c94783..f6145ae 100644 --- a/src/InsightsService/Program.cs +++ b/src/InsightsService/Program.cs @@ -1,3 +1,5 @@ +using System.Security.Cryptography; +using System.Text; using InsightsService.Application; using InsightsService.Clients; using InsightsService.Domain; @@ -14,11 +16,34 @@ public class Program builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddHttpClient((services, client) => - client.BaseAddress = GetGatewayUri(services.GetRequiredService())) + { + var configuration = services.GetRequiredService(); + client.BaseAddress = GetGatewayUri(configuration); + var serviceKey = configuration["Services:ApiGateway:Key"]; + if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32) + throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters."); + client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey); + }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); var app = builder.Build(); + if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https") + throw new InvalidOperationException("Production gateway endpoints must use HTTPS."); _ = GetGatewayUri(app.Configuration); + var outgoingKey = app.Configuration["Services:ApiGateway:Key"]; + if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32) + throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters."); + var gatewayKey = app.Configuration["InternalAccess:GatewayKey"]; + if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32) + throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters."); app.UseExceptionHandler(); + app.Use(async (context, next) => + { + var supplied = context.Request.Headers["X-Gateway-Key"].ToString(); + if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) || + !CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey))) + { context.Response.StatusCode = 401; return; } + await next(context); + }); app.MapControllers(); app.Run(); } diff --git a/src/ObservationService/Program.cs b/src/ObservationService/Program.cs index efe2b4a..4de5b9b 100644 --- a/src/ObservationService/Program.cs +++ b/src/ObservationService/Program.cs @@ -1,3 +1,5 @@ +using System.Security.Cryptography; +using System.Text; using Microsoft.EntityFrameworkCore; using ObservationService.Application; using ObservationService.Persistence; @@ -16,7 +18,14 @@ public class Program builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHttpClient("ApiGateway", (services, client) => - client.BaseAddress = GetGatewayUri(services.GetRequiredService())) + { + var configuration = services.GetRequiredService(); + client.BaseAddress = GetGatewayUri(configuration); + var serviceKey = configuration["Services:ApiGateway:Key"]; + if (string.IsNullOrWhiteSpace(serviceKey) || serviceKey.Length < 32) + throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters."); + client.DefaultRequestHeaders.Add("X-Service-Key", serviceKey); + }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); var app = builder.Build(); @@ -30,8 +39,24 @@ public class Program return; } + if (!app.Environment.IsDevelopment() && GetGatewayUri(app.Configuration).Scheme != "https") + throw new InvalidOperationException("Production gateway endpoints must use HTTPS."); _ = GetGatewayUri(app.Configuration); + var outgoingKey = app.Configuration["Services:ApiGateway:Key"]; + if (string.IsNullOrWhiteSpace(outgoingKey) || outgoingKey.Length < 32) + throw new InvalidOperationException("Services:ApiGateway:Key must contain at least 32 characters."); + var gatewayKey = app.Configuration["InternalAccess:GatewayKey"]; + if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32) + throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters."); app.UseExceptionHandler(); + app.Use(async (context, next) => + { + var supplied = context.Request.Headers["X-Gateway-Key"].ToString(); + if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) || + !CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey))) + { context.Response.StatusCode = 401; return; } + await next(context); + }); app.MapControllers(); await app.RunAsync(); } diff --git a/src/PatientProfileService/Application/PatientApplicationService.cs b/src/PatientProfileService/Application/PatientApplicationService.cs index 30593f9..3548906 100644 --- a/src/PatientProfileService/Application/PatientApplicationService.cs +++ b/src/PatientProfileService/Application/PatientApplicationService.cs @@ -5,17 +5,21 @@ namespace PatientProfileService.Application; public sealed class PatientApplicationService(PatientRepository repository) { - public Task CreatePatientAsync(CreatePatientRequest request, CancellationToken cancellationToken) + public async Task CreatePatientAsync(CreatePatientRequest request, string accountId, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrWhiteSpace(request.Name); + ArgumentException.ThrowIfNullOrWhiteSpace(accountId); + if (await repository.FindByAccountIdAsync(accountId, cancellationToken) is not null) + throw new ProfileAlreadyExistsException(); if (request.DateOfBirth is null) throw new ArgumentException("A date of birth is required.", nameof(request)); // The documented TIMESTAMP columns store UTC without a time-zone component. var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified); - return repository.SaveAsync(new Patient + return await repository.SaveAsync(new Patient { PatientId = Guid.NewGuid(), + AccountId = accountId, Name = request.Name, DateOfBirth = request.DateOfBirth.Value, ContactInfo = request.ContactInfo, @@ -24,6 +28,9 @@ public sealed class PatientApplicationService(PatientRepository repository) }, cancellationToken); } + public Task GetByAccountAsync(string accountId, CancellationToken cancellationToken) => + repository.FindByAccountIdAsync(accountId, cancellationToken); + public Task GetPatientAsync(Guid patientId, CancellationToken cancellationToken) => repository.FindByIdAsync(patientId, cancellationToken); diff --git a/src/PatientProfileService/Application/PatientRepository.cs b/src/PatientProfileService/Application/PatientRepository.cs index 40f889f..2d24e3e 100644 --- a/src/PatientProfileService/Application/PatientRepository.cs +++ b/src/PatientProfileService/Application/PatientRepository.cs @@ -4,6 +4,7 @@ namespace PatientProfileService.Application; public interface PatientRepository { + Task FindByAccountIdAsync(string accountId, CancellationToken cancellationToken); Task SaveAsync(Patient patient, CancellationToken cancellationToken); Task FindByIdAsync(Guid patientId, CancellationToken cancellationToken); Task UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken); diff --git a/src/PatientProfileService/Application/ProfileAlreadyExistsException.cs b/src/PatientProfileService/Application/ProfileAlreadyExistsException.cs new file mode 100644 index 0000000..e9f40db --- /dev/null +++ b/src/PatientProfileService/Application/ProfileAlreadyExistsException.cs @@ -0,0 +1,5 @@ +namespace PatientProfileService.Application; + +public sealed class ProfileAlreadyExistsException : Exception +{ +} diff --git a/src/PatientProfileService/Controllers/PatientController.cs b/src/PatientProfileService/Controllers/PatientController.cs index 1018086..f03f791 100644 --- a/src/PatientProfileService/Controllers/PatientController.cs +++ b/src/PatientProfileService/Controllers/PatientController.cs @@ -12,8 +12,24 @@ public sealed class PatientController(PatientApplicationService service) : Contr [HttpPost] public async Task> CreatePatient(CreatePatientRequest request, CancellationToken cancellationToken) { - var patient = await service.CreatePatientAsync(request, cancellationToken); - return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient)); + var accountId = Request.Headers["X-Account-Id"].ToString(); + if (string.IsNullOrWhiteSpace(accountId)) return BadRequest(); + try + { + var patient = await service.CreatePatientAsync(request, accountId, cancellationToken); + return CreatedAtAction(nameof(GetPatient), new { patientId = patient.PatientId }, ToDto(patient)); + } + catch (ProfileAlreadyExistsException) + { + return Conflict(new { title = "A profile already exists for this account." }); + } + } + + [HttpGet("by-account/{accountId}")] + public async Task> GetByAccount(string accountId, CancellationToken cancellationToken) + { + var patient = await service.GetByAccountAsync(accountId, cancellationToken); + return patient is null ? NotFound() : Ok(ToDto(patient)); } [HttpGet("{patientId:guid}")] diff --git a/src/PatientProfileService/Domain/Patient.cs b/src/PatientProfileService/Domain/Patient.cs index c36ace6..0c4f84f 100644 --- a/src/PatientProfileService/Domain/Patient.cs +++ b/src/PatientProfileService/Domain/Patient.cs @@ -2,6 +2,7 @@ namespace PatientProfileService.Domain; public sealed class Patient { + public string? AccountId { get; set; } public Guid PatientId { get; set; } public string Name { get; set; } = ""; public DateOnly DateOfBirth { get; set; } diff --git a/src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.Designer.cs b/src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.Designer.cs new file mode 100644 index 0000000..8d12aa2 --- /dev/null +++ b/src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.Designer.cs @@ -0,0 +1,69 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using PatientProfileService.Persistence; + +#nullable disable + +namespace PatientProfileService.Persistence.Migrations +{ + [DbContext(typeof(PatientDbContext))] + [Migration("20261005082209_AccountProfileAssociation")] + partial class AccountProfileAssociation + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("PatientProfileService.Domain.Patient", b => + { + b.Property("PatientId") + .HasColumnType("uuid") + .HasColumnName("patient_id"); + + b.Property("AccountId") + .HasColumnType("text") + .HasColumnName("account_id"); + + b.Property("ContactInfo") + .HasColumnType("character varying") + .HasColumnName("contact_info"); + + b.Property("CreatedAt") + .HasColumnType("timestamp without time zone") + .HasColumnName("created_at"); + + b.Property("DateOfBirth") + .HasColumnType("date") + .HasColumnName("date_of_birth"); + + b.Property("Name") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("name"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp without time zone") + .HasColumnName("updated_at"); + + b.HasKey("PatientId"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.ToTable("patient", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.cs b/src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.cs new file mode 100644 index 0000000..391f17b --- /dev/null +++ b/src/PatientProfileService/Persistence/Migrations/20261005082209_AccountProfileAssociation.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace PatientProfileService.Persistence.Migrations +{ + /// + public partial class AccountProfileAssociation : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "account_id", + table: "patient", + type: "text", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_patient_account_id", + table: "patient", + column: "account_id", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_patient_account_id", + table: "patient"); + + migrationBuilder.DropColumn( + name: "account_id", + table: "patient"); + } + } +} diff --git a/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs b/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs index d8edb4d..526e7fe 100644 --- a/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs +++ b/src/PatientProfileService/Persistence/Migrations/PatientDbContextModelSnapshot.cs @@ -28,6 +28,10 @@ namespace PatientProfileService.Persistence.Migrations .HasColumnType("uuid") .HasColumnName("patient_id"); + b.Property("AccountId") + .HasColumnType("text") + .HasColumnName("account_id"); + b.Property("ContactInfo") .HasColumnType("character varying") .HasColumnName("contact_info"); @@ -51,6 +55,9 @@ namespace PatientProfileService.Persistence.Migrations b.HasKey("PatientId"); + b.HasIndex("AccountId") + .IsUnique(); + b.ToTable("patient", (string)null); }); #pragma warning restore 612, 618 diff --git a/src/PatientProfileService/Persistence/PatientDbContext.cs b/src/PatientProfileService/Persistence/PatientDbContext.cs index 794ab62..12fba1d 100644 --- a/src/PatientProfileService/Persistence/PatientDbContext.cs +++ b/src/PatientProfileService/Persistence/PatientDbContext.cs @@ -12,6 +12,8 @@ public sealed class PatientDbContext(DbContextOptions options) var patient = modelBuilder.Entity(); patient.ToTable("patient"); patient.HasKey(p => p.PatientId); + patient.Property(p => p.AccountId).HasColumnName("account_id"); + patient.HasIndex(p => p.AccountId).IsUnique(); patient.Property(p => p.PatientId).HasColumnName("patient_id").ValueGeneratedNever(); patient.Property(p => p.Name).HasColumnName("name").HasColumnType("character varying").IsRequired(); patient.Property(p => p.DateOfBirth).HasColumnName("date_of_birth").HasColumnType("date"); diff --git a/src/PatientProfileService/Persistence/SqlPatientRepository.cs b/src/PatientProfileService/Persistence/SqlPatientRepository.cs index 27641b4..e8d38cf 100644 --- a/src/PatientProfileService/Persistence/SqlPatientRepository.cs +++ b/src/PatientProfileService/Persistence/SqlPatientRepository.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Npgsql; using PatientProfileService.Application; using PatientProfileService.Domain; @@ -9,10 +10,17 @@ public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepositor public async Task SaveAsync(Patient patient, CancellationToken cancellationToken) { db.Patients.Add(patient); - await db.SaveChangesAsync(cancellationToken); + try { await db.SaveChangesAsync(cancellationToken); } + catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: "23505", ConstraintName: "IX_patient_account_id" }) + { + throw new ProfileAlreadyExistsException(); + } return patient; } + public Task FindByAccountIdAsync(string accountId, CancellationToken cancellationToken) => + db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.AccountId == accountId, cancellationToken); + public Task FindByIdAsync(Guid patientId, CancellationToken cancellationToken) => db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken); diff --git a/src/PatientProfileService/Program.cs b/src/PatientProfileService/Program.cs index 2919489..67eb5c6 100644 --- a/src/PatientProfileService/Program.cs +++ b/src/PatientProfileService/Program.cs @@ -1,3 +1,5 @@ +using System.Security.Cryptography; +using System.Text; using Microsoft.EntityFrameworkCore; using PatientProfileService.Application; using PatientProfileService.Persistence; @@ -27,7 +29,18 @@ public class Program return; } + var gatewayKey = app.Configuration["InternalAccess:GatewayKey"]; + if (string.IsNullOrWhiteSpace(gatewayKey) || gatewayKey.Length < 32) + throw new InvalidOperationException("InternalAccess:GatewayKey must contain at least 32 characters."); app.UseExceptionHandler(); + app.Use(async (context, next) => + { + var supplied = context.Request.Headers["X-Gateway-Key"].ToString(); + if ((!app.Environment.IsDevelopment() && !context.Request.IsHttps) || + !CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(gatewayKey))) + { context.Response.StatusCode = 401; return; } + await next(context); + }); app.MapControllers(); await app.RunAsync(); } diff --git a/src/README.md b/src/README.md index 1f7b274..9573a74 100644 --- a/src/README.md +++ b/src/README.md @@ -1,11 +1,21 @@ -# US-01–US-10: Patient profiles and blood-pressure observations +# Patient profiles, observations, insights and authentication -Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway, Patient/Profile service, Observation Service, and Insights Service are separate executables and can run on separate machines. Patient/Profile and Observation each own a database. Insights calculates on demand without persistence, following `Docs/Requirements/US_10_Correction` and `Docs/Architecture/us10-insights-correction.md`. +Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway, Patient/Profile service, Observation Service, and Insights Service are separate executables and can run on separate machines. Patient/Profile and Observation each own a database. Insights calculates on demand without persistence, following `Docs/Architecture/us10-insights-correction.md`. The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns. +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. + ## Build and run +Load external service configuration using the updated `deploy/*.env.example` templates. +Use HTTPS certificates for all production endpoints. For local HTTP development +only, set `ASPNETCORE_ENVIRONMENT=Development` on each process; all credentials and +the gateway key directory are still required. + Install a .NET 10 SDK and provision an empty PostgreSQL database owned by the Patient/Profile service's database user. From the repository root: ```bash @@ -38,9 +48,16 @@ Send requests to the gateway: ```bash curl -i http://127.0.0.1:5080/api/patients \ -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer YOUR_LOGIN_TOKEN' \ -d '{"name":"Steffen Example","dateOfBirth":"1980-01-01","contactInfo":"steffen@example.test"}' ``` +`POST /api/authentication/login` accepts `accountId` and `password` and returns a +protected access token. Include `Authorization: Bearer YOUR_LOGIN_TOKEN` on each +patient-data request below. Initial profile creation is permitted once per patient +account; repeated/concurrent attempts report `409`. `GET /api/patients/me` retrieves +the account’s profile when its generated identifier is not yet known. + `POST /api/patients` returns `201 Created`, a relative `Location: /api/patients/{patientId}` header, and a JSON profile containing `patientId`, `name`, `dateOfBirth`, and `contactInfo`. Identifiers are generated UUIDs and the database primary key enforces uniqueness. Names must be nonblank; dates of birth must be supplied as valid `YYYY-MM-DD` dates. Invalid requests return `400` validation problem details and do not create profiles. Contact information is optional because US-01 does not require it. `GET /api/patients/{patientId}` retrieves the persisted profile, or returns `404` when absent. Retrieval is included because US-01 explicitly requires it. The gateway returns `502` for connection failures and `504` for upstream timeouts. @@ -73,7 +90,11 @@ The independent Insights Service follows the documented controller/application-s US-10 tests use all four HTTP hosts and the existing separate patient/observation test databases. They cover all five acceptance scenarios, fractional averages, patient and inclusive-period filtering, equal/offset bounds, corrections/deletions, restart, malformed/missing periods, and unavailable observation retrieval. Insights introduces no external dependencies. Trend calculation remains outside this story. -Authentication and access control are defined in US-13, US-14 and `Docs/Design/authentication-and-access-control-design.md`, and remain to be implemented as separate stories, as explicitly instructed. These endpoints currently have no access restrictions. +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 +and rounding requirements in other stories remain to be implemented incrementally. ## Automated acceptance tests diff --git a/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj b/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj index 31ff829..15b4d16 100644 --- a/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj +++ b/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj @@ -16,4 +16,7 @@ + + + diff --git a/tests/Observation.AcceptanceTests/ObservationApiFixture.cs b/tests/Observation.AcceptanceTests/ObservationApiFixture.cs index b7d297b..6315012 100644 --- a/tests/Observation.AcceptanceTests/ObservationApiFixture.cs +++ b/tests/Observation.AcceptanceTests/ObservationApiFixture.cs @@ -1,3 +1,5 @@ +using Microsoft.AspNetCore.Authentication.BearerToken; +using HealthApp.TestSupport; using Microsoft.AspNetCore.Hosting; using System.Net; using Microsoft.AspNetCore.Mvc.Testing; @@ -22,6 +24,11 @@ public sealed class ObservationApiFixture : IAsyncLifetime private WebApplicationFactory? gateway; public string ConnectionString { get; private set; } = ""; public HttpClient Client { get; private set; } = null!; + public HttpClient RawClient { get; private set; } = null!; + public HttpClient CreateDirectPatientClient() => service!.CreateClient(); + public HttpClient CreateDirectObservationClient() => observation!.CreateClient(); + public HttpClient CreateDirectInsightsClient() => insights!.CreateClient(); + public AuthenticatedTestClient Authentication { get; } = new(); public async Task InitializeAsync() { @@ -57,31 +64,39 @@ public sealed class ObservationApiFixture : IAsyncLifetime { service = new WebApplicationFactory().WithWebHostBuilder(builder => { + builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( - new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString })); + new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey })); }); service.UseKestrel(0); using var serviceClient = service.CreateClient(); gateway = new WebApplicationFactory().WithWebHostBuilder(builder => { + builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); - builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( + builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).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/" })); }); + gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services => + services.PostConfigure("Bearer", options => options.TimeProvider = Authentication.Clock))); gateway.UseKestrel(0); - Client = gateway.CreateClient(); + RawClient = gateway.CreateClient(); + Client = Authentication.Wrap(RawClient); observation = new WebApplicationFactory().WithWebHostBuilder(builder => { + builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( new Dictionary { ["ConnectionStrings:ObservationDatabase"] = ObservationConnectionString, - ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() + ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), + ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, + ["Services:ApiGateway:Key"] = Authentication.ObservationServiceKey })); }); observation.UseKestrel(0); @@ -89,9 +104,10 @@ public sealed class ObservationApiFixture : IAsyncLifetime gateway.Services.GetRequiredService()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString(); insights = new WebApplicationFactory().WithWebHostBuilder(builder => { + builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( - new Dictionary { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() })); + new Dictionary { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, ["Services:ApiGateway:Key"] = Authentication.InsightsServiceKey })); }); insights.UseKestrel(0); using var insightsClient = insights.CreateClient(); @@ -101,6 +117,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime public async Task RestartHostsAsync() { Client.Dispose(); + RawClient.Dispose(); await insights!.DisposeAsync(); if (observation is not null) await observation.DisposeAsync(); await gateway!.DisposeAsync(); @@ -123,10 +140,12 @@ public sealed class ObservationApiFixture : IAsyncLifetime public async Task DisposeAsync() { Client?.Dispose(); + RawClient?.Dispose(); if (insights is not null) await insights.DisposeAsync(); if (observation is not null) await observation.DisposeAsync(); if (gateway is not null) await gateway.DisposeAsync(); if (service is not null) await service.DisposeAsync(); + if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true); if (string.IsNullOrEmpty(adminConnectionString)) return; NpgsqlConnection.ClearAllPools(); diff --git a/tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs b/tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs new file mode 100644 index 0000000..b8ae03e --- /dev/null +++ b/tests/Observation.AcceptanceTests/PatientAuthenticationTests.cs @@ -0,0 +1,277 @@ +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.BadGateway, 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 Direct_services_reject_client_tokens_missing_keys_and_forged_keys() + { + var patient = await Patient(); + foreach (var client in new[] { fixture.CreateDirectPatientClient(), fixture.CreateDirectObservationClient(), fixture.CreateDirectInsightsClient() }) + { + using (client) + { + client.DefaultRequestHeaders.Authorization = new("Bearer", patient.Token); + foreach (var key in new string?[] { null, "forged" }) + { + client.DefaultRequestHeaders.Remove("X-Gateway-Key"); + if (key is not null) client.DefaultRequestHeaders.Add("X-Gateway-Key", key); + using var response = await client.GetAsync($"/api/patients/{patient.PatientId}"); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + } + } + } + + [Fact] + public async Task Service_credentials_are_limited_to_their_documented_read_calls() + { + using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) }; + request.Headers.Add("X-Service-Key", fixture.Authentication.ObservationServiceKey); + using var response = await fixture.RawClient.SendAsync(request); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + using var forbidden = new HttpRequestMessage(HttpMethod.Get, "/api/patients/by-account/test-0"); + forbidden.Headers.Add("X-Service-Key", fixture.Authentication.InsightsServiceKey); + using var rejected = await fixture.RawClient.SendAsync(forbidden); + Assert.Equal(HttpStatusCode.Forbidden, rejected.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/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs b/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs new file mode 100644 index 0000000..588835f --- /dev/null +++ b/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs @@ -0,0 +1,97 @@ +using System.Net; +using System.Security.Claims; +using System.Text; +using System.Text.Encodings.Web; +using HealthApp.TestSupport; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Xunit; + +namespace PatientProfile.AcceptanceTests; + +public sealed class AuthenticationIntegrationTests +{ + [Fact] + public async Task Production_gateway_rejects_plain_http_even_for_login_and_public_guidance() + { + var authentication = new AuthenticatedTestClient(); + try + { + var configuration = authentication.Configuration(); + foreach (var service in new[] { "PatientProfile", "Observation", "Insights" }) + configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/"; + using var host = new WebApplicationFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment("Production"); + builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration)); + }); + using var http = host.CreateClient(); + using var guidance = await http.GetAsync("/api/measurement-guidance"); + Assert.Equal(HttpStatusCode.BadRequest, guidance.StatusCode); + using var login = await http.PostAsync("/api/authentication/login", new StringContent("{}", Encoding.UTF8, "application/json")); + Assert.Equal(HttpStatusCode.BadRequest, login.StatusCode); + using var https = host.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") }); + using var available = await https.GetAsync("/api/measurement-guidance"); + Assert.Equal(HttpStatusCode.OK, available.StatusCode); + } + finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } + } + + [Fact] + public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy() + { + var authentication = new AuthenticatedTestClient(); + var patient = Guid.NewGuid(); + try + { + var configuration = authentication.Configuration(); + foreach (var service in new[] { "PatientProfile", "Observation", "Insights" }) + configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/"; + using var host = new WebApplicationFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment("Development"); + builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration)); + builder.ConfigureServices(services => + { + services.AddAuthentication().AddScheme("Replacement", null); + services.PostConfigure("ClientOrService", options => options.ForwardDefaultSelector = _ => "Replacement"); + services.AddHttpClient("PatientProfile").ConfigurePrimaryHttpMessageHandler(() => new PatientHandler(patient)); + }); + }); + using var client = host.CreateClient(); + using var own = await client.GetAsync($"/api/patients/{patient}"); + Assert.Equal(HttpStatusCode.OK, own.StatusCode); + using var other = await client.GetAsync($"/api/patients/{Guid.NewGuid()}"); + Assert.Equal(HttpStatusCode.NotFound, other.StatusCode); + Assert.Empty(await other.Content.ReadAsStringAsync()); + } + finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } + } + + public sealed class ReplacementHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) + : 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") + }, Scheme.Name)), Scheme.Name))); + } + + private sealed class PatientHandler(Guid patientId) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Assert.True(request.Headers.Contains("X-Gateway-Key")); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent($"{{\"patientId\":\"{patientId}\"}}", Encoding.UTF8, "application/json") + }); + } + } +} diff --git a/tests/PatientProfile.AcceptanceTests/MeasurementGuidanceTests.cs b/tests/PatientProfile.AcceptanceTests/MeasurementGuidanceTests.cs index 6bb427b..b9a3359 100644 --- a/tests/PatientProfile.AcceptanceTests/MeasurementGuidanceTests.cs +++ b/tests/PatientProfile.AcceptanceTests/MeasurementGuidanceTests.cs @@ -1,4 +1,6 @@ using System.Net; +using HealthApp.TestSupport; +using Microsoft.AspNetCore.Hosting; using System.Text.Json; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.Configuration; @@ -12,12 +14,14 @@ public sealed class MeasurementGuidanceTests : IDisposable private readonly WebApplicationFactory host; private readonly HttpClient client; private int upstreamCalls; + private readonly AuthenticatedTestClient authentication = new(); public MeasurementGuidanceTests() { host = new WebApplicationFactory().WithWebHostBuilder(builder => { - builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection( + builder.UseEnvironment("Development"); + builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(authentication.Configuration()).AddInMemoryCollection( new Dictionary { ["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/", @@ -118,6 +122,7 @@ public sealed class MeasurementGuidanceTests : IDisposable { client.Dispose(); host.Dispose(); + if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); } private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler diff --git a/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs b/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs index c36b6d1..18115ef 100644 --- a/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs +++ b/tests/PatientProfile.AcceptanceTests/PatientApiFixture.cs @@ -1,3 +1,6 @@ +using Microsoft.AspNetCore.Authentication.BearerToken; +using Microsoft.Extensions.DependencyInjection; +using HealthApp.TestSupport; using Microsoft.AspNetCore.Hosting; using System.Net; using Microsoft.AspNetCore.Mvc.Testing; @@ -17,6 +20,8 @@ public sealed class PatientApiFixture : IAsyncLifetime private WebApplicationFactory? gateway; public string ConnectionString { get; private set; } = ""; public HttpClient Client { get; private set; } = null!; + public HttpClient RawClient { get; private set; } = null!; + public AuthenticatedTestClient Authentication { get; } = new(); public async Task InitializeAsync() { @@ -42,24 +47,29 @@ public sealed class PatientApiFixture : IAsyncLifetime { service = new WebApplicationFactory().WithWebHostBuilder(builder => { + builder.UseEnvironment("Development"); builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( - new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString })); + new Dictionary { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey })); }); service.UseKestrel(0); using var serviceClient = service.CreateClient(); gateway = new WebApplicationFactory().WithWebHostBuilder(builder => - builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection( + builder.UseEnvironment("Development").ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).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/" }))); - Client = gateway.CreateClient(); + gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services => + services.PostConfigure("Bearer", options => options.TimeProvider = Authentication.Clock))); + RawClient = gateway.CreateClient(); + Client = Authentication.Wrap(RawClient); } public async Task RestartHostsAsync() { Client.Dispose(); + RawClient.Dispose(); await gateway!.DisposeAsync(); await service!.DisposeAsync(); StartHosts(); @@ -68,8 +78,10 @@ public sealed class PatientApiFixture : IAsyncLifetime public async Task DisposeAsync() { Client?.Dispose(); + RawClient?.Dispose(); if (gateway is not null) await gateway.DisposeAsync(); if (service is not null) await service.DisposeAsync(); + if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true); if (string.IsNullOrEmpty(adminConnectionString)) return; NpgsqlConnection.ClearAllPools(); diff --git a/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj b/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj index f945f2c..244d3e4 100644 --- a/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj +++ b/tests/PatientProfile.AcceptanceTests/PatientProfile.AcceptanceTests.csproj @@ -14,4 +14,7 @@ + + + diff --git a/tests/Support/AuthenticatedTestClient.cs b/tests/Support/AuthenticatedTestClient.cs new file mode 100644 index 0000000..3b0d911 --- /dev/null +++ b/tests/Support/AuthenticatedTestClient.cs @@ -0,0 +1,102 @@ +using System.Collections.Concurrent; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using ApiGateway.Security; +using Microsoft.AspNetCore.Identity; + +namespace HealthApp.TestSupport; + +// Existing functional tests use real login and an authorised account for each resource. +// Security tests use RawClient instead to exercise rejected requests explicitly. +public sealed class AuthenticatedTestClient +{ + public const string Password = "synthetic-test-password"; + public readonly string GatewayKey = new('g', 48); + public readonly string ObservationServiceKey = new('o', 48); + public readonly string InsightsServiceKey = new('i', 48); + public TestClock Clock { get; } = new(); + public string KeyDirectory { get; } = Path.Combine(Path.GetTempPath(), "healthapp-keys-" + Guid.NewGuid()); + public ConcurrentDictionary PatientAccounts { get; } = new(); + private readonly ConcurrentDictionary observationAccounts = new(); + private readonly ConcurrentDictionary tokens = new(); + private int accountNumber; + private string lastAccount = "test-0"; + private readonly string hash = new PasswordHasher().HashPassword(new(), Password); + + public Dictionary Configuration() + { + var values = new Dictionary + { + ["Authentication:KeyDirectory"] = KeyDirectory, + ["Services:PatientProfile:Key"] = GatewayKey, + ["Services:Observation:Key"] = GatewayKey, + ["Services:Insights:Key"] = GatewayKey, + ["InternalAccess:Observation:Key"] = ObservationServiceKey, + ["InternalAccess:Insights:Key"] = InsightsServiceKey + }; + for (var i = 0; i < 256; i++) + { + values[$"Authentication:Accounts:{i}:AccountId"] = "test-" + i; + values[$"Authentication:Accounts:{i}:PasswordHash"] = hash; + values[$"Authentication:Accounts:{i}:Role"] = "Patient"; + } + values["Authentication:Accounts:256:AccountId"] = "professional"; + values["Authentication:Accounts:256:PasswordHash"] = hash; + values["Authentication:Accounts:256:Role"] = "HealthcareProfessional"; + return values; + } + + public HttpClient Wrap(HttpClient raw) => new(new Handler(this, raw)) { BaseAddress = raw.BaseAddress }; + + public static async Task LoginAsync(HttpClient raw, string account = "test-0", string password = Password) + { + using var response = await raw.PostAsJsonAsync("/api/authentication/login", new { accountId = account, password }); + response.EnsureSuccessStatusCode(); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("accessToken").GetString()!; + } + + private sealed class Handler(AuthenticatedTestClient owner, HttpClient raw) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var path = request.RequestUri!.AbsolutePath; + var parts = path.Trim('/').Split('/'); + var account = owner.lastAccount; + if (path == "/api/patients" && request.Method == HttpMethod.Post) + account = "test-" + Interlocked.Increment(ref owner.accountNumber); + else if (parts.Length >= 3 && Guid.TryParse(parts[2], out var id)) + { + var map = parts[1] == "patients" ? owner.PatientAccounts : owner.observationAccounts; + if (map.TryGetValue(id, out var found)) account = found; + } + if (!owner.tokens.TryGetValue(account, out var token)) + { + token = await LoginAsync(raw, account); + owner.tokens[account] = token; + } + using var forwarded = new HttpRequestMessage(request.Method, request.RequestUri) { Content = request.Content }; + foreach (var header in request.Headers) forwarded.Headers.TryAddWithoutValidation(header.Key, header.Value); + forwarded.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + var response = await raw.SendAsync(forwarded, cancellationToken); + if (response.IsSuccessStatusCode && request.Method == HttpMethod.Post) + { + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)); + if (json.RootElement.TryGetProperty("patientId", out var patient)) + owner.PatientAccounts[patient.GetGuid()] = account; + if (json.RootElement.TryGetProperty("observationId", out var observation)) + owner.observationAccounts[observation.GetGuid()] = account; + owner.lastAccount = account; + } + return response; + } + } +} + +public sealed class TestClock : TimeProvider +{ + private DateTimeOffset now = DateTimeOffset.UtcNow; + public override DateTimeOffset GetUtcNow() => now; + public void Advance(TimeSpan span) => now += span; +} diff --git a/tools/PasswordHash/PasswordHash.csproj b/tools/PasswordHash/PasswordHash.csproj new file mode 100644 index 0000000..b22cee9 --- /dev/null +++ b/tools/PasswordHash/PasswordHash.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + diff --git a/tools/PasswordHash/Program.cs b/tools/PasswordHash/Program.cs new file mode 100644 index 0000000..05fe123 --- /dev/null +++ b/tools/PasswordHash/Program.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Identity; + +// Read from standard input, never from a command-line argument or environment dump. +var password = Console.ReadLine(); +if (string.IsNullOrEmpty(password)) +{ + Console.Error.WriteLine("Supply a nonempty password on standard input."); + return 1; +} +Console.WriteLine(new PasswordHasher().HashPassword(new object(), password)); +return 0;