Files

103 lines
5.4 KiB
C#

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", "HealthOverview" })
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); }
}
[Theory]
[InlineData("Patient", "test-0")]
[InlineData("HealthcareProfessional", "professional")]
public async Task Standard_replacement_handler_with_same_identity_retains_ownership_policy(string role, string accountId)
{
var authentication = new AuthenticatedTestClient();
var patient = Guid.NewGuid();
try
{
var configuration = authentication.Configuration();
configuration["TestIdentity:Role"] = role;
configuration["TestIdentity:AccountId"] = accountId;
configuration[$"Access:ProfessionalAssignments:{accountId}:0"] = patient.ToString();
foreach (var service in new[] { "PatientProfile", "Observation", "Insights", "HealthOverview" })
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, IConfiguration configuration)
: 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, configuration["TestIdentity:AccountId"]!), new Claim(ClaimTypes.Role, configuration["TestIdentity:Role"]!)
}, 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")
});
}
}
}