Establish single host with preserved login and public guidance
This commit is contained in:
1 parent
cee98e7035
commit
523cfbf42e
20 files changed
+1784
No files matched your search
@@ -0,0 +1,30 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Xunit;
|
||||
namespace HealthApp.AcceptanceTests;
|
||||
public sealed class FoundationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Framework_login_retains_identity_generic_failures_and_no_service_key_bypass()
|
||||
{
|
||||
var auth=new AuthenticatedTestClient();
|
||||
using var host=new WebApplicationFactory<Program>().WithWebHostBuilder(b=>b.UseEnvironment("Development").ConfigureAppConfiguration((_,c)=>c.AddInMemoryCollection(auth.Configuration())));
|
||||
using var client=host.CreateClient();
|
||||
using var login=await client.PostAsJsonAsync("/api/authentication/login",new {accountId="professional",password=AuthenticatedTestClient.Password});
|
||||
Assert.Equal(HttpStatusCode.OK,login.StatusCode);Assert.Equal("no-store",login.Headers.CacheControl!.ToString());
|
||||
using var json=JsonDocument.Parse(await login.Content.ReadAsStringAsync());
|
||||
Assert.Equal("HealthcareProfessional",json.RootElement.GetProperty("role").GetString());
|
||||
Assert.Equal(1800,json.RootElement.GetProperty("expiresIn").GetInt32());
|
||||
Assert.DoesNotContain("patientId",json.RootElement.GetRawText());
|
||||
using var badAccount=await client.PostAsJsonAsync("/api/authentication/login",new {accountId="missing",password=AuthenticatedTestClient.Password});
|
||||
using var badPassword=await client.PostAsJsonAsync("/api/authentication/login",new {accountId="test-0",password="wrong"});
|
||||
Assert.Equal(HttpStatusCode.Unauthorized,badAccount.StatusCode);Assert.Equal(await badAccount.Content.ReadAsStringAsync(),await badPassword.Content.ReadAsStringAsync());
|
||||
using var forged=new HttpRequestMessage(HttpMethod.Get,"/api/professionals/me/patients");forged.Headers.Add("X-Service-Key",auth.OverviewServiceKey);
|
||||
using var rejected=await client.SendAsync(forged);Assert.Equal(HttpStatusCode.Unauthorized,rejected.StatusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><IsTestProject>true</IsTestProject><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../src/HealthApp/HealthApp.csproj" /><PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/><PackageReference Include="xunit" Version="2.9.3"/><PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" PrivateAssets="all"/><PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.12"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,136 @@
|
||||
using System.Net;
|
||||
using HealthApp.TestSupport;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Xunit;
|
||||
|
||||
namespace PatientProfile.AcceptanceTests;
|
||||
|
||||
public sealed class MeasurementGuidanceTests : IDisposable
|
||||
{
|
||||
private readonly WebApplicationFactory<HealthApp.Program> host;
|
||||
private readonly HttpClient client;
|
||||
private int upstreamCalls;
|
||||
private readonly AuthenticatedTestClient authentication = new();
|
||||
|
||||
public MeasurementGuidanceTests()
|
||||
{
|
||||
host = new WebApplicationFactory<HealthApp.Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(authentication.Configuration()).AddInMemoryCollection(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["Services:PatientProfile:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Observation:BaseUrl"] = "http://127.0.0.1:1/",
|
||||
["Services:Insights:BaseUrl"] = "http://127.0.0.1:1/"
|
||||
}));
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
foreach (var name in new[] { "PatientProfile", "Observation", "Insights" })
|
||||
services.AddHttpClient(name).ConfigurePrimaryHttpMessageHandler(
|
||||
() => new RejectUpstreamHandler(() => Interlocked.Increment(ref upstreamCalls)));
|
||||
});
|
||||
});
|
||||
client = host.CreateClient();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("?setting=Unknown")]
|
||||
[InlineData("?setting=Home")]
|
||||
public async Task Public_guidance_without_patient_records_is_labelled_and_has_ordered_sourced_instructions(string query)
|
||||
{
|
||||
using var response = await client.GetAsync("/api/measurement-guidance" + query);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var result = json.RootElement;
|
||||
Assert.True(result.GetProperty("available").GetBoolean());
|
||||
Assert.Equal("Home", result.GetProperty("applicableSetting").GetString());
|
||||
Assert.Equal("AtRest", result.GetProperty("applicableActivityCondition").GetString());
|
||||
Assert.True(DateOnly.TryParse(result.GetProperty("reviewedOn").GetString(), out _));
|
||||
var steps = result.GetProperty("steps").EnumerateArray().ToArray();
|
||||
Assert.Equal(Enumerable.Range(1, 6), steps.Select(s => s.GetProperty("order").GetInt32()));
|
||||
var instructions = string.Join(" ", steps.Select(s => s.GetProperty("instruction").GetString()));
|
||||
foreach (var text in new[] { "validated upper-arm", "cuff", "five minutes", "back and arm supported",
|
||||
"still", "three readings", "three consecutive days", "one observation", "actual", "measurement time" })
|
||||
Assert.Contains(text, instructions);
|
||||
var sources = result.GetProperty("sources").EnumerateArray().ToArray();
|
||||
Assert.Equal(2, sources.Length);
|
||||
Assert.All(sources, source =>
|
||||
{
|
||||
Assert.StartsWith("https://www.sundhed.dk/", source.GetProperty("url").GetString());
|
||||
Assert.True(DateOnly.TryParse(source.GetProperty("updatedOn").GetString(), out _));
|
||||
});
|
||||
Assert.Contains("not a clinical measurement protocol", result.GetProperty("explanation").GetString());
|
||||
Assert.Contains("does not assess rhythm regularity", result.GetProperty("pulseExplanation").GetString());
|
||||
Assert.Contains("does not save or alter", result.GetProperty("limitations").GetString());
|
||||
Assert.Contains("prevent a valid submission", result.GetProperty("limitations").GetString());
|
||||
Assert.DoesNotContain("patientId", result.GetRawText());
|
||||
Assert.DoesNotContain("assignments", result.GetRawText());
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("DuringActivity")]
|
||||
[InlineData("AfterActivity")]
|
||||
public async Task Activity_is_not_relabelled_as_rest_or_certified(string activity)
|
||||
{
|
||||
using var response = await client.GetAsync($"/api/measurement-guidance?setting=Home&activityCondition={activity}");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var result = json.RootElement;
|
||||
Assert.Equal(activity, result.GetProperty("requestedActivityCondition").GetString());
|
||||
Assert.Contains("do not relabel", result.GetProperty("activityExplanation").GetString());
|
||||
Assert.Contains("remain valid to record", result.GetProperty("activityExplanation").GetString());
|
||||
Assert.Contains("does not record a setting or certify compliance", result.GetProperty("explanation").GetString());
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Clinic")]
|
||||
[InlineData("Other")]
|
||||
public async Task Unsupported_guidance_is_explicitly_unavailable_without_unverified_instructions(string setting)
|
||||
{
|
||||
using var response = await client.GetAsync($"/api/measurement-guidance?setting={setting}");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var result = json.RootElement;
|
||||
Assert.False(result.GetProperty("available").GetBoolean());
|
||||
Assert.Contains("unavailable", result.GetProperty("explanation").GetString());
|
||||
Assert.Empty(result.GetProperty("steps").EnumerateArray());
|
||||
Assert.Empty(result.GetProperty("sources").EnumerateArray());
|
||||
Assert.Equal(JsonValueKind.Null, result.GetProperty("applicableSetting").ValueKind);
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("setting=Unsupported")]
|
||||
[InlineData("activityCondition=Unsupported")]
|
||||
public async Task Invalid_categories_return_explained_rejections(string query)
|
||||
{
|
||||
using var response = await client.GetAsync("/api/measurement-guidance?" + query);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Contains("Unsupported", await response.Content.ReadAsStringAsync());
|
||||
Assert.Equal(0, upstreamCalls);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
client.Dispose();
|
||||
host.Dispose();
|
||||
if (Directory.Exists(authentication.KeyDirectory)) Directory.Delete(authentication.KeyDirectory, true);
|
||||
}
|
||||
|
||||
private sealed class RejectUpstreamHandler(Action called) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
called();
|
||||
throw new InvalidOperationException("Guidance must not read or write patient data.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using HealthApp.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 readonly string OverviewServiceKey = new('v', 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,
|
||||
["InternalAccess:HealthOverview:Key"] = OverviewServiceKey,
|
||||
["Services:HealthOverview:Key"] = GatewayKey,
|
||||
["Services:HealthOverview:BaseUrl"] = "http://127.0.0.1:1/"
|
||||
};
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user