Implement US-13 patient authentication and persistent ownership
This commit is contained in:
1 parent
ebf50827d6
commit
0ce9b2b168
36 files changed
+1203
-28
No files matched your search
@@ -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 <token>` 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:<index>:{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:<service>: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
|
||||
@@ -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<BearerTokenOptions> 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);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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<PrototypeAccounts>();
|
||||
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<AuthenticationSchemeOptions, InternalServiceAuthenticationHandler>("InternalService", null);
|
||||
builder.Services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); options.AddPolicy("Patient", policy => policy.RequireRole("Patient").RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier)); });
|
||||
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||
builder.Services.AddOptions<KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((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<IConfiguration>(), "PatientProfile"))
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
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<IConfiguration>(), "Observation"))
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
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<IConfiguration>(), "Insights"))
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
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<PrototypeAccounts>();
|
||||
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<PatientAccessMiddleware>();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
}
|
||||
|
||||
@@ -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<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger, UrlEncoder encoder, IConfiguration configuration)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> 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."));
|
||||
}
|
||||
}
|
||||
@@ -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<IAllowAnonymous>() 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); }
|
||||
}
|
||||
}
|
||||
@@ -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<string, PrototypeAccount> accounts;
|
||||
private readonly PasswordHasher<PrototypeAccount> hasher = new();
|
||||
private readonly PrototypeAccount dummy = new() { AccountId = "invalid" };
|
||||
|
||||
public PrototypeAccounts(IConfiguration configuration)
|
||||
{
|
||||
var configured = configuration.GetSection("Authentication:Accounts").Get<PrototypeAccount[]>() ?? [];
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -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<InsightsApplicationService>();
|
||||
builder.Services.AddSingleton<InsightCalculator>();
|
||||
builder.Services.AddHttpClient<ObservationServiceClient, HttpObservationServiceClient>((services, client) =>
|
||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -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<ObservationRepository, SqlObservationRepository>();
|
||||
builder.Services.AddScoped<ObservationApplicationService>();
|
||||
builder.Services.AddHttpClient("ApiGateway", (services, client) =>
|
||||
client.BaseAddress = GetGatewayUri(services.GetRequiredService<IConfiguration>()))
|
||||
{
|
||||
var configuration = services.GetRequiredService<IConfiguration>();
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -5,17 +5,21 @@ namespace PatientProfileService.Application;
|
||||
|
||||
public sealed class PatientApplicationService(PatientRepository repository)
|
||||
{
|
||||
public Task<Patient> CreatePatientAsync(CreatePatientRequest request, CancellationToken cancellationToken)
|
||||
public async Task<Patient> 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<Patient?> GetByAccountAsync(string accountId, CancellationToken cancellationToken) =>
|
||||
repository.FindByAccountIdAsync(accountId, cancellationToken);
|
||||
|
||||
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||
repository.FindByIdAsync(patientId, cancellationToken);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace PatientProfileService.Application;
|
||||
|
||||
public interface PatientRepository
|
||||
{
|
||||
Task<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken);
|
||||
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
|
||||
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
|
||||
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace PatientProfileService.Application;
|
||||
|
||||
public sealed class ProfileAlreadyExistsException : Exception
|
||||
{
|
||||
}
|
||||
@@ -12,8 +12,24 @@ public sealed class PatientController(PatientApplicationService service) : Contr
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<PatientDto>> 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<ActionResult<PatientDto>> GetByAccount(string accountId, CancellationToken cancellationToken)
|
||||
{
|
||||
var patient = await service.GetByAccountAsync(accountId, cancellationToken);
|
||||
return patient is null ? NotFound() : Ok(ToDto(patient));
|
||||
}
|
||||
|
||||
[HttpGet("{patientId:guid}")]
|
||||
|
||||
@@ -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; }
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// <auto-generated />
|
||||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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<Guid>("PatientId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("patient_id");
|
||||
|
||||
b.Property<string>("AccountId")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("account_id");
|
||||
|
||||
b.Property<string>("ContactInfo")
|
||||
.HasColumnType("character varying")
|
||||
.HasColumnName("contact_info");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp without time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<DateOnly>("DateOfBirth")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date_of_birth");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("character varying")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<DateTime>("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
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PatientProfileService.Persistence.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AccountProfileAssociation : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "account_id",
|
||||
table: "patient",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_patient_account_id",
|
||||
table: "patient",
|
||||
column: "account_id",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_patient_account_id",
|
||||
table: "patient");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "account_id",
|
||||
table: "patient");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,10 @@ namespace PatientProfileService.Persistence.Migrations
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("patient_id");
|
||||
|
||||
b.Property<string>("AccountId")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("account_id");
|
||||
|
||||
b.Property<string>("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
|
||||
|
||||
@@ -12,6 +12,8 @@ public sealed class PatientDbContext(DbContextOptions<PatientDbContext> options)
|
||||
var patient = modelBuilder.Entity<Patient>();
|
||||
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");
|
||||
|
||||
@@ -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<Patient> 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<Patient?> FindByAccountIdAsync(string accountId, CancellationToken cancellationToken) =>
|
||||
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.AccountId == accountId, cancellationToken);
|
||||
|
||||
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
|
||||
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
+24
-3
@@ -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
|
||||
|
||||
|
||||
Reference in new issue
Block a user