Files

280 lines
14 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 ProfessionalAccessTests(ObservationApiFixture fixture) : IClassFixture<ObservationApiFixture>
{
private const string AssignmentPath = "/api/professionals/me/patients";
private sealed record Profile(Guid PatientId, string Name);
private sealed record Observation(Guid ObservationId, Guid PatientId, int Systolic, string? Context, string? Note);
private sealed record AssignedPatient(Guid PatientId);
private async Task<Guid> CreatePatient()
{
using var response = await fixture.Client.PostAsJsonAsync("/api/patients", new { name = "Assigned Patient", dateOfBirth = "1980-01-01" });
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Profile>())!.PatientId;
}
private async Task<Observation> Record(Guid patientId)
{
using var response = await fixture.Client.PostAsJsonAsync($"/api/patients/{patientId}/observations", new
{
measuredAt = "2026-09-12T08:00:00",
systolic = 128,
diastolic = 82,
pulse = 68,
context = "Resting",
note = "Actual conditions"
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<Observation>())!;
}
private async Task Assign(Guid[] first, Guid[]? second = null)
{
fixture.AdditionalGatewayConfiguration.Clear();
for (var i = 0; i < first.Length; i++)
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional:{i}"] = first[i].ToString();
for (var i = 0; i < (second?.Length ?? 0); i++)
fixture.AdditionalGatewayConfiguration[$"Access:ProfessionalAssignments:professional-second:{i}"] = second![i].ToString();
await fixture.RestartHostsAsync();
}
private async Task<HttpResponseMessage> Send(HttpMethod method, string path, string? token, 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);
}
[Fact]
public async Task Login_recognizes_professional_identity_and_does_not_put_assignments_in_the_token_response()
{
using var response = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login",
new { accountId = "professional", password = AuthenticatedTestClient.Password, role = "Patient" });
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
Assert.Equal("HealthcareProfessional", json.RootElement.GetProperty("role").GetString());
Assert.Equal("professional", json.RootElement.GetProperty("accountId").GetString());
Assert.False(json.RootElement.TryGetProperty("patientId", out _));
Assert.False(json.RootElement.TryGetProperty("assignments", out _));
}
[Fact]
public async Task Professionals_list_only_their_own_assignments_and_can_share_patients()
{
var first = await CreatePatient();
var shared = await CreatePatient();
var second = await CreatePatient();
var excluded = await CreatePatient();
await Assign([first, shared, first], [shared, second]);
foreach (var (account, expected) in new[]
{
("professional", new[] { first, shared }),
("professional-second", new[] { shared, second }),
("professional-empty", Array.Empty<Guid>())
})
{
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var response = await Send(HttpMethod.Get, AssignmentPath + "?accountId=professional-second", token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var patients = (await response.Content.ReadFromJsonAsync<AssignedPatient[]>())!;
Assert.Equal(expected.Order(), patients.Select(p => p.PatientId).Order());
Assert.DoesNotContain(patients, p => p.PatientId == excluded);
}
var sharedToken = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional-second");
using var read = await Send(HttpMethod.Get, $"/api/patients/{shared}", sharedToken);
Assert.Equal(HttpStatusCode.OK, read.StatusCode);
}
[Fact]
public async Task Assigned_profiles_observations_context_history_latest_and_insights_are_readable()
{
var patient = await CreatePatient();
var observation = await Record(patient);
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var path in new[]
{
$"/api/patients/{patient}", $"/api/observations/{observation.ObservationId}",
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01",
$"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
})
{
using var response = await Send(HttpMethod.Get, path, token);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var own = await fixture.Client.GetAsync(path);
Assert.Equal(await own.Content.ReadAsStringAsync(), await response.Content.ReadAsStringAsync());
}
using var specific = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
Assert.Equal(observation, await specific.Content.ReadFromJsonAsync<Observation>());
}
[Fact]
public async Task Unassigned_patients_and_observations_are_rejected_even_with_a_supplied_assigned_patient_id()
{
var assigned = await CreatePatient();
var unassigned = await CreatePatient();
var observation = await Record(unassigned);
await Assign([assigned]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var path in new[]
{
$"/api/patients/{unassigned}", $"/api/observations/{observation.ObservationId}?patientId={assigned}",
$"/api/patients/{unassigned}/observations/latest", $"/api/patients/{unassigned}/observations?from=2026-09-01&to=2026-10-01",
$"/api/patients/{unassigned}/insights?from=2026-09-01&to=2026-10-01"
})
{
using var response = await Send(HttpMethod.Get, path, token);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
}
}
[Fact]
public async Task Missing_information_for_assigned_patients_follows_existing_retrieval_behaviour()
{
var patient = await CreatePatient();
var missingPatient = Guid.NewGuid();
await Assign([patient, missingPatient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
foreach (var path in new[]
{
$"/api/patients/{missingPatient}", $"/api/observations/{Guid.NewGuid()}",
$"/api/patients/{patient}/observations/latest", $"/api/patients/{patient}/insights?from=2026-09-01&to=2026-10-01"
})
{
using var response = await Send(HttpMethod.Get, path, token);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
using var history = await Send(HttpMethod.Get, $"/api/patients/{patient}/observations?from=2026-09-01&to=2026-10-01", token);
Assert.Equal(HttpStatusCode.OK, history.StatusCode);
Assert.Equal("[]", await history.Content.ReadAsStringAsync());
}
[Theory]
[InlineData("professional")]
[InlineData("professional-empty")]
public async Task Professionals_cannot_create_update_or_delete_any_patient_information(string account)
{
var patient = await CreatePatient();
var observation = await Record(patient);
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
await using var patients = fixture.CreateDbContext();
await using var observations = fixture.CreateObservationDbContext();
var before = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
var count = await patients.Patients.CountAsync();
foreach (var (method, path, body) in new[]
{
(HttpMethod.Post, "/api/patients", (object?)new { name = "Forbidden", dateOfBirth = "1980-01-01" }),
(HttpMethod.Put, $"/api/patients/{patient}", (object?)new { name = "Forbidden" }),
(HttpMethod.Post, $"/api/patients/{patient}/observations", (object?)new { measuredAt = "2026-09-12T08:00:00", systolic = 190, diastolic = 90, pulse = 80 }),
(HttpMethod.Put, $"/api/observations/{observation.ObservationId}", (object?)new { systolic = 190, diastolic = 90, pulse = 80 }),
(HttpMethod.Delete, $"/api/observations/{observation.ObservationId}", (object?)null)
})
{
using var response = await Send(method, path, token, body);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.Empty(await response.Content.ReadAsStringAsync());
}
Assert.Equal(count, await patients.Patients.CountAsync());
var after = await patients.Patients.AsNoTracking().SingleAsync(p => p.PatientId == patient);
Assert.Equal(before.Name, after.Name);
Assert.Equal(before.UpdatedAt, after.UpdatedAt);
var saved = await observations.Observations.AsNoTracking().SingleAsync(o => o.ObservationId == observation.ObservationId);
Assert.Equal(128, saved.Systolic);
Assert.Equal("Resting", saved.Context);
Assert.Equal("Actual conditions", saved.Note);
Assert.Single(await observations.Observations.Where(o => o.PatientId == patient).ToListAsync());
}
[Fact]
public async Task Missing_invalid_and_expired_tokens_do_not_disclose_assignments_or_patient_data()
{
var patient = await CreatePatient();
await Assign([patient]);
foreach (var token in new string?[] { null, "invalid" })
{
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
using var read = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.Unauthorized, list.StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, read.StatusCode);
Assert.Empty(await list.Content.ReadAsStringAsync());
Assert.Empty(await read.Content.ReadAsStringAsync());
}
var valid = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(31));
try
{
using var expired = await Send(HttpMethod.Get, AssignmentPath, valid);
Assert.Equal(HttpStatusCode.Unauthorized, expired.StatusCode);
}
finally { fixture.Authentication.Clock.Advance(TimeSpan.FromMinutes(-31)); }
}
[Fact]
public async Task Incorrect_professional_secret_and_unknown_account_have_identical_login_rejections()
{
using var incorrect = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "professional", password = "wrong" });
using var unknown = await fixture.RawClient.PostAsJsonAsync("/api/authentication/login", new { accountId = "unknown-professional", password = AuthenticatedTestClient.Password });
Assert.Equal(HttpStatusCode.Unauthorized, incorrect.StatusCode);
Assert.Equal(incorrect.StatusCode, unknown.StatusCode);
Assert.Equal(await incorrect.Content.ReadAsStringAsync(), await unknown.Content.ReadAsStringAsync());
}
[Fact]
public async Task Patient_cannot_list_professional_assignments_and_retains_own_access()
{
var patient = await CreatePatient();
await Assign([patient]);
var account = fixture.Authentication.PatientAccounts[patient];
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, account);
using var rejected = await Send(HttpMethod.Get, AssignmentPath, token);
Assert.Equal(HttpStatusCode.Forbidden, rejected.StatusCode);
using var own = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.OK, own.StatusCode);
}
[Fact]
public async Task Assignment_removal_is_used_after_restart_even_with_an_existing_token()
{
var patient = await CreatePatient();
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
using var allowed = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.OK, allowed.StatusCode);
await Assign([]);
using var rejected = await Send(HttpMethod.Get, $"/api/patients/{patient}", token);
Assert.Equal(HttpStatusCode.NotFound, rejected.StatusCode);
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
Assert.Equal("[]", await list.Content.ReadAsStringAsync());
}
[Fact]
public async Task Observation_ownership_lookup_failure_fails_closed_while_assignment_list_remains_available()
{
var patient = await CreatePatient();
var observation = await Record(patient);
await Assign([patient]);
var token = await AuthenticatedTestClient.LoginAsync(fixture.RawClient, "professional");
await fixture.StopObservationServiceAsync();
try
{
using var read = await Send(HttpMethod.Get, $"/api/observations/{observation.ObservationId}", token);
Assert.Equal(HttpStatusCode.BadGateway, read.StatusCode);
using var list = await Send(HttpMethod.Get, AssignmentPath, token);
Assert.Equal(HttpStatusCode.OK, list.StatusCode);
}
finally { await fixture.RestartHostsAsync(); }
}
}