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().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().WithWebHostBuilder(builder => { builder.UseEnvironment("Development"); builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(configuration)); builder.ConfigureServices(services => { services.AddAuthentication().AddScheme("Replacement", null); services.PostConfigure("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 options, ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler(options, logger, encoder) { protected override Task 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 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") }); } } }