diff --git a/HealthApp.slnx b/HealthApp.slnx index c2f0b6f..b99c2cf 100644 --- a/HealthApp.slnx +++ b/HealthApp.slnx @@ -1,5 +1,6 @@ + diff --git a/deploy/api-gateway.env.example b/deploy/api-gateway.env.example index dbff8d4..ab25a80 100644 --- a/deploy/api-gateway.env.example +++ b/deploy/api-gateway.env.example @@ -27,3 +27,7 @@ Authentication__Accounts__1__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH # Replace the synthetic identifier below with a created patient's identifier. # Restart the gateway after changing assignments. Omit assignments for an empty list. Access__ProfessionalAssignments__example_professional__0=00000000-0000-0000-0000-000000000001 + +Services__HealthOverview__BaseUrl=https://health-overview.example.test:5084/ +Services__HealthOverview__Key=REPLACE_ME +InternalAccess__HealthOverview__Key=REPLACE_ME diff --git a/deploy/health-overview.env.example b/deploy/health-overview.env.example new file mode 100644 index 0000000..306c61e --- /dev/null +++ b/deploy/health-overview.env.example @@ -0,0 +1,8 @@ +ASPNETCORE_ENVIRONMENT=Production +ASPNETCORE_URLS=https://0.0.0.0:5084 +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/systemd/healthapp-health-overview.service b/deploy/systemd/healthapp-health-overview.service new file mode 100644 index 0000000..c5533b8 --- /dev/null +++ b/deploy/systemd/healthapp-health-overview.service @@ -0,0 +1,20 @@ +[Unit] +Description=HealthApp Health Overview service +Wants=network-online.target +After=network-online.target + +[Service] +Type=simple +User=healthapp +Group=healthapp +WorkingDirectory=/opt/healthapp/health-overview +ExecStart=/usr/bin/dotnet /opt/healthapp/health-overview/HealthOverviewService.dll +EnvironmentFile=/etc/healthapp/health-overview.env +Restart=on-failure +RestartSec=5 +KillSignal=SIGINT +TimeoutStopSec=30 +SyslogIdentifier=healthapp-health-overview + +[Install] +WantedBy=multi-user.target diff --git a/src/AUTHENTICATION.md b/src/AUTHENTICATION.md index 0bd5e69..a23f95d 100644 --- a/src/AUTHENTICATION.md +++ b/src/AUTHENTICATION.md @@ -181,6 +181,20 @@ The US-14 tests exercise actual login, multiple and shared assignments, empty li 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. +endpoints now have equivalent owner/assignment routing and integration tests under +US-11/US-12. Structured observation context is included in authorized reads. + +## US-12 Overview service access + +The gateway requires `Services:HealthOverview:BaseUrl` and `Services:HealthOverview:Key`. +The latter matches Overview's `InternalAccess:GatewayKey` and protects direct access. +Overview's outgoing `Services:ApiGateway:Key` matches `InternalAccess:HealthOverview:Key` +on the gateway. Use distinct randomly generated credentials of at least 32 characters +for each direction and service; load them externally. Production endpoints use HTTPS. + +The HealthOverview service identity is restricted to GET patient profiles, GET latest +overall observations and GET numerical insights. It cannot retrieve history, trends or +another overview, or perform writes. It establishes no client identity. The gateway +checks client ownership/professional assignment before forwarding the outer request. +Internal credentials are trusted service credentials and must remain inaccessible to clients. +Overview adds no authentication framework, shared runtime library or persistence. diff --git a/src/ApiGateway/Controllers/HealthOverviewController.cs b/src/ApiGateway/Controllers/HealthOverviewController.cs new file mode 100644 index 0000000..12510d7 --- /dev/null +++ b/src/ApiGateway/Controllers/HealthOverviewController.cs @@ -0,0 +1,48 @@ +using Microsoft.AspNetCore.Mvc; + +namespace ApiGateway.Controllers; + +[ApiController] +[Route("api")] +public sealed class HealthOverviewController(IHttpClientFactory clients) : ControllerBase +{ + [HttpGet("patients/{patientId:guid}/overview")] + public Task GetOverview(Guid patientId, CancellationToken cancellationToken) => + ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}/overview{Request.QueryString}", cancellationToken); + + private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(method, path); + + try + { + using var upstream = await clients.CreateClient("HealthOverview") + .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + Response.StatusCode = (int)upstream.StatusCode; + Response.ContentType = upstream.Content.Headers.ContentType?.ToString(); + if (upstream.Headers.Location is { } location) + Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString(); + await upstream.Content.CopyToAsync(Response.Body, cancellationToken); + } + catch (HttpRequestException) + { + await WriteFailureAsync(StatusCodes.Status502BadGateway); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + await WriteFailureAsync(StatusCodes.Status504GatewayTimeout); + } + } + + private Task WriteFailureAsync(int status) + { + if (Response.HasStarted) + { + HttpContext.Abort(); + return Task.CompletedTask; + } + Response.Clear(); + return Results.Problem(statusCode: status, title: "Health overview service is unavailable.") + .ExecuteAsync(HttpContext); + } +} diff --git a/src/ApiGateway/Program.cs b/src/ApiGateway/Program.cs index e65a512..02fe7f2 100644 --- a/src/ApiGateway/Program.cs +++ b/src/ApiGateway/Program.cs @@ -62,11 +62,20 @@ public class Program }) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + builder.Services.AddHttpClient("HealthOverview", (services, client) => + { + var configuration = services.GetRequiredService(); + client.BaseAddress = GetBaseUri(configuration, "HealthOverview"); + client.DefaultRequestHeaders.Add("X-Gateway-Key", configuration["Services:HealthOverview: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" }) + _ = GetBaseUri(app.Configuration, "HealthOverview"); + foreach (var key in new[] { "Services:PatientProfile:Key", "Services:Observation:Key", "Services:Insights:Key", "Services:HealthOverview:Key", "InternalAccess:HealthOverview: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"])) @@ -74,7 +83,7 @@ public class Program 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" }) + foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" }) if (GetBaseUri(app.Configuration, service).Scheme != "https") throw new InvalidOperationException("Production service endpoints must use HTTPS."); _ = app.Services.GetRequiredService(); diff --git a/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs b/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs index 1fa7fac..8c484da 100644 --- a/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs +++ b/src/ApiGateway/Security/InternalServiceAuthenticationHandler.cs @@ -14,7 +14,7 @@ public sealed class InternalServiceAuthenticationHandler(IOptionsMonitor HandleAuthenticateAsync() { var supplied = Request.Headers["X-Service-Key"].ToString(); - foreach (var service in new[] { "Observation", "Insights" }) + foreach (var service in new[] { "Observation", "Insights", "HealthOverview" }) { var expected = configuration[$"InternalAccess:{service}:Key"]!; if (CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(supplied), Encoding.UTF8.GetBytes(expected))) diff --git a/src/ApiGateway/Security/PatientAccessMiddleware.cs b/src/ApiGateway/Security/PatientAccessMiddleware.cs index d82e201..b07faea 100644 --- a/src/ApiGateway/Security/PatientAccessMiddleware.cs +++ b/src/ApiGateway/Security/PatientAccessMiddleware.cs @@ -21,9 +21,17 @@ public sealed class PatientAccessMiddleware(RequestDelegate next) 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"); + var patientRoute = segments.Length >= 3 && segments[0] == "api" && segments[1] == "patients" + && Guid.TryParse(segments[2], out _); + var allowed = context.Request.Method == "GET" && patientRoute && (service switch + { + "Observation" => segments.Length == 3, + "Insights" => segments.Length == 4 && segments[3] == "observations", + "HealthOverview" => segments.Length == 3 || + (segments.Length == 4 && segments[3] == "insights") || + (segments.Length == 5 && segments[3] == "observations" && segments[4] == "latest"), + _ => false + }); if (!allowed) { context.Response.StatusCode = 403; return; } await next(context); return; diff --git a/src/HealthOverviewService/Application/HealthOverviewApplicationService.cs b/src/HealthOverviewService/Application/HealthOverviewApplicationService.cs new file mode 100644 index 0000000..ea5a327 --- /dev/null +++ b/src/HealthOverviewService/Application/HealthOverviewApplicationService.cs @@ -0,0 +1,30 @@ +using System.ComponentModel.DataAnnotations; +using HealthOverviewService.Clients; +using HealthOverviewService.Contracts; + +namespace HealthOverviewService.Application; + +public sealed class HealthOverviewApplicationService(PatientProfileServiceClient patients, + ObservationServiceClient observations, InsightsServiceClient insights) +{ + public async Task GetOverviewAsync(Guid patientId, DateTime from, DateTime to, + ContextSelection selection, CancellationToken cancellationToken) + { + from = NormalizeTimestamp(from); + to = NormalizeTimestamp(to); + if (to < from) throw new ArgumentException("The end time must not be earlier than the start time.", nameof(to)); + Validator.ValidateObject(selection, new ValidationContext(selection), validateAllProperties: true); + var patient = await patients.GetPatientAsync(patientId, cancellationToken); + if (patient is null) return null; + var latest = await observations.GetLatestAsync(patientId, cancellationToken); + var insight = await insights.GetSummaryAsync(patientId, from, to, selection, cancellationToken); + return new(patient, latest, insight, from, to, selection, insight?.ContributingCount ?? 0, + "Latest overall observation for the patient, independent of the insight period and context selections. " + + "Its recorded context applies only to that observation, not to the insight's contributing observations.", + insight is null ? "No calculated insight is available: no observations match the requested period and insight selection." : + "The insight uses the requested period and context selection only. " + insight.ContextExplanation); + } + + private static DateTime NormalizeTimestamp(DateTime value) => DateTime.SpecifyKind( + value.Kind == DateTimeKind.Unspecified ? value : value.ToUniversalTime(), DateTimeKind.Unspecified); +} diff --git a/src/HealthOverviewService/Clients/InsightsServiceClient.cs b/src/HealthOverviewService/Clients/InsightsServiceClient.cs new file mode 100644 index 0000000..848b58c --- /dev/null +++ b/src/HealthOverviewService/Clients/InsightsServiceClient.cs @@ -0,0 +1,28 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using HealthOverviewService.Contracts; + +namespace HealthOverviewService.Clients; + +public abstract class InsightsServiceClient +{ + public abstract Task GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken); +} + +public sealed class HttpInsightsServiceClient(HttpClient client) : InsightsServiceClient +{ + public override async Task GetSummaryAsync(Guid patientId, DateTime from, DateTime to, ContextSelection selection, CancellationToken cancellationToken) + { + var path = $"api/patients/{patientId}/insights"; + path += $"?from={Uri.EscapeDataString(from.ToString("O", CultureInfo.InvariantCulture))}&to={Uri.EscapeDataString(to.ToString("O", CultureInfo.InvariantCulture))}"; + if (selection.Setting is not null) path += "&setting=" + Uri.EscapeDataString(selection.Setting); + if (selection.ActivityCondition is not null) path += "&activityCondition=" + Uri.EscapeDataString(selection.ActivityCondition); + + using var response = await client.GetAsync(path, cancellationToken); + if (response.StatusCode == HttpStatusCode.NotFound) return null; + response.EnsureSuccessStatusCode(); + return await response.Content.ReadFromJsonAsync(cancellationToken) + ?? throw new JsonException("Empty upstream response."); + } +} diff --git a/src/HealthOverviewService/Clients/ObservationServiceClient.cs b/src/HealthOverviewService/Clients/ObservationServiceClient.cs new file mode 100644 index 0000000..d5275b7 --- /dev/null +++ b/src/HealthOverviewService/Clients/ObservationServiceClient.cs @@ -0,0 +1,24 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using HealthOverviewService.Contracts; + +namespace HealthOverviewService.Clients; + +public abstract class ObservationServiceClient +{ + public abstract Task GetLatestAsync(Guid patientId, CancellationToken cancellationToken); +} + +public sealed class HttpObservationServiceClient(HttpClient client) : ObservationServiceClient +{ + public override async Task GetLatestAsync(Guid patientId, CancellationToken cancellationToken) + { + var path = $"api/patients/{patientId}/observations/latest"; + using var response = await client.GetAsync(path, cancellationToken); + if (response.StatusCode == HttpStatusCode.NotFound) return null; + response.EnsureSuccessStatusCode(); + return await response.Content.ReadFromJsonAsync(cancellationToken) + ?? throw new JsonException("Empty upstream response."); + } +} diff --git a/src/HealthOverviewService/Clients/PatientProfileServiceClient.cs b/src/HealthOverviewService/Clients/PatientProfileServiceClient.cs new file mode 100644 index 0000000..c6e0de8 --- /dev/null +++ b/src/HealthOverviewService/Clients/PatientProfileServiceClient.cs @@ -0,0 +1,24 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using HealthOverviewService.Contracts; + +namespace HealthOverviewService.Clients; + +public abstract class PatientProfileServiceClient +{ + public abstract Task GetPatientAsync(Guid patientId, CancellationToken cancellationToken); +} + +public sealed class HttpPatientProfileServiceClient(HttpClient client) : PatientProfileServiceClient +{ + public override async Task GetPatientAsync(Guid patientId, CancellationToken cancellationToken) + { + var path = $"api/patients/{patientId}"; + using var response = await client.GetAsync(path, cancellationToken); + if (response.StatusCode == HttpStatusCode.NotFound) return null; + response.EnsureSuccessStatusCode(); + return await response.Content.ReadFromJsonAsync(cancellationToken) + ?? throw new JsonException("Empty upstream response."); + } +} diff --git a/src/HealthOverviewService/Contracts/HealthOverviewDto.cs b/src/HealthOverviewService/Contracts/HealthOverviewDto.cs new file mode 100644 index 0000000..006139b --- /dev/null +++ b/src/HealthOverviewService/Contracts/HealthOverviewDto.cs @@ -0,0 +1,24 @@ +using System.ComponentModel.DataAnnotations; + +namespace HealthOverviewService.Contracts; + +public sealed record ContextSelection +{ + [AllowedValues("Home", "Clinic", "Other", "Unknown", null)] + public string? Setting { get; init; } + [AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)] + public string? ActivityCondition { get; init; } +} + +public sealed record PatientDto(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo); +public sealed record MeasurementContextDto(string Setting, string ActivityCondition, decimal? RestDurationMinutes, + string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances); +public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt, + int Systolic, int Diastolic, int Pulse, string? Context, string? Note, MeasurementContextDto MeasurementContext); +public sealed record HealthInsightDto(Guid PatientId, DateTime PeriodStart, DateTime PeriodEnd, + decimal AverageSystolic, decimal AverageDiastolic, decimal AveragePulse, + int MinSystolic, int MaxSystolic, int MinDiastolic, int MaxDiastolic, + ContextSelection AppliedSelection, int ContributingCount, string ContextExplanation); +public sealed record HealthOverviewDto(PatientDto Patient, ObservationDto? LatestObservation, HealthInsightDto? Insight, + DateTime PeriodStart, DateTime PeriodEnd, ContextSelection InsightSelection, int InsightContributingCount, + string LatestObservationBasis, string InsightExplanation); diff --git a/src/HealthOverviewService/Controllers/HealthOverviewController.cs b/src/HealthOverviewService/Controllers/HealthOverviewController.cs new file mode 100644 index 0000000..f0ae49d --- /dev/null +++ b/src/HealthOverviewService/Controllers/HealthOverviewController.cs @@ -0,0 +1,34 @@ +using HealthOverviewService.Application; +using HealthOverviewService.Contracts; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace HealthOverviewService.Controllers; + +[ApiController] +[Route("api/patients/{patientId:guid}/overview")] +public sealed class HealthOverviewController(HealthOverviewApplicationService service) : ControllerBase +{ + [HttpGet] + public async Task> GetOverview(Guid patientId, + [FromQuery, BindRequired] DateTime from, [FromQuery, BindRequired] DateTime to, + [FromQuery] ContextSelection selection, CancellationToken cancellationToken) + { + try + { + var result = await service.GetOverviewAsync(patientId, from, to, selection, cancellationToken); + return result is null ? Problem(statusCode: 404, title: "Patient does not exist.") : Ok(result); + } + catch (ArgumentException) + { + ModelState.AddModelError(nameof(to), "The end time must not be earlier than the start time."); + return ValidationProblem(ModelState); + } + catch (HttpRequestException) + { return Problem(statusCode: 502, title: "Overview source service is unavailable."); } + catch (System.Text.Json.JsonException) + { return Problem(statusCode: 502, title: "Overview source response is invalid."); } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { return Problem(statusCode: 504, title: "Overview source request timed out."); } + } +} diff --git a/src/HealthOverviewService/HealthOverviewService.csproj b/src/HealthOverviewService/HealthOverviewService.csproj new file mode 100644 index 0000000..9a04a31 --- /dev/null +++ b/src/HealthOverviewService/HealthOverviewService.csproj @@ -0,0 +1,7 @@ + + + net10.0 + enable + enable + + diff --git a/src/HealthOverviewService/Program.cs b/src/HealthOverviewService/Program.cs new file mode 100644 index 0000000..0b7e52e --- /dev/null +++ b/src/HealthOverviewService/Program.cs @@ -0,0 +1,78 @@ +using System.Security.Cryptography; +using System.Text; +using HealthOverviewService.Application; +using HealthOverviewService.Clients; + +namespace HealthOverviewService; + +public class Program +{ + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + builder.Services.AddControllers(); + builder.Services.AddProblemDetails(); + builder.Services.AddScoped(); + builder.Services.AddHttpClient((services, client) => + { + 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 }); + builder.Services.AddHttpClient((services, client) => + { + 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 }); + builder.Services.AddHttpClient((services, client) => + { + 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(); + } + + private static Uri GetGatewayUri(IConfiguration configuration) + { + var endpoint = configuration["Services:ApiGateway:BaseUrl"]; + if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || + (uri.Scheme != "http" && uri.Scheme != "https") || uri.AbsolutePath != "/" || + !string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment) || !string.IsNullOrEmpty(uri.UserInfo)) + throw new InvalidOperationException("Services:ApiGateway:BaseUrl must be an HTTP(S) origin URL."); + return uri; + } +} diff --git a/src/HealthOverviewService/appsettings.json b/src/HealthOverviewService/appsettings.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/src/HealthOverviewService/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/OVERVIEW.md b/src/OVERVIEW.md new file mode 100644 index 0000000..4c7c1e9 --- /dev/null +++ b/src/OVERVIEW.md @@ -0,0 +1,64 @@ +# US-12 health overview + +`GET /api/patients/{patientId}/overview?from=...&to=...&setting=Home&activityCondition=AtRest` +requires the patient's authenticated account or an assigned read-only professional. +Dates use the existing inclusive measurement-instant convention. Offset-free timestamps +mean UTC; equivalent offsets identify the same instant. From and to are required, +equal bounds are valid, reversed/malformed/missing bounds return 400. Both selected +context dimensions must match for insight; `Unknown` is an explicit selectable category. +Omitted dimensions are unrestricted. Unsupported selections return 400 validation details. + +The independent ASP.NET Core Health Overview Service loads the profile, latest overall +observation and US-10 numerical insight through three HTTP clients routed through the +gateway. It has no production project references to another service, database, stored +aggregate or cache. The renamed Overview ER illustration explicitly denotes data needed +from other services rather than overview persistence; the current class model governs. + +## Response + +A successful request returns 200 with: + +- `patient`: the current profile, including ID, name, birth date and contact information. +- `latestObservation`: latest overall reading, including original text, note and all recorded + structured context, or null when no observations exist. Latest retains US-06 timestamp, + original recording-time and deterministic ID ordering. The insight period and filters + never limit latest-observation selection. +- `insight`: the existing US-10 response or null when no observations match the insight + period/context. Its rounded means, extrema, selection, contributing count and context + explanation are preserved. No trend component is added. +- `periodStart`, `periodEnd`, `insightSelection`, `insightContributingCount`: explicit insight + basis even when insight is absent (count zero). +- `latestObservationBasis`: explains that latest context belongs to that reading only. +- `insightExplanation`: preserves the insight's context limitations or explains why no + selected-period insight is available. Empty insight does not remove profile/latest. + +An authorized missing patient returns 404 with `Patient does not exist.` Access rejection +retains the gateway's non-disclosing empty 404 convention; unauthenticated clients get 401. +Professional writes remain forbidden. Upstream connection/status/invalid-JSON failures +return 502; local upstream timeouts return 504. These are not reported as absent data. +Only upstream 404 responses on the appropriate profile/latest/insight routes represent +missing data. Requests are cancelled on client disconnect. + +Every overview request fetches current source data, including profile updates, corrected +measurement/context, and deletions. Reads occur separately across services, so concurrent +writes may occur between them; the overview does not promise a cross-service snapshot. +There is no extra transaction, refresh mechanism, synchronisation process or persisted +copy to invalidate. + +## Deployment and verification + +The service builds/publishes independently with .NET 10 and starts from external +configuration. See `deploy/health-overview.env.example`, the independent systemd unit, +[README.md](README.md) and [AUTHENTICATION.md](AUTHENTICATION.md). It requires only the +gateway origin and incoming/outgoing service credentials; no database configuration or +migration is needed. Production uses HTTPS; local HTTP is limited to Development. +Addresses, network binding, credentials and certificates are configurable for separate +machines. Standard stdout/stderr logging, graceful shutdown and restart follow the other +service units. No new package dependencies are introduced. + +US-12 acceptance tests run five actual HTTP hosts against separate patient/observation +PostgreSQL databases. They cover all story scenarios, boundaries/offsets, patient scope, +latest tie rules, context preservation, independent filters, unknown/mixed context, +empty selected insight, corrections/deletions/restart, profile updates, missing patients, +validation, owner/assignment enforcement, direct bypass rejection, restricted internal +service reads and unavailable upstream/Overview services. diff --git a/src/README.md b/src/README.md index 9cbfddd..d28ae82 100644 --- a/src/README.md +++ b/src/README.md @@ -1,6 +1,6 @@ -# Patient profiles, observations, insights and authentication +# Patient profiles, observations, insights, overview 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/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, Insights Service, and Health Overview 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. @@ -28,7 +28,7 @@ dotnet run --project src/PatientProfileService -c Release --no-build -- --migrat ASPNETCORE_URLS=http://127.0.0.1:5081 dotnet run --project src/PatientProfileService -c Release --no-build # In a separate gateway terminal. -Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ Services__Insights__BaseUrl=http://127.0.0.1:5083/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build +Services__PatientProfile__BaseUrl=http://127.0.0.1:5081/ Services__Observation__BaseUrl=http://127.0.0.1:5082/ Services__Insights__BaseUrl=http://127.0.0.1:5083/ Services__HealthOverview__BaseUrl=http://127.0.0.1:5084/ ASPNETCORE_URLS=http://127.0.0.1:5080 dotnet run --project src/ApiGateway -c Release --no-build # In a separate observation terminal, with its own provisioned database. export ConnectionStrings__ObservationDatabase='Host=127.0.0.1;Database=observations;Username=observations;Password=YOUR_LOCAL_PASSWORD' @@ -37,6 +37,9 @@ Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127. # In a separate insights terminal; no database or migration is required. Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5083 dotnet run --project src/InsightsService -c Release --no-build + +# In a separate overview terminal; no database or migration is required. +Services__ApiGateway__BaseUrl=http://127.0.0.1:5080/ ASPNETCORE_URLS=http://127.0.0.1:5084 dotnet run --project src/HealthOverviewService -c Release --no-build ``` `--migrate` applies committed EF Core migrations and exits. Apply migrations as a deployment step before starting the service; normal startup does not modify the schema. Both services fail startup with a clear message if required configuration is absent. Configuration uses standard .NET JSON files, environment variables, and command-line arguments. Service endpoints and database hosts may be remote. @@ -233,6 +236,14 @@ reproducible mathematical methods, reference sources and interpretation limits. all US-11 acceptance criteria, current corrections/context/deletion, access controls and failures. No persistence, service boundaries, dependencies or configuration changed. +`GET /api/patients/{patientId}/overview?from=...&to=...` implements US-12 in the +independently deployable Health Overview Service. It returns the current profile, +latest overall observation with its own recorded context, and selected-period numerical +insight. Setting/activity filters apply to insight only. Empty insight selections keep +the profile and latest reading and explain the missing insight. Context limitations, +applied selections and counts remain visible. See [OVERVIEW.md](OVERVIEW.md) for +response semantics, service credentials, deployment and consistency limits. + 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 professional reads require predefined gateway assignments; professional @@ -293,6 +304,7 @@ dotnet publish src/PatientProfileService -c Release -o /tmp/healthapp-publish/pa dotnet publish src/ApiGateway -c Release -o /tmp/healthapp-publish/api-gateway dotnet publish src/ObservationService -c Release -o /tmp/healthapp-publish/observation dotnet publish src/InsightsService -c Release -o /tmp/healthapp-publish/insights +dotnet publish src/HealthOverviewService -c Release -o /tmp/healthapp-publish/health-overview ``` Copy each output to its corresponding `/opt/healthapp/` directory on the intended host, install the ASP.NET Core 10 runtime, and create a `healthapp` service user/group. Adjust the paths/user in `deploy/systemd/*.service` for the host. Copy the environment examples to `/etc/healthapp/patient-profile.env` and `/etc/healthapp/api-gateway.env`, replace example values, and restrict their permissions to protect credentials. Configure the gateway certificate for the HTTPS client entry point. Its example uses a PFX certificate; standard Kestrel configuration also supports other certificate formats. @@ -309,3 +321,10 @@ Install the corresponding unit on each host and enable/start it with systemd. Th The Observation Service has its own `healthapp-observation.service` unit and environment example. Configure its `Services__ApiGateway__BaseUrl` and the gateway's `Services__Observation__BaseUrl` for the deployed hosts. Apply its migration with its own database configuration. Services need not be started in a fixed order; requests needing an unavailable upstream fail without saving observations. The Insights Service has an independent `healthapp-insights.service` systemd unit and `deploy/insights.env.example`. Install its published output under `/opt/healthapp/insights`, configure `/etc/healthapp/insights.env`, and set `Services__ApiGateway__BaseUrl` to the deployed gateway. Configure the gateway's required `Services__Insights__BaseUrl` for the deployed Insights host. URLs may refer to separate machines. Insights requires no database, migration, startup ordering, or shared process state. Standard stdout/stderr logging, graceful shutdown, and restart follow the other service units. + +The Health Overview Service has its own `healthapp-health-overview.service` unit and +`deploy/health-overview.env.example`. Publish to `/opt/healthapp/health-overview` and +configure `/etc/healthapp/health-overview.env`. Set its `Services__ApiGateway__BaseUrl` +and the gateway's `Services__HealthOverview__BaseUrl` to the deployed hosts. The +gateway now requires the Overview endpoint and both directions of service credentials. +Overview owns no database and requires no migrations or fixed startup order. diff --git a/suggestions/us12-overview-persistence-conflict.md b/suggestions/us12-overview-persistence-conflict.md new file mode 100644 index 0000000..6e8ce37 --- /dev/null +++ b/suggestions/us12-overview-persistence-conflict.md @@ -0,0 +1,54 @@ +# US-12 — Overview persistence clarification resolved + +Status: resolved by the user's authoritative diagram rename on 2026-10-05. +The Overview ER illustration is now named +`10_er_health_overview_service-overruled no persistence here to give an idea of what data is needed to be able to use from other services or calculate.jpg`. +This explicitly identifies its fields as a non-persisted data illustration. Follow +`06_class_health_overview_service.drawio`: aggregate current source-service data +without own persistence. No architecture or requirements documents were edited by the agent. + +The original conflict and recommendation are retained below as review history; +the approval request and draft status below are superseded by this resolution. + +## Original proposal + +## Conflicting authoritative material + +- `Docs/Architecture/06_class_health_overview_service.drawio` explicitly says the + application service loads profile, latest overall observation and selected-period + numerical insight and aggregates **without own persistence**. +- `Docs/Architecture/10_er_health_overview_service.jpg` shows a `HealthOverview` + table with a `patient_id` primary key, copied patient/latest/average fields and + `updated_at`. +- `Docs/Architecture/README.md` supersedes only listed same-stem JPEGs; the Overview + ER diagram is unlisted and remains supplied. Unlike Insights, there is no explicit + correction retiring the Overview ER table or identifying it as a non-persisted projection. + +The ER diagram's database-shaped representation is ambiguous against the explicit +no-persistence class model. Implementation must not silently decide that it requires +storage or silently retire it. + +## Recommended clarification (requires approval) + +Follow the current class model: the independent Health Overview service calculates +on demand through gateway-routed HTTP clients and owns no database, cache or stored +aggregate. Treat the retained Overview ER diagram as a historical/logical projection, +not a persistence requirement. The user can incorporate that clarification into the +authoritative Architecture documentation; no Docs files have been edited. + +This keeps current profile, latest context and selected numerical insight visible +without an unspecified synchronisation/update mechanism or additional persistence. +It matches US-12 and the explicit current Overview application-service responsibility. + +If persistence is intended instead, clarify ownership, refresh/invalidation, period +and selection keys, consistency after edits/deletion, and storage schema before that +implementation proceeds. A patient-id-only table cannot represent arbitrary selected +periods and context selections without additional decisions. + +## Prepared implementation + +A working draft independent service, clients, protected gateway route, configuration, +systemd template and acceptance tests are present in the working tree. They implement +the recommended on-demand option and remain uncommitted pending this clarification. +No authoritative documentation or existing review file was changed. The draft does +not constitute an approved resolution of the conflict or a completed US-12 commit. diff --git a/tests/Observation.AcceptanceTests/HealthOverviewTests.cs b/tests/Observation.AcceptanceTests/HealthOverviewTests.cs new file mode 100644 index 0000000..aa71a6b --- /dev/null +++ b/tests/Observation.AcceptanceTests/HealthOverviewTests.cs @@ -0,0 +1,249 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using HealthApp.TestSupport; +using HealthOverviewService.Contracts; +using Xunit; + +namespace Observation.AcceptanceTests; + +public sealed class HealthOverviewTests(ObservationApiFixture fixture) : IClassFixture +{ + private sealed record Recorded(Guid ObservationId); + private const string Period = "from=2026-09-01T08%3A00%3A00&to=2026-09-10T08%3A00%3A00"; + private static string PathFor(Guid patient, string query = Period) => $"/api/patients/{patient}/overview?{query}"; + private async Task Patient() + { + using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new + { name = "Overview patient", dateOfBirth = "1980-01-01", contactInfo = "Synthetic contact" }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!.PatientId; + } + private async Task Record(Guid patient, string time, int systolic = 120, + string? setting = "Home", string? activity = "AtRest") + { + using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patient}/observations", new + { + measuredAt = time, systolic, diastolic = 80, pulse = 65, context = "Preserved original context", note = "Preserved note", + measurementContext = new { setting, activityCondition = activity, restDurationMinutes = 5, + bodyPosition = "Seated", measuredArm = "Left", deviceDetails = "Device", cuffDetails = "Cuff", additionalCircumstances = "Morning" } + }); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!.ObservationId; + } + private async Task Overview(Guid patient, string query = Period) + { + using var response = await fixture.Client.GetAsync(PathFor(patient, query)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return (await response.Content.ReadFromJsonAsync())!; + } + + [Fact] + public async Task Overview_preserves_profile_latest_context_and_selected_insight_with_different_bases() + { + var patient = await Patient(); + await Record(patient, "2026-09-01T08:00:00", 120); + await Record(patient, "2026-09-10T08:00:00", 130); + await Record(patient, "2026-09-01T07:59:59", 200); + var latest = await Record(patient, "2026-09-11T08:00:00", 210, "Clinic", "AfterActivity"); + await Record(await Patient(), "2026-09-05T08:00:00", 250); + var result = await Overview(patient, Period + "&setting=Home&activityCondition=AtRest"); + Assert.Equal(patient, result.Patient.PatientId); + Assert.Equal("Overview patient", result.Patient.Name); + Assert.Equal(new DateOnly(1980, 1, 1), result.Patient.DateOfBirth); + Assert.Equal("Synthetic contact", result.Patient.ContactInfo); + Assert.Equal(latest, result.LatestObservation!.ObservationId); + Assert.Equal("AfterActivity", result.LatestObservation.MeasurementContext.ActivityCondition); + Assert.Equal("Clinic", result.LatestObservation.MeasurementContext.Setting); + Assert.Equal("Seated", result.LatestObservation.MeasurementContext.BodyPosition); + Assert.Equal("Left", result.LatestObservation.MeasurementContext.MeasuredArm); + Assert.Equal("Device", result.LatestObservation.MeasurementContext.DeviceDetails); + Assert.Equal("Cuff", result.LatestObservation.MeasurementContext.CuffDetails); + Assert.Equal(5m, result.LatestObservation.MeasurementContext.RestDurationMinutes); + Assert.Equal("Morning", result.LatestObservation.MeasurementContext.AdditionalCircumstances); + Assert.Equal("Preserved original context", result.LatestObservation.Context); + Assert.Equal("Preserved note", result.LatestObservation.Note); + Assert.Equal(125m, result.Insight!.AverageSystolic); + Assert.Equal(2, result.InsightContributingCount); + Assert.Equal(result.InsightSelection, result.Insight.AppliedSelection); + Assert.Equal("Home", result.InsightSelection.Setting); + Assert.Equal("AtRest", result.InsightSelection.ActivityCondition); + Assert.Equal(new DateTime(2026, 9, 1, 8, 0, 0), result.PeriodStart); + Assert.Equal(new DateTime(2026, 9, 10, 8, 0, 0), result.PeriodEnd); + Assert.Contains("independent of the insight period and context selections", result.LatestObservationBasis); + Assert.Contains("not to the insight", result.LatestObservationBasis); + using var raw = await fixture.Client.GetAsync(PathFor(patient)); + using var json = JsonDocument.Parse(await raw.Content.ReadAsStringAsync()); + Assert.False(json.RootElement.TryGetProperty("trend", out _)); + } + + [Fact] + public async Task No_observations_returns_profile_and_explicit_insight_absence() + { + var result = await Overview(await Patient()); + Assert.NotNull(result.Patient); + Assert.Null(result.LatestObservation); + Assert.Null(result.Insight); + Assert.Equal(0, result.InsightContributingCount); + Assert.Contains("No calculated insight is available", result.InsightExplanation); + } + + [Theory] + [InlineData("&setting=Clinic")] + [InlineData("&activityCondition=AfterActivity")] + [InlineData("&setting=Unknown&activityCondition=Unknown")] + public async Task Empty_selected_insight_preserves_profile_latest_and_applied_selection(string selection) + { + var patient = await Patient(); + var latest = await Record(patient, "2026-09-05T08:00:00"); + var result = await Overview(patient, Period + selection); + Assert.Equal(patient, result.Patient.PatientId); + Assert.Equal(latest, result.LatestObservation!.ObservationId); + Assert.Null(result.Insight); + Assert.Equal(0, result.InsightContributingCount); + Assert.Contains("no observations match", result.InsightExplanation); + Assert.True(result.InsightSelection.Setting is not null || result.InsightSelection.ActivityCondition is not null); + } + + [Fact] + public async Task Unfiltered_pooled_insight_preserves_mixed_and_unknown_context_explanations() + { + var patient = await Patient(); + await Record(patient, "2026-09-02T08:00:00", 120); + await Record(patient, "2026-09-03T08:00:00", 130, "Clinic", "AfterActivity"); + var latest = await Record(patient, "2026-09-04T08:00:00", 140, null, null); + var result = await Overview(patient); + Assert.Equal(latest, result.LatestObservation!.ObservationId); + Assert.Equal("Unknown", result.LatestObservation.MeasurementContext.Setting); + Assert.Equal("Unknown", result.LatestObservation.MeasurementContext.ActivityCondition); + Assert.Null(result.InsightSelection.Setting); + Assert.Null(result.InsightSelection.ActivityCondition); + Assert.Equal(3, result.InsightContributingCount); + Assert.Equal(130m, result.Insight!.AverageSystolic); + Assert.Contains("mixed settings or activity conditions", result.Insight.ContextExplanation); + Assert.Contains("unknown", result.InsightExplanation); + } + + [Fact] + public async Task Equal_offset_instants_are_valid_and_single_observation_insight_is_sufficient() + { + var patient = await Patient(); + await Record(patient, "2026-09-05T10:00:00+02:00", 121); + var result = await Overview(patient, + "from=2026-09-05T10%3A00%3A00%2B02%3A00&to=2026-09-05T08%3A00%3A00Z&setting=Home"); + Assert.Equal(result.PeriodStart, result.PeriodEnd); + Assert.Equal(1, result.InsightContributingCount); + Assert.Equal(121m, result.Insight!.AverageSystolic); + } + + [Fact] + public async Task Latest_tie_rules_and_current_corrections_deletions_and_profile_edits_survive_restart() + { + var patient = await Patient(); + var first = await Record(patient, "2026-09-05T08:00:00", 120); + var second = await Record(patient, "2026-09-05T08:00:00", 130, "Clinic", "AfterActivity"); + Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId); + using var patched = await fixture.Client.PatchAsJsonAsync($"/api/observations/{first}", + new { systolic = 140, measurementContext = new { setting = "Clinic" } }); + Assert.Equal(HttpStatusCode.OK, patched.StatusCode); + Assert.Null((await Overview(patient, Period + "&setting=Home")).Insight); + Assert.Equal(second, (await Overview(patient)).LatestObservation!.ObservationId); + using var edited = await fixture.Client.PutAsJsonAsync($"/api/patients/{patient}", + new { name = "Updated overview", dateOfBirth = "1980-01-01", contactInfo = "Updated contact" }); + Assert.Equal(HttpStatusCode.OK, edited.StatusCode); + using var deleted = await fixture.Client.DeleteAsync($"/api/observations/{second}"); + Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode); + await fixture.RestartHostsAsync(); + var result = await Overview(patient); + Assert.Equal("Updated overview", result.Patient.Name); + Assert.Equal(first, result.LatestObservation!.ObservationId); + Assert.Equal(140m, result.Insight!.AverageSystolic); + Assert.Equal(1, result.InsightContributingCount); + } + + [Theory] + [InlineData("from=2026-09-10&to=2026-09-01")] + [InlineData("from=bad&to=2026-09-10")] + [InlineData("from=2026-09-01&to=bad")] + [InlineData("from=2026-09-01")] + [InlineData("to=2026-09-10")] + [InlineData("")] + [InlineData(Period + "&setting=Invalid")] + [InlineData(Period + "&activityCondition=Invalid")] + public async Task Invalid_period_or_context_is_rejected_with_details(string query) + { + using var response = await fixture.Client.GetAsync(PathFor(await Patient(), query)); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.True(problem.RootElement.TryGetProperty("errors", out _)); + } + + [Fact] + public async Task Assigned_missing_patient_reports_absence_without_exposing_other_patients() + { + var missing = Guid.NewGuid(); + fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = missing.ToString(); + await fixture.RestartHostsAsync(); + using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(missing)); + request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional")); + using var response = await fixture.RawClient.SendAsync(request); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Contains("Patient does not exist", await response.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Overview_requires_owner_or_assigned_professional_and_blocks_direct_bypass() + { + var patient = await Patient(); + await Record(patient, "2026-09-05T08:00:00"); + var other = await Patient(); + fixture.AdditionalGatewayConfiguration["Access:ProfessionalAssignments:professional:0"] = patient.ToString(); + await fixture.RestartHostsAsync(); + using var anonymous = await fixture.RawClient.GetAsync(PathFor(patient)); + Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); + foreach (var (account, status) in new[] { ("professional", HttpStatusCode.OK), + ("professional-empty", HttpStatusCode.NotFound), (fixture.Authentication.PatientAccounts[other], HttpStatusCode.NotFound) }) + { + using var request = new HttpRequestMessage(HttpMethod.Get, PathFor(patient)); + request.Headers.Authorization = new("Bearer", await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account)); + using var response = await fixture.RawClient.SendAsync(request); + Assert.Equal(status, response.StatusCode); + if (status != HttpStatusCode.OK) Assert.Empty(await response.Content.ReadAsStringAsync()); + } + using var direct = fixture.CreateDirectOverviewClient(); + using var bypass = await direct.GetAsync(PathFor(patient)); + Assert.Equal(HttpStatusCode.Unauthorized, bypass.StatusCode); + Assert.Empty(await bypass.Content.ReadAsStringAsync()); + } + + [Theory] + [InlineData("overview")] + [InlineData("trends")] + [InlineData("observations")] + public async Task Overview_service_credential_is_restricted_to_required_reads(string route) + { + using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{await Patient()}/{route}?{Period}"); + request.Headers.Add("X-Service-Key", fixture.Authentication.OverviewServiceKey); + using var response = await fixture.RawClient.SendAsync(request); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + } + + [Theory] + [InlineData("Observation")] + [InlineData("Insights")] + [InlineData("Overview")] + public async Task Unavailable_source_or_overview_is_a_failure_not_absent_insight(string service) + { + var patient = await Patient(); + if (service == "Observation") await fixture.StopObservationServiceAsync(); + if (service == "Insights") await fixture.StopInsightsServiceAsync(); + if (service == "Overview") await fixture.StopOverviewServiceAsync(); + try + { + using var response = await fixture.Client.GetAsync(PathFor(patient)); + Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode); + } + finally { await fixture.RestartHostsAsync(); } + } +} diff --git a/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj b/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj index 15b4d16..7caa04d 100644 --- a/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj +++ b/tests/Observation.AcceptanceTests/Observation.AcceptanceTests.csproj @@ -13,6 +13,7 @@ + diff --git a/tests/Observation.AcceptanceTests/ObservationApiFixture.cs b/tests/Observation.AcceptanceTests/ObservationApiFixture.cs index fcb91bf..179d329 100644 --- a/tests/Observation.AcceptanceTests/ObservationApiFixture.cs +++ b/tests/Observation.AcceptanceTests/ObservationApiFixture.cs @@ -18,6 +18,8 @@ public sealed class ObservationApiFixture : IAsyncLifetime private readonly string observationDatabaseName = "us04_observation_" + Guid.NewGuid().ToString("N"); private WebApplicationFactory? observation; private WebApplicationFactory? insights; + private WebApplicationFactory? overview; + public HttpClient CreateDirectOverviewClient() => overview!.CreateClient(); public string ObservationConnectionString { get; private set; } = ""; private string adminConnectionString = ""; private WebApplicationFactory? service; @@ -113,19 +115,44 @@ public sealed class ObservationApiFixture : IAsyncLifetime insights.UseKestrel(0); using var insightsClient = insights.CreateClient(); gateway.Services.GetRequiredService()["Services:Insights:BaseUrl"] = insightsClient.BaseAddress!.ToString(); + overview = 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(), + ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, + ["Services:ApiGateway:Key"] = Authentication.OverviewServiceKey })); + }); + overview.UseKestrel(0); + using var overviewClient = overview.CreateClient(); + gateway.Services.GetRequiredService()["Services:HealthOverview:BaseUrl"] = overviewClient.BaseAddress!.ToString(); } public async Task RestartHostsAsync() { Client.Dispose(); RawClient.Dispose(); - await insights!.DisposeAsync(); + if (overview is not null) await overview.DisposeAsync(); + if (insights is not null) await insights.DisposeAsync(); if (observation is not null) await observation.DisposeAsync(); await gateway!.DisposeAsync(); if (service is not null) await service.DisposeAsync(); StartHosts(); } + public async Task StopOverviewServiceAsync() + { + if (overview is not null) await overview.DisposeAsync(); + overview = null; + } + + public async Task StopInsightsServiceAsync() + { + if (insights is not null) await insights.DisposeAsync(); + insights = null; + } + public async Task StopObservationServiceAsync() { if (observation is not null) await observation.DisposeAsync(); @@ -142,6 +169,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime { Client?.Dispose(); RawClient?.Dispose(); + if (overview is not null) await overview.DisposeAsync(); if (insights is not null) await insights.DisposeAsync(); if (observation is not null) await observation.DisposeAsync(); if (gateway is not null) await gateway.DisposeAsync(); diff --git a/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs b/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs index 1e3e5b2..446d64a 100644 --- a/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs +++ b/tests/PatientProfile.AcceptanceTests/AuthenticationIntegrationTests.cs @@ -23,7 +23,7 @@ public sealed class AuthenticationIntegrationTests try { var configuration = authentication.Configuration(); - foreach (var service in new[] { "PatientProfile", "Observation", "Insights" }) + foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" }) configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/"; using var host = new WebApplicationFactory().WithWebHostBuilder(builder => { @@ -55,7 +55,7 @@ public sealed class AuthenticationIntegrationTests configuration["TestIdentity:Role"] = role; configuration["TestIdentity:AccountId"] = accountId; configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString(); - foreach (var service in new[] { "PatientProfile", "Observation", "Insights" }) + foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" }) configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/"; using var host = new WebApplicationFactory().WithWebHostBuilder(builder => { diff --git a/tests/Support/AuthenticatedTestClient.cs b/tests/Support/AuthenticatedTestClient.cs index 876e19e..7fce3f2 100644 --- a/tests/Support/AuthenticatedTestClient.cs +++ b/tests/Support/AuthenticatedTestClient.cs @@ -15,6 +15,7 @@ public sealed class AuthenticatedTestClient public readonly string GatewayKey = new('g', 48); public readonly string ObservationServiceKey = new('o', 48); public readonly string InsightsServiceKey = new('i', 48); + public readonly string OverviewServiceKey = new('v', 48); public TestClock Clock { get; } = new(); public string KeyDirectory { get; } = Path.Combine(Path.GetTempPath(), "healthapp-keys-" + Guid.NewGuid()); public ConcurrentDictionary PatientAccounts { get; } = new(); @@ -33,7 +34,10 @@ public sealed class AuthenticatedTestClient ["Services:Observation:Key"] = GatewayKey, ["Services:Insights:Key"] = GatewayKey, ["InternalAccess:Observation:Key"] = ObservationServiceKey, - ["InternalAccess:Insights:Key"] = InsightsServiceKey + ["InternalAccess:Insights:Key"] = InsightsServiceKey, + ["InternalAccess:HealthOverview:Key"] = OverviewServiceKey, + ["Services:HealthOverview:Key"] = GatewayKey, + ["Services:HealthOverview:BaseUrl"] = "http://127.0.0.1:1/" }; for (var i = 0; i < 256; i++) {