Files
HealthAppRepository/tests/Support/AuthenticatedTestClient.cs
T

109 lines
5.4 KiB
C#

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";
for (var i = 257; i <= 258; i++)
{
values[$"Authentication:Accounts:{i}:AccountId"] = i == 257 ? "professional-second" : "professional-empty";
values[$"Authentication:Accounts:{i}:PasswordHash"] = hash;
values[$"Authentication:Accounts:{i}: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;
}