Implement US-13 patient authentication and persistent ownership
This commit is contained in:
1 parent
ebf50827d6
commit
0ce9b2b168
36 files changed
+1203
-28
No files matched your search
@@ -0,0 +1,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>
|
||||
Reference in new issue
Block a user