Files

263 lines
15 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HealthApp.TestSupport;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Observation.AcceptanceTests;
public sealed class PatientAuthenticationTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private static int nextAccount = 150;
private sealed record Profile(Guid PatientId);
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic);
private static object ProfileRequest => new { name = "Patient", dateOfBirth = "1980-01-01" };
private static object ObservationRequest => new { measuredAt = "2026-09-12T08:00:00", systolic = 128, diastolic = 82, pulse = 68 };
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token = null, object? body = null)
{
using var request = new HttpRequestMessage(method, path);
if (token is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body is not null) request.Content = JsonContent.Create(body);
return await fixture.RawClient.SendAsync(request);
}
private async Task<(string Token, Guid PatientId, string Account)> Patient()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (token, (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId, account);
}
[Fact]
public async Task Login_without_profile_returns_normalized_identity_and_no_patient_data()
{
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
new { accountId = "test-0", password = AuthenticatedTestClient.Password, role = "HealthcareProfessional" });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("no-store", response.Headers.CacheControl!.ToString());
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("test-0", json.RootElement.GetProperty("accountId").GetString());
Assert.Equal("Patient", json.RootElement.GetProperty("role").GetString());
Assert.Equal(1800, json.RootElement.GetProperty("expiresIn").GetInt32());
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
Assert.False(json.RootElement.TryGetProperty("refreshToken", out _));
using var unavailable = await Send(HttpMethod.Get, $"/api/patients/{Guid.NewGuid()}", json.RootElement.GetProperty("accessToken").GetString());
Assert.Equal(HttpStatusCode.NotFound, unavailable.StatusCode);
}
[Fact]
public async Task Invalid_account_and_invalid_password_have_same_rejection()
{
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "absent", password = AuthenticatedTestClient.Password });
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "test-0", password = "incorrect" });
Assert.Equal(HttpStatusCode.Unauthorized, unknown.StatusCode);
Assert.Equal(unknown.StatusCode, incorrect.StatusCode);
Assert.Equal(await unknown.Content.ReadAsStringAsync(), await incorrect.Content.ReadAsStringAsync());
}
[Theory]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001")]
[InlineData("POST", "patients")]
[InlineData("GET", "patients/me")]
[InlineData("PUT", "patients/00000000-0000-0000-0000-000000000001")]
[InlineData("GET", "observations/00000000-0000-0000-0000-000000000001")]
[InlineData("PUT", "observations/00000000-0000-0000-0000-000000000001")]
[InlineData("DELETE", "observations/00000000-0000-0000-0000-000000000001")]
[InlineData("POST", "patients/00000000-0000-0000-0000-000000000001/observations")]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations/latest")]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/observations")]
[InlineData("GET", "patients/00000000-0000-0000-0000-000000000001/insights")]
public async Task Missing_and_invalid_tokens_reject_every_existing_patient_operation(string method, string path)
{
await using var patients = fixture.CreateDbContext();
await using var observations = fixture.CreateObservationDbContext();
var patientCount = await patients.Patients.CountAsync();
var observationCount = await observations.Observations.CountAsync();
foreach (var token in new string?[] { null, "unverifiable" })
{
using var response = await Send(new HttpMethod(method), "/api/" + path, token, method == "GET" ? null : ProfileRequest);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.DoesNotContain("Patient", await response.Content.ReadAsStringAsync());
}
Assert.Equal(patientCount, await patients.Patients.CountAsync());
Assert.Equal(observationCount, await observations.Observations.CountAsync());
}
[Fact]
public async Task Own_observations_and_insights_are_available_but_another_patients_reads_and_writes_are_rejected()
{
var first = await Patient();
var second = await Patient();
using var record = await Send(HttpMethod.Post, $"/api/patients/{first.PatientId}/observations", first.Token, ObservationRequest);
Assert.Equal(HttpStatusCode.Created, record.StatusCode);
var observation = (await record.Content.ReadFromJsonAsync<Observation>())!;
var paths = new[] { $"patients/{first.PatientId}", $"patients/{first.PatientId}/observations",
$"patients/{first.PatientId}/observations/latest", $"patients/{first.PatientId}/insights", $"observations/{observation.ObservationId}" };
foreach (var path in paths)
{
var query = path.EndsWith("/observations") || path.EndsWith("/insights") ? "?from=2026-09-01&to=2026-10-01" : "";
using var own = await Send(HttpMethod.Get, "/api/" + path + query, first.Token);
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
using var other = await Send(HttpMethod.Get, "/api/" + path + query, second.Token);
Assert.Equal(HttpStatusCode.NotFound, other.StatusCode);
Assert.Empty(await other.Content.ReadAsStringAsync());
}
foreach (var (method, path, body) in new[]
{
(HttpMethod.Put, $"patients/{first.PatientId}", ProfileRequest),
(HttpMethod.Post, $"patients/{first.PatientId}/observations", ObservationRequest),
(HttpMethod.Put, $"observations/{observation.ObservationId}", ObservationRequest),
(HttpMethod.Delete, $"observations/{observation.ObservationId}", (object?)null)
})
{
using var response = await Send(method, "/api/" + path, second.Token, body);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
using var retained = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", first.Token);
Assert.Equal(128, (await retained.Content.ReadFromJsonAsync<Observation>())!.Systolic);
await using var db = fixture.CreateObservationDbContext();
Assert.Single(await db.Observations.Where(o => o.PatientId == first.PatientId).ToListAsync());
}
[Fact]
public async Task Caller_supplied_account_identity_cannot_replace_authenticated_identity()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/patients") { Content = JsonContent.Create(ProfileRequest) };
request.Headers.Authorization = new("Bearer", token);
request.Headers.Add("X-Account-Id", "test-0");
using var response = await fixture.RawClient.SendAsync(request);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
await using var db = fixture.CreateDbContext();
var id = (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
Assert.Equal(account, (await db.Patients.SingleAsync(p => p.PatientId == id)).AccountId);
}
[Fact]
public async Task Profile_creation_retries_and_concurrency_preserve_one_persistent_association()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
var responses = await Task.WhenAll(Send(HttpMethod.Post, "/api/patients", token, ProfileRequest), Send(HttpMethod.Post, "/api/patients", token, ProfileRequest));
try
{
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Created);
Assert.Single(responses, r => r.StatusCode == HttpStatusCode.Conflict);
var profile = (await responses.Single(r => r.StatusCode == HttpStatusCode.Created).Content.ReadFromJsonAsync<Profile>())!;
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Conflict, retry.StatusCode);
await fixture.RestartHostsAsync();
using var read = await Send(HttpMethod.Get, "/api/patients/me", token);
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
Assert.Equal(profile.PatientId, (await read.Content.ReadFromJsonAsync<Profile>())!.PatientId);
await using var db = fixture.CreateDbContext();
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
}
finally { foreach (var response in responses) response.Dispose(); }
}
[Fact]
public async Task Failed_creation_can_be_retried_without_an_orphan_profile()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
await fixture.StopPatientServiceAsync();
using var failed = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.BadGateway, failed.StatusCode);
await fixture.RestartHostsAsync();
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
await using var db = fixture.CreateDbContext();
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
}
[Fact]
public async Task Expired_token_is_rejected_and_login_produces_a_fresh_token()
{
var patient = await Patient();
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
try
{
using var expired = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", patient.Token);
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, patient.Account);
using var renewed = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", token);
Assert.Equal(HttpStatusCode.OK, renewed.StatusCode);
}
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
}
[Fact]
public async Task Tampering_with_a_valid_token_is_rejected()
{
var patient = await Patient();
var token = patient.Token.ToCharArray();
var position = token.Length / 2;
token[position] = token[position] == 'A' ? 'B' : 'A';
using var response = await Send(HttpMethod.Get, $"/api/patients/{patient.PatientId}", new string(token));
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task Database_failure_rolls_back_profile_and_association_together()
{
var account = "test-" + Interlocked.Increment(ref nextAccount);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
await using var db = fixture.CreateDbContext();
await db.Database.ExecuteSqlRawAsync("""
CREATE FUNCTION fail_profile_test() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.name = 'simulate-write-failure' THEN RAISE EXCEPTION 'test write failure'; END IF;
RETURN NEW;
END; $$;
CREATE TRIGGER fail_profile_test BEFORE INSERT ON patient FOR EACH ROW EXECUTE FUNCTION fail_profile_test();
""");
try
{
using var failed = await Send(HttpMethod.Post, "/api/patients", token,
new { name = "simulate-write-failure", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.InternalServerError, failed.StatusCode);
Assert.Empty(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
using var retry = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Created, retry.StatusCode);
Assert.Single(await db.Patients.Where(p => p.AccountId == account).ToListAsync());
}
finally
{
await db.Database.ExecuteSqlRawAsync("DROP TRIGGER fail_profile_test ON patient; DROP FUNCTION fail_profile_test();");
}
}
[Fact]
public async Task Sole_public_edge_accepts_client_ticket_but_service_headers_grant_no_access()
{
var patient = await Patient();
using var request = new HttpRequestMessage(HttpMethod.Get, $"/api/patients/{patient.PatientId}");
request.Headers.Authorization = new("Bearer", patient.Token); request.Headers.Add("X-Gateway-Key", "forged");
using var own = await fixture.RawClient.SendAsync(request); Assert.Equal(HttpStatusCode.OK, own.StatusCode);
using var bypass = new HttpRequestMessage(HttpMethod.Get, "/api/patients/by-account/" + patient.Account);
bypass.Headers.Authorization = new("Bearer", patient.Token);
using var absent = await fixture.RawClient.SendAsync(bypass); Assert.Equal(HttpStatusCode.NotFound, absent.StatusCode);
foreach (var path in new[] { "/api/patients", "/api/patients/by-account/test-0" })
{
using var forged = new HttpRequestMessage(path == "/api/patients" ? HttpMethod.Post : HttpMethod.Get, path) { Content = path == "/api/patients" ? JsonContent.Create(ProfileRequest) : null };
forged.Headers.Add("X-Service-Key", fixture.Authentication.ObservationServiceKey);
using var denied = await fixture.RawClient.SendAsync(forged); Assert.Equal(HttpStatusCode.Unauthorized, denied.StatusCode);
}
}
[Fact]
public async Task Healthcare_professional_cannot_create_profiles()
{
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
using var response = await Send(HttpMethod.Post, "/api/patients", token, ProfileRequest);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
}