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
@@ -1,8 +1,21 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
Services__PatientProfile__BaseUrl=http://patient-profile.example.test:5081/
|
||||
Services__PatientProfile__BaseUrl=https://patient-profile.example.test:5081/
|
||||
ASPNETCORE_URLS=https://0.0.0.0:5443
|
||||
Kestrel__Certificates__Default__Path=/etc/healthapp/gateway.pfx
|
||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||
Services__Observation__BaseUrl=http://observation.example.test:5082/
|
||||
Services__Observation__BaseUrl=https://observation.example.test:5082/
|
||||
|
||||
Services__Insights__BaseUrl=http://insights.example.test:5083/
|
||||
Services__Insights__BaseUrl=https://insights.example.test:5083/
|
||||
|
||||
Authentication__KeyDirectory=/var/lib/healthapp-api-gateway/keys
|
||||
Authentication__TokenLifetimeMinutes=30
|
||||
# Account identifiers support ASCII letters, digits, hyphen and underscore.
|
||||
Authentication__Accounts__0__AccountId=example-patient
|
||||
Authentication__Accounts__0__Role=Patient
|
||||
Authentication__Accounts__0__PasswordHash=REPLACE_WITH_ASPNET_CORE_PASSWORD_HASH
|
||||
# Use distinct randomly generated credentials of at least 32 characters.
|
||||
Services__PatientProfile__Key=REPLACE_ME
|
||||
Services__Observation__Key=REPLACE_ME
|
||||
Services__Insights__Key=REPLACE_ME
|
||||
InternalAccess__Observation__Key=REPLACE_ME
|
||||
InternalAccess__Insights__Key=REPLACE_ME
|
||||
@@ -1,3 +1,8 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5083
|
||||
ASPNETCORE_URLS=https://0.0.0.0:5083
|
||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||
|
||||
InternalAccess__GatewayKey=REPLACE_ME
|
||||
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||
Services__ApiGateway__Key=REPLACE_ME
|
||||
@@ -1,4 +1,9 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5082
|
||||
ASPNETCORE_URLS=https://0.0.0.0:5082
|
||||
ConnectionStrings__ObservationDatabase="Host=database.example.test;Port=5432;Database=observations;Username=observations;Password=REPLACE_ME"
|
||||
Services__ApiGateway__BaseUrl=https://gateway.example.test:5443/
|
||||
|
||||
InternalAccess__GatewayKey=REPLACE_ME
|
||||
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||
Services__ApiGateway__Key=REPLACE_ME
|
||||
@@ -1,3 +1,7 @@
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_URLS=http://0.0.0.0:5081
|
||||
ASPNETCORE_URLS=https://0.0.0.0:5081
|
||||
ConnectionStrings__PatientDatabase="Host=database.example.test;Port=5432;Database=patient_profile;Username=patient_profile;Password=REPLACE_ME"
|
||||
|
||||
InternalAccess__GatewayKey=REPLACE_ME
|
||||
Kestrel__Certificates__Default__Path=/etc/healthapp/service.pfx
|
||||
Kestrel__Certificates__Default__Password=REPLACE_ME
|
||||
@@ -4,6 +4,8 @@ Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
StateDirectory=healthapp-api-gateway
|
||||
StateDirectoryMode=0700
|
||||
Type=simple
|
||||
User=healthapp
|
||||
Group=healthapp
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -16,4 +16,7 @@
|
||||
<ProjectReference Include="../../src/InsightsService/InsightsService.csproj" />
|
||||
<ProjectReference Include="../../src/ObservationService/ObservationService.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,3 +1,5 @@
|
||||
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
@@ -22,6 +24,11 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
||||
public string ConnectionString { get; private set; } = "";
|
||||
public HttpClient Client { get; private set; } = null!;
|
||||
public HttpClient RawClient { get; private set; } = null!;
|
||||
public HttpClient CreateDirectPatientClient() => service!.CreateClient();
|
||||
public HttpClient CreateDirectObservationClient() => observation!.CreateClient();
|
||||
public HttpClient CreateDirectInsightsClient() => insights!.CreateClient();
|
||||
public AuthenticatedTestClient Authentication { get; } = new();
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
@@ -57,31 +64,39 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
{
|
||||
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
|
||||
});
|
||||
service.UseKestrel(0);
|
||||
using var serviceClient = service.CreateClient();
|
||||
|
||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" }));
|
||||
});
|
||||
gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services =>
|
||||
services.PostConfigure<BearerTokenOptions>("Bearer", options => options.TimeProvider = Authentication.Clock)));
|
||||
gateway.UseKestrel(0);
|
||||
Client = gateway.CreateClient();
|
||||
RawClient = gateway.CreateClient();
|
||||
Client = Authentication.Wrap(RawClient);
|
||||
observation = new WebApplicationFactory<ObservationService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["ConnectionStrings:ObservationDatabase"] = ObservationConnectionString,
|
||||
["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString()
|
||||
["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(),
|
||||
["InternalAccess:GatewayKey"] = Authentication.GatewayKey,
|
||||
["Services:ApiGateway:Key"] = Authentication.ObservationServiceKey
|
||||
}));
|
||||
});
|
||||
observation.UseKestrel(0);
|
||||
@@ -89,9 +104,10 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
gateway.Services.GetRequiredService<IConfiguration>()["Services:Observation:BaseUrl"] = observationClient.BaseAddress!.ToString();
|
||||
insights = new WebApplicationFactory<InsightsService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString() }));
|
||||
new Dictionary<string, string?> { ["Services:ApiGateway:BaseUrl"] = Client.BaseAddress!.ToString(), ["InternalAccess:GatewayKey"] = Authentication.GatewayKey, ["Services:ApiGateway:Key"] = Authentication.InsightsServiceKey }));
|
||||
});
|
||||
insights.UseKestrel(0);
|
||||
using var insightsClient = insights.CreateClient();
|
||||
@@ -101,6 +117,7 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
public async Task RestartHostsAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
RawClient.Dispose();
|
||||
await insights!.DisposeAsync();
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
await gateway!.DisposeAsync();
|
||||
@@ -123,10 +140,12 @@ public sealed class ObservationApiFixture : IAsyncLifetime
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
Client?.Dispose();
|
||||
RawClient?.Dispose();
|
||||
if (insights is not null) await insights.DisposeAsync();
|
||||
if (observation is not null) await observation.DisposeAsync();
|
||||
if (gateway is not null) await gateway.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true);
|
||||
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
||||
|
||||
NpgsqlConnection.ClearAllPools();
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Xunit;
|
||||
|
||||
namespace Observation.AcceptanceTests;
|
||||
|
||||
public sealed class PatientAuthenticationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
|
||||
{
|
||||
private static int nextAccount = 150;
|
||||
private sealed record Profile(Guid PatientId);
|
||||
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic);
|
||||
private static object ProfileRequest => new { name = "Patient", dateOfBirth = "1980-01-01" };
|
||||
private static object ObservationRequest => new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
|
||||
|
||||
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token = null, object? body = null)
|
||||
{
|
||||
using var request = new HttpRequestMessage(method, path);
|
||||
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
if (body is not null) request.Content = JsonContent.Create(body);
|
||||
return await fixture.RawClient.SendAsync(request);
|
||||
}
|
||||
|
||||
private async Task<(string Token, Guid PatientId, string Account)> Patient()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
return (token, (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId, account);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Login_without_profile_returns_normalized_identity_and_no_patient_data()
|
||||
{
|
||||
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
|
||||
new { accountId = "test-0", password = AuthenticatedTestClient.Password, role = "HealthcareProfessional" });
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("no-store", response.Headers.CacheControl!.ToString());
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal("test-0", json.RootElement.GetProperty("accountId").GetString());
|
||||
Assert.Equal("Patient", json.RootElement.GetProperty("role").GetString());
|
||||
Assert.Equal(1800, json.RootElement.GetProperty("expiresIn").GetInt32());
|
||||
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
|
||||
Assert.False(json.RootElement.TryGetProperty("refreshToken", out _));
|
||||
using var unavailable = await Send(HttpMethod.Get, $"/api/patients/{Guid.NewGuid()}", json.RootElement.GetProperty("accessToken").GetString());
|
||||
Assert.Equal(HttpStatusCode.NotFound, unavailable.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_account_and_invalid_password_have_same_rejection()
|
||||
{
|
||||
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "absent", password = AuthenticatedTestClient.Password });
|
||||
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "test-0", password = "incorrect" });
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, unknown.StatusCode);
|
||||
Assert.Equal(unknown.StatusCode, incorrect.StatusCode);
|
||||
Assert.Equal(await unknown.Content.ReadAsStringAsync(), await incorrect.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("POST", "patients")]
|
||||
[InlineData("GET", "patients/me")]
|
||||
[InlineData("PUT", "patients/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("GET", "observations/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("PUT", "observations/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("DELETE", "observations/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("POST", "patients/00000000-0000-0000-0000-000000000001/observations")]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations/latest")]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations")]
|
||||
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/insights")]
|
||||
public async Task Missing_and_invalid_tokens_reject_every_existing_patient_operation(string method, string path)
|
||||
{
|
||||
await using var patients = fixture.CreateDbContext();
|
||||
await using var observations = fixture.CreateObservationDbContext();
|
||||
var patientCount = await patients.Patients.CountAsync();
|
||||
var observationCount = await observations.Observations.CountAsync();
|
||||
foreach (var token in new string?[] { null, "unverifiable" })
|
||||
{
|
||||
using var response = await Send(new HttpMethod(method), "/api/" + path, token, method == "GET" ? null : ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.DoesNotContain("Patient", await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
Assert.Equal(patientCount, await patients.Patients.CountAsync());
|
||||
Assert.Equal(observationCount, await observations.Observations.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected()
|
||||
{
|
||||
var first = await Patient();
|
||||
var second = await Patient();
|
||||
using var record = await Send(HttpMethod.Post, $"/api/patients/{first.PatientId}/observations", first.Token, ObservationRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, record.StatusCode);
|
||||
var observation = (await record.Content.ReadFromJsonAsync<Observation>())!;
|
||||
var paths = new[] { $"patients/{first.PatientId}", $"patients/{first.PatientId}/observations",
|
||||
$"patients/{first.PatientId}/observations/latest", $"patients/{first.PatientId}/insights", $"observations/{observation.ObservationId}" };
|
||||
foreach (var path in paths)
|
||||
{
|
||||
var query = path.EndsWith("/observations") || path.EndsWith("/insights") ? "?from=2026-09-01&to=2026-10-01" : "";
|
||||
using var own = await Send(HttpMethod.Get, "/api/" + path + query, first.Token);
|
||||
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||
using var other = await Send(HttpMethod.Get, "/api/" + path + query, second.Token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
|
||||
Assert.Empty(await other.Content.ReadAsStringAsync());
|
||||
}
|
||||
foreach (var (method, path, body) in new[]
|
||||
{
|
||||
(HttpMethod.Put, $"patients/{first.PatientId}", ProfileRequest),
|
||||
(HttpMethod.Post, $"patients/{first.PatientId}/observations", ObservationRequest),
|
||||
(HttpMethod.Put, $"observations/{observation.ObservationId}", ObservationRequest),
|
||||
(HttpMethod.Delete, $"observations/{observation.ObservationId}", (object?)null)
|
||||
})
|
||||
{
|
||||
using var response = await Send(method, "/api/" + path, second.Token, body);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
using var retained = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", first.Token);
|
||||
Assert.Equal(128, (await retained.Content.ReadFromJsonAsync<Observation>())!.Systolic);
|
||||
await using var db = fixture.CreateObservationDbContext();
|
||||
Assert.Single(await db.Observations.Where(o => o.PatientId == first.PatientId).ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Caller_supplied_account_identity_cannot_replace_authenticated_identity()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
|
||||
request.Headers.Authorization = new("Bearer", token);
|
||||
request.Headers.Add("X-Account-Id", "test-0");
|
||||
using var response = await fixture.RawClient.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
var id = (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
|
||||
Assert.Equal(account, (await db.Patients.SingleAsync(p => p.PatientId == id)).AccountId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Profile_creation_retries_and_concurrency_preserve_one_persistent_association()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
var responses = await Task.WhenAll(Send(HttpMethod.Post, "/api/patients", token, ProfileRequest), Send(HttpMethod.Post, "/api/patients", token, ProfileRequest));
|
||||
try
|
||||
{
|
||||
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
|
||||
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
|
||||
var profile = (await responses.Single(r => r.StatusCode == HttpStatusCode.Created).Content.ReadFromJsonAsync<Profile>())!;
|
||||
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
|
||||
await fixture.RestartHostsAsync();
|
||||
using var read = await Send(HttpMethod.Get, "/api/patients/me", token);
|
||||
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
|
||||
Assert.Equal(profile.PatientId, (await read.Content.ReadFromJsonAsync<Profile>())!.PatientId);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
}
|
||||
finally { foreach (var response in responses) response.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_creation_can_be_retried_without_an_orphan_profile()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
await fixture.StopPatientServiceAsync();
|
||||
using var failed = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.BadGateway, failed.StatusCode);
|
||||
await fixture.RestartHostsAsync();
|
||||
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Expired_token_is_rejected_and_login_produces_a_fresh_token()
|
||||
{
|
||||
var patient = await Patient();
|
||||
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
|
||||
try
|
||||
{
|
||||
using var expired = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", patient.Token);
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, patient.Account);
|
||||
using var renewed = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", token);
|
||||
Assert.Equal(HttpStatusCode.OK, renewed.StatusCode);
|
||||
}
|
||||
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Tampering_with_a_valid_token_is_rejected()
|
||||
{
|
||||
var patient = await Patient();
|
||||
var token = patient.Token.ToCharArray();
|
||||
var position = token.Length / 2;
|
||||
token[position] = token[position] == 'A' ? 'B' : 'A';
|
||||
using var response = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", new string(token));
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Database_failure_rolls_back_profile_and_association_together()
|
||||
{
|
||||
var account = "test-" + Interlocked.Increment(ref nextAccount);
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
|
||||
await using var db = fixture.CreateDbContext();
|
||||
await db.Database.ExecuteSqlRawAsync("""
|
||||
CREATE FUNCTION fail_profile_test() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.name = 'simulate-write-failure' THEN RAISE EXCEPTION 'test write failure'; END IF;
|
||||
RETURN NEW;
|
||||
END; $$;
|
||||
CREATE TRIGGER fail_profile_test BEFORE INSERT ON patient FOR EACH ROW EXECUTE FUNCTION fail_profile_test();
|
||||
""");
|
||||
try
|
||||
{
|
||||
using var failed = await Send(HttpMethod.Post, "/api/patients", token,
|
||||
new { name = "simulate-write-failure", dateOfBirth = "1980-01-01" });
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
|
||||
Assert.Empty(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
|
||||
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.Database.ExecuteSqlRawAsync("DROP TRIGGER fail_profile_test ON patient; DROP FUNCTION fail_profile_test();");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Direct_services_reject_client_tokens_missing_keys_and_forged_keys()
|
||||
{
|
||||
var patient = await Patient();
|
||||
foreach (var client in new[] { fixture.CreateDirectPatientClient(), fixture.CreateDirectObservationClient(), fixture.CreateDirectInsightsClient() })
|
||||
{
|
||||
using (client)
|
||||
{
|
||||
client.DefaultRequestHeaders.Authorization = new("Bearer", patient.Token);
|
||||
foreach (var key in new string?[] { null, "forged" })
|
||||
{
|
||||
client.DefaultRequestHeaders.Remove("X-Gateway-Key");
|
||||
if (key is not null) client.DefaultRequestHeaders.Add("X-Gateway-Key", key);
|
||||
using var response = await client.GetAsync($"/api/patients/{patient.PatientId}");
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Service_credentials_are_limited_to_their_documented_read_calls()
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
|
||||
request.Headers.Add("X-Service-Key", fixture.Authentication.ObservationServiceKey);
|
||||
using var response = await fixture.RawClient.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
using var forbidden = new HttpRequestMessage(HttpMethod.Get, "/api/patients/by-account/test-0");
|
||||
forbidden.Headers.Add("X-Service-Key", fixture.Authentication.InsightsServiceKey);
|
||||
using var rejected = await fixture.RawClient.SendAsync(forbidden);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Healthcare_professional_cannot_create_profiles()
|
||||
{
|
||||
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
|
||||
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class AuthenticationIntegrationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Production_gateway_rejects_plain_http_even_for_login_and_public_guidance()
|
||||
{
|
||||
var authentication = new AuthenticatedTestClient();
|
||||
try
|
||||
{
|
||||
var configuration = authentication.Configuration();
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
configuration[$"Services:{service}:BaseUrl"] = "https://service.example.test/";
|
||||
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Production");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
|
||||
});
|
||||
using var http = host.CreateClient();
|
||||
using var guidance = await http.GetAsync("/api/measurement-guidance");
|
||||
Assert.Equal(HttpStatusCode.BadRequest, guidance.StatusCode);
|
||||
using var login = await http.PostAsync("/api/authentication/login", new StringContent("{}", Encoding.UTF8, "application/json"));
|
||||
Assert.Equal(HttpStatusCode.BadRequest, login.StatusCode);
|
||||
using var https = host.CreateClient(new WebApplicationFactoryClientOptions { BaseAddress = new Uri("https://localhost") });
|
||||
using var available = await https.GetAsync("/api/measurement-guidance");
|
||||
Assert.Equal(HttpStatusCode.OK, available.StatusCode);
|
||||
}
|
||||
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy()
|
||||
{
|
||||
var authentication = new AuthenticatedTestClient();
|
||||
var patient = Guid.NewGuid();
|
||||
try
|
||||
{
|
||||
var configuration = authentication.Configuration();
|
||||
foreach (var service in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
configuration[$"Services:{service}:BaseUrl"] = "http://service.example.test/";
|
||||
using var host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration));
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddAuthentication().AddScheme<AuthenticationSchemeOptions, ReplacementHandler>("Replacement", null);
|
||||
services.PostConfigure<PolicySchemeOptions>("ClientOrService", options => options.ForwardDefaultSelector = _ => "Replacement");
|
||||
services.AddHttpClient("PatientProfile").ConfigurePrimaryHttpMessageHandler(() => new PatientHandler(patient));
|
||||
});
|
||||
});
|
||||
using var client = host.CreateClient();
|
||||
using var own = await client.GetAsync($"/api/patients/{patient}");
|
||||
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
|
||||
using var other = await client.GetAsync($"/api/patients/{Guid.NewGuid()}");
|
||||
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
|
||||
Assert.Empty(await other.Content.ReadAsStringAsync());
|
||||
}
|
||||
finally { if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true); }
|
||||
}
|
||||
|
||||
public sealed class ReplacementHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(
|
||||
AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, "test-0"), new Claim(ClaimTypes.Role, "Patient")
|
||||
}, Scheme.Name)), Scheme.Name)));
|
||||
}
|
||||
|
||||
private sealed class PatientHandler(Guid patientId) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Assert.True(request.Headers.Contains("X-Gateway-Key"));
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent($"{{\"patientId\":\"{patientId}\"}}", Encoding.UTF8, "application/json")
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using System.Net;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -12,12 +14,14 @@ public sealed class MeasurementGuidanceTests : IDisposable
|
||||
private readonly WebApplicationFactory<ApiGateway.Program> host;
|
||||
private readonly HttpClient client;
|
||||
private int upstreamCalls;
|
||||
private readonly AuthenticatedTestClient authentication = new();
|
||||
|
||||
public MeasurementGuidanceTests()
|
||||
{
|
||||
host = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(authentication.Configuration()).AddInMemoryCollection(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
@@ -118,6 +122,7 @@ public sealed class MeasurementGuidanceTests : IDisposable
|
||||
{
|
||||
client.Dispose();
|
||||
host.Dispose();
|
||||
if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true);
|
||||
}
|
||||
|
||||
private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
using Microsoft.AspNetCore.Authentication.BearerToken;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
@@ -17,6 +20,8 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
||||
private WebApplicationFactory<ApiGateway.Program>? gateway;
|
||||
public string ConnectionString { get; private set; } = "";
|
||||
public HttpClient Client { get; private set; } = null!;
|
||||
public HttpClient RawClient { get; private set; } = null!;
|
||||
public AuthenticatedTestClient Authentication { get; } = new();
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
@@ -42,24 +47,29 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
||||
{
|
||||
service = new WebApplicationFactory<PatientProfileService.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0));
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString }));
|
||||
new Dictionary<string, string?> { ["ConnectionStrings:PatientDatabase"] = ConnectionString, ["InternalAccess:GatewayKey"] = Authentication.GatewayKey }));
|
||||
});
|
||||
service.UseKestrel(0);
|
||||
using var serviceClient = service.CreateClient();
|
||||
|
||||
gateway = new WebApplicationFactory<ApiGateway.Program>().WithWebHostBuilder(builder =>
|
||||
builder.ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(
|
||||
builder.UseEnvironment("Development").ConfigureAppConfiguration((_, configuration) => configuration.AddInMemoryCollection(Authentication.Configuration()).AddInMemoryCollection(
|
||||
new Dictionary<string, string?> { ["Services:PatientProfile:BaseUrl"] = serviceClient.BaseAddress!.ToString(),
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/" })));
|
||||
Client = gateway.CreateClient();
|
||||
gateway = gateway.WithWebHostBuilder(builder => builder.ConfigureServices(services =>
|
||||
services.PostConfigure<BearerTokenOptions>("Bearer", options => options.TimeProvider = Authentication.Clock)));
|
||||
RawClient = gateway.CreateClient();
|
||||
Client = Authentication.Wrap(RawClient);
|
||||
}
|
||||
|
||||
public async Task RestartHostsAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
RawClient.Dispose();
|
||||
await gateway!.DisposeAsync();
|
||||
await service!.DisposeAsync();
|
||||
StartHosts();
|
||||
@@ -68,8 +78,10 @@ public sealed class PatientApiFixture : IAsyncLifetime
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
Client?.Dispose();
|
||||
RawClient?.Dispose();
|
||||
if (gateway is not null) await gateway.DisposeAsync();
|
||||
if (service is not null) await service.DisposeAsync();
|
||||
if (Directory.Exists(Authentication.KeyDirectory)) Directory.Delete(Authentication.KeyDirectory, true);
|
||||
if (string.IsNullOrEmpty(adminConnectionString)) return;
|
||||
|
||||
NpgsqlConnection.ClearAllPools();
|
||||
|
||||
@@ -14,4 +14,7 @@
|
||||
<ProjectReference Include="../../src/PatientProfileService/PatientProfileService.csproj" />
|
||||
<ProjectReference Include="../../src/ApiGateway/ApiGateway.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="../Support/AuthenticatedTestClient.cs" Link="Support/AuthenticatedTestClient.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,102 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using ApiGateway.Security;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace HealthApp.TestSupport;
|
||||
|
||||
// Existing functional tests use real login and an authorised account for each resource.
|
||||
// Security tests use RawClient instead to exercise rejected requests explicitly.
|
||||
public sealed class AuthenticatedTestClient
|
||||
{
|
||||
public const string Password = "synthetic-test-password";
|
||||
public readonly string GatewayKey = new('g', 48);
|
||||
public readonly string ObservationServiceKey = new('o', 48);
|
||||
public readonly string InsightsServiceKey = new('i', 48);
|
||||
public TestClock Clock { get; } = new();
|
||||
public string KeyDirectory { get; } = Path.Combine(Path.GetTempPath(), "healthapp-keys-" + Guid.NewGuid());
|
||||
public ConcurrentDictionary<Guid, string> PatientAccounts { get; } = new();
|
||||
private readonly ConcurrentDictionary<Guid, string> observationAccounts = new();
|
||||
private readonly ConcurrentDictionary<string, string> tokens = new();
|
||||
private int accountNumber;
|
||||
private string lastAccount = "test-0";
|
||||
private readonly string hash = new PasswordHasher<PrototypeAccount>().HashPassword(new(), Password);
|
||||
|
||||
public Dictionary<string, string?> Configuration()
|
||||
{
|
||||
var values = new Dictionary<string, string?>
|
||||
{
|
||||
["Authentication:KeyDirectory"] = KeyDirectory,
|
||||
["Services:PatientProfile:Key"] = GatewayKey,
|
||||
["Services:Observation:Key"] = GatewayKey,
|
||||
["Services:Insights:Key"] = GatewayKey,
|
||||
["InternalAccess:Observation:Key"] = ObservationServiceKey,
|
||||
["InternalAccess:Insights:Key"] = InsightsServiceKey
|
||||
};
|
||||
for (var i = 0; i < 256; i++)
|
||||
{
|
||||
values[$"Authentication:Accounts:{i}:AccountId"] = "test-" + i;
|
||||
values[$"Authentication:Accounts:{i}:PasswordHash"] = hash;
|
||||
values[$"Authentication:Accounts:{i}:Role"] = "Patient";
|
||||
}
|
||||
values["Authentication:Accounts:256:AccountId"] = "professional";
|
||||
values["Authentication:Accounts:256:PasswordHash"] = hash;
|
||||
values["Authentication:Accounts:256:Role"] = "HealthcareProfessional";
|
||||
return values;
|
||||
}
|
||||
|
||||
public HttpClient Wrap(HttpClient raw) => new(new Handler(this, raw)) { BaseAddress = raw.BaseAddress };
|
||||
|
||||
public static async Task<string> LoginAsync(HttpClient raw, string account = "test-0", string password = Password)
|
||||
{
|
||||
using var response = await raw.PostAsJsonAsync("/api/authentication/login", new { accountId = account, password });
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
return json.RootElement.GetProperty("accessToken").GetString()!;
|
||||
}
|
||||
|
||||
private sealed class Handler(AuthenticatedTestClient owner, HttpClient raw) : HttpMessageHandler
|
||||
{
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var path = request.RequestUri!.AbsolutePath;
|
||||
var parts = path.Trim('/').Split('/');
|
||||
var account = owner.lastAccount;
|
||||
if (path == "/api/patients" && request.Method == HttpMethod.Post)
|
||||
account = "test-" + Interlocked.Increment(ref owner.accountNumber);
|
||||
else if (parts.Length >= 3 && Guid.TryParse(parts[2], out var id))
|
||||
{
|
||||
var map = parts[1] == "patients" ? owner.PatientAccounts : owner.observationAccounts;
|
||||
if (map.TryGetValue(id, out var found)) account = found;
|
||||
}
|
||||
if (!owner.tokens.TryGetValue(account, out var token))
|
||||
{
|
||||
token = await LoginAsync(raw, account);
|
||||
owner.tokens[account] = token;
|
||||
}
|
||||
using var forwarded = new HttpRequestMessage(request.Method, request.RequestUri) { Content = request.Content };
|
||||
foreach (var header in request.Headers) forwarded.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
forwarded.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
var response = await raw.SendAsync(forwarded, cancellationToken);
|
||||
if (response.IsSuccessStatusCode && request.Method == HttpMethod.Post)
|
||||
{
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
|
||||
if (json.RootElement.TryGetProperty("patientId", out var patient))
|
||||
owner.PatientAccounts[patient.GetGuid()] = account;
|
||||
if (json.RootElement.TryGetProperty("observationId", out var observation))
|
||||
owner.observationAccounts[observation.GetGuid()] = account;
|
||||
owner.lastAccount = account;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TestClock : TimeProvider
|
||||
{
|
||||
private DateTimeOffset now = DateTimeOffset.UtcNow;
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
public void Advance(TimeSpan span) => now += span;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
// Read from standard input, never from a command-line argument or environment dump.
|
||||
var password = Console.ReadLine();
|
||||
if (string.IsNullOrEmpty(password))
|
||||
{
|
||||
Console.Error.WriteLine("Supply a nonempty password on standard input.");
|
||||
return 1;
|
||||
}
|
||||
Console.WriteLine(new PasswordHasher<object>().HashPassword(new object(), password));
|
||||
return 0;
|
||||
Reference in new issue
Block a user