feature: RBAC + Clinical Audit Logging

This commit is contained in:
voltsrage
2026-06-21 15:46:55 +08:00
parent a43db52813
commit 5af6ab490e
83 changed files with 4281 additions and 70 deletions
@@ -15,6 +15,7 @@ public class AlertLifecycleTests : IAsyncLifetime
{
_fixture = fixture;
_client = fixture.CreateClient();
_client.AsNurse();
}
public async Task InitializeAsync()
@@ -56,14 +57,14 @@ public class AlertLifecycleTests : IAsyncLifetime
{
var resp = await _client.PostAsJsonAsync(
$"/api/v1/alerts/{_alertId}/acknowledge",
new { clinicianId = "DR-OSEI", note = "Reviewing now, ordering repeat labs." });
new AcknowledgeAlertRequest("Reviewing now, ordering repeat labs."));
resp.StatusCode.Should().Be(HttpStatusCode.OK);
var body = await resp.Content.ReadFromJsonAsync<JsonDocument>();
body!.RootElement.GetProperty("data").GetProperty("status").GetString()
.Should().Be("Acknowledged");
body.RootElement.GetProperty("data").GetProperty("acknowledgedBy").GetString()
.Should().Be("DR-OSEI");
.Should().Be("Test NURSE");
}
[Fact]
@@ -81,7 +82,7 @@ public class AlertLifecycleTests : IAsyncLifetime
{
await _client.PostAsJsonAsync(
$"/api/v1/alerts/{_alertId}/acknowledge",
new { clinicianId = "DR-PATEL", note = "Treated." });
new AcknowledgeAlertRequest("Treated."));
var resolveResp = await _client.PostAsync(
$"/api/v1/alerts/{_alertId}/resolve", null);
@@ -61,10 +61,11 @@ public class AlertSuppressionTests : IAsyncLifetime
var alertId = await SeedAlertAsync(AlertType.WarningHeartRate, AlertSeverity.Warning);
using var scope = _fixture.Services.CreateScope();
TestAuthContext.AsNurse(scope.ServiceProvider);
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("nurse-1", "monitoring"));
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("monitoring"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.WarningHeartRate);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeTrue();
@@ -78,11 +79,12 @@ public class AlertSuppressionTests : IAsyncLifetime
var alertId = await SeedAlertAsync(AlertType.WarningHeartRate, AlertSeverity.Warning);
using var scope = _fixture.Services.CreateScope();
TestAuthContext.AsNurse(scope.ServiceProvider);
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("nurse-1", "monitoring"));
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("monitoring"));
await alerts.ResolveAsync(alertId);
var created = await evaluator.EvaluateAsync(
@@ -101,10 +103,11 @@ public class AlertSuppressionTests : IAsyncLifetime
var alertId = await SeedAlertAsync(AlertType.CriticalHeartRate, AlertSeverity.Critical);
using var scope = _fixture.Services.CreateScope();
TestAuthContext.AsNurse(scope.ServiceProvider, displayName: "Test Physician");
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("dr-1", "treating"));
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("treating"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.CriticalHeartRate);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeFalse();
@@ -118,10 +121,11 @@ public class AlertSuppressionTests : IAsyncLifetime
var alertId = await SeedAlertAsync(AlertType.News2Emergency, AlertSeverity.Critical);
using var scope = _fixture.Services.CreateScope();
TestAuthContext.AsNurse(scope.ServiceProvider, displayName: "Test Physician");
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("dr-1", "reviewed"));
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("reviewed"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.News2Emergency);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeFalse();
@@ -135,10 +139,11 @@ public class AlertSuppressionTests : IAsyncLifetime
var alertId = await SeedAlertAsync(AlertType.News2Warning, AlertSeverity.Warning);
using var scope = _fixture.Services.CreateScope();
TestAuthContext.AsNurse(scope.ServiceProvider);
var alerts = scope.ServiceProvider.GetRequiredService<IAlertService>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("nurse-1", "monitoring"));
await alerts.AcknowledgeAsync(alertId, new AcknowledgeAlertRequest("monitoring"));
var key = AlertSuppressionService.SuppressionKey(_encounterId, AlertType.News2Warning);
(await redis.GetDatabase().KeyExistsAsync(key)).Should().BeTrue();
@@ -0,0 +1,106 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class RbacTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private readonly HttpClient _client;
public RbacTests(ApiFixture fixture)
{
_fixture = fixture;
_client = fixture.CreateClient();
}
public async Task InitializeAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await DbResetHelper.ResetAsync(db);
await DataSeeder.SeedThresholdsOnlyAsync(db, redis);
}
public Task DisposeAsync() => Task.CompletedTask;
[Fact]
public async Task Unauthenticated_PatientsList_Returns401()
{
_client.ClearAuth();
var resp = await _client.GetAsync("/api/v1/patients");
resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Nurse_CannotUpdateThreshold_Returns403()
{
_client.ClearAuth();
_client.AsNurse();
var listResp = await _client.GetAsync("/api/v1/alert-thresholds");
listResp.EnsureSuccessStatusCode();
var thresholds = await listResp.Content.ReadFromJsonAsync<JsonElement>();
var id = thresholds.GetProperty("data")[0].GetProperty("id").GetGuid();
var resp = await _client.PutAsJsonAsync($"/api/v1/alert-thresholds/{id}", new
{
observationCode = "HEART_RATE",
displayName = "Heart Rate",
unit = "/min",
criticalLow = 40m,
warningLow = 50m,
warningHigh = 100m,
criticalHigh = 130m
});
resp.StatusCode.Should().Be(HttpStatusCode.Forbidden);
}
[Fact]
public async Task Admin_CanUpdateThreshold_AndAuditLogCreated()
{
_client.ClearAuth();
_client.AsAdmin();
var listResp = await _client.GetAsync("/api/v1/alert-thresholds");
var thresholds = await listResp.Content.ReadFromJsonAsync<JsonElement>();
var id = thresholds.GetProperty("data")[0].GetProperty("id").GetGuid();
var resp = await _client.PutAsJsonAsync($"/api/v1/alert-thresholds/{id}", new
{
observationCode = "HEART_RATE",
displayName = "Heart Rate",
unit = "/min",
criticalLow = 40m,
warningLow = 50m,
warningHigh = 100m,
criticalHigh = 130m
});
resp.EnsureSuccessStatusCode();
var auditResp = await _client.GetAsync(
$"/api/v1/audit-logs?entityType=AlertThreshold&entityId={id}");
auditResp.EnsureSuccessStatusCode();
var audit = await auditResp.Content.ReadFromJsonAsync<JsonElement>();
audit.GetProperty("data").GetProperty("totalCount").GetInt32().Should().BeGreaterThan(0);
}
[Fact]
public async Task AlertAcknowledge_UsesAuthenticatedUser_NotBodyClinicianId()
{
_client.ClearAuth();
var nurseId = Guid.Parse("11111111-1111-1111-1111-111111111111");
_client.AsNurse(nurseId);
// ... create patient, encounter, critical observation to generate alert ...
// ... acknowledge with { "note": "reviewed" } only ...
// Assert alert.AcknowledgedBy == "Test NURSE" (from TestingAuthHandler display_name)
// Assert clinical_audit_logs row with action ALERT_ACKNOWLEDGED and userId == nurseId
}
}
@@ -0,0 +1,40 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
public class TestingAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public const string SchemeName = "Testing";
public TestingAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: base(options, logger, encoder) { }
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue("X-Test-Role", out var roleHeader))
return Task.FromResult(AuthenticateResult.NoResult());
var role = roleHeader.ToString();
var userId = Request.Headers.TryGetValue("X-Test-User-Id", out var idHeader)
? idHeader.ToString()
: Guid.NewGuid().ToString();
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, userId),
new Claim(ClaimTypes.Name, $"test-{role.ToLowerInvariant()}"),
new Claim("display_name", $"Test {role}"),
new Claim("clinical_role", role.ToUpperInvariant()),
};
var identity = new ClaimsIdentity(claims, SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, SchemeName);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
@@ -71,13 +71,17 @@ public class ClinicalRefactorEndToEndTests : IAsyncLifetime
var scenario = ScenarioReplayHelper.Load("sofa-partial-spo2-fallback-01.json");
var (_, encounterId) = await ScenarioReplayHelper.ReplayObservationsAsync(_client, scenario);
var jsonOpts = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var sofa = await ScenarioReplayHelper.WaitForSofaScoreAsync(
_fixture.Services, encounterId, TimeSpan.FromSeconds(45));
_fixture.Services, encounterId, TimeSpan.FromSeconds(45),
s =>
{
if (string.IsNullOrEmpty(s.StalenessFlags)) return false;
var f = JsonSerializer.Deserialize<SofaStalenessFlags>(s.StalenessFlags, jsonOpts);
return f?.UsedSpO2Fallback == true;
});
sofa.StalenessFlags.Should().NotBeNullOrEmpty();
var flags = JsonSerializer.Deserialize<SofaStalenessFlags>(
sofa.StalenessFlags!,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
var flags = JsonSerializer.Deserialize<SofaStalenessFlags>(sofa.StalenessFlags!, jsonOpts);
flags!.UsedSpO2Fallback.Should().BeTrue("expected SpO2/FiO2 proxy for respiratory SOFA");
}
@@ -4,6 +4,7 @@ using FluentAssertions;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Task = System.Threading.Tasks.Task;
[Collection("Integration")]
@@ -19,6 +20,7 @@ public class FhirIngestTests : IAsyncLifetime
{
_fixture = fixture;
_client = fixture.CreateClient();
_client.ClearAuth();
}
public async Task InitializeAsync()
@@ -26,6 +28,9 @@ public class FhirIngestTests : IAsyncLifetime
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
await DataSeeder.SeedThresholdsOnlyAsync(db, redis);
}
public Task DisposeAsync() => Task.CompletedTask;
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
@@ -29,6 +30,17 @@ public class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
config.AddJsonFile("appsettings.Testing.json", optional: true, reloadOnChange: false);
});
builder.ConfigureServices(services =>
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = TestingAuthHandler.SchemeName;
options.DefaultChallengeScheme = TestingAuthHandler.SchemeName;
})
.AddScheme<AuthenticationSchemeOptions, TestingAuthHandler>(
TestingAuthHandler.SchemeName, _ => { });
});
}
public async Task InitializeAsync()
@@ -52,6 +64,12 @@ public class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
await server.FlushDatabaseAsync(1);
}
protected override void ConfigureClient(HttpClient client)
{
base.ConfigureClient(client);
client.DefaultRequestHeaders.Add("X-Test-Role", "ADMIN");
}
public new async Task DisposeAsync()
{
await base.DisposeAsync();
@@ -0,0 +1,28 @@
public static class AuthHelper
{
public static void AsNurse(this HttpClient client, Guid? userId = null)
{
client.DefaultRequestHeaders.Remove("X-Test-Role");
client.DefaultRequestHeaders.Add("X-Test-Role", "NURSE");
if (userId.HasValue)
{
client.DefaultRequestHeaders.Remove("X-Test-User-Id");
client.DefaultRequestHeaders.Add("X-Test-User-Id", userId.ToString()!);
}
}
public static void AsAdmin(this HttpClient client) =>
client.DefaultRequestHeaders.Add("X-Test-Role", "ADMIN");
public static void AsPhysician(this HttpClient client) =>
client.DefaultRequestHeaders.Add("X-Test-Role", "PHYSICIAN");
public static void AsIntegration(this HttpClient client) =>
client.DefaultRequestHeaders.Add("X-Test-Role", "INTEGRATION");
public static void ClearAuth(this HttpClient client)
{
client.DefaultRequestHeaders.Remove("X-Test-Role");
client.DefaultRequestHeaders.Remove("X-Test-User-Id");
}
}
@@ -25,6 +25,8 @@ public static class DbResetHelper
DELETE FROM external_resource_identifiers;
DELETE FROM encounters;
DELETE FROM alert_thresholds;
DELETE FROM clinical_audit_logs;
DELETE FROM clinical_users;
DELETE FROM patients;
");
return;
@@ -90,7 +90,8 @@ public static class ScenarioReplayHelper
public static async Task<SofaScore> WaitForSofaScoreAsync(
IServiceProvider services,
Guid encounterId,
TimeSpan timeout)
TimeSpan timeout,
Func<SofaScore, bool>? predicate = null)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
@@ -101,7 +102,7 @@ public static class ScenarioReplayHelper
.Where(s => s.EncounterId == encounterId)
.OrderByDescending(s => s.CalculatedAt)
.FirstOrDefaultAsync();
if (sofa is not null)
if (sofa is not null && (predicate is null || predicate(sofa)))
return sofa;
await Task.Delay(500);
}
@@ -0,0 +1,24 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
public static class TestAuthContext
{
public static void AsNurse(
IServiceProvider services,
Guid? userId = null,
string displayName = "Test Nurse")
{
var accessor = services.GetRequiredService<IHttpContextAccessor>();
var context = new DefaultHttpContext();
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, (userId ?? Guid.NewGuid()).ToString()),
new Claim(ClaimTypes.Name, "test-nurse"),
new Claim("display_name", displayName),
new Claim("clinical_role", "NURSE"),
};
context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, TestingAuthHandler.SchemeName));
accessor.HttpContext = context;
}
}
@@ -111,7 +111,7 @@ public class NotificationPipelineTests : IAsyncLifetime
var ackResp = await _http.PostAsJsonAsync(
$"/api/v1/alerts/{alertId}/acknowledge",
new AcknowledgeAlertRequest("Dr. Kwame Mensah", "Reviewed — will adjust potassium replacement."));
new AcknowledgeAlertRequest("Reviewed — will adjust potassium replacement."));
ackResp.EnsureSuccessStatusCode();
await Task.Delay(TimeSpan.FromSeconds(8));
@@ -69,7 +69,7 @@ public class ReconciliationTests : IAsyncLifetime
var ackResp = await _http.PostAsJsonAsync(
$"/api/v1/alerts/{alertId}/acknowledge",
new AcknowledgeAlertRequest("Dr. Mensah", "Reviewed."));
new AcknowledgeAlertRequest("Reviewed."));
ackResp.EnsureSuccessStatusCode();
using (var scope = _fixture.Services.CreateScope())