Implement US-13 patient authentication and persistent ownership

This commit is contained in:
Steffen committed 2026-10-05 11:10:22 +02:00
1 parent ebf50827d6
commit 0ce9b2b168
36 files changed
+1203 -28

No files matched your search

@@ -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>
+102
View File
@@ -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;
}