begin: PHI Column Encryption
This commit is contained in:
@@ -92,6 +92,7 @@ packages/
|
|||||||
node_modules/
|
node_modules/
|
||||||
dist/
|
dist/
|
||||||
build/
|
build/
|
||||||
|
data-protection-keys/
|
||||||
|
|
||||||
# =========================
|
# =========================
|
||||||
# Docker
|
# Docker
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
public class PhiEncryptionOptions
|
||||||
|
{
|
||||||
|
public const string Section = "PhiEncryption";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Purpose string for IDataProtector. Rotate by changing purpose and re-encrypting.
|
||||||
|
/// </summary>
|
||||||
|
public string ProtectorPurpose { get; set; } = "VigilCare.PatientPhi.v1";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// HMAC key for name search tokens (base64). Separate from encryption key.
|
||||||
|
/// In production: store in Key Vault, not appsettings.
|
||||||
|
/// </summary>
|
||||||
|
public string SearchTokenKey { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>When true, logs PHI access for list/search operations as aggregate events.</summary>
|
||||||
|
public bool LogListAccess { get; set; } = true;
|
||||||
|
}
|
||||||
@@ -2,7 +2,14 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
|
|
||||||
public class AppDbContext : DbContext
|
public class AppDbContext : DbContext
|
||||||
{
|
{
|
||||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
|
private readonly IPhiEncryptionService? _phiCrypto;
|
||||||
|
|
||||||
|
public AppDbContext(
|
||||||
|
DbContextOptions<AppDbContext> options,
|
||||||
|
IPhiEncryptionService? phiCrypto = null) : base(options)
|
||||||
|
{
|
||||||
|
_phiCrypto = phiCrypto;
|
||||||
|
}
|
||||||
|
|
||||||
public DbSet<Patient> Patients => Set<Patient>();
|
public DbSet<Patient> Patients => Set<Patient>();
|
||||||
public DbSet<Encounter> Encounters => Set<Encounter>();
|
public DbSet<Encounter> Encounters => Set<Encounter>();
|
||||||
@@ -21,9 +28,13 @@ public class AppDbContext : DbContext
|
|||||||
public DbSet<ExternalResourceIdentifier> ExternalResourceIdentifiers => Set<ExternalResourceIdentifier>();
|
public DbSet<ExternalResourceIdentifier> ExternalResourceIdentifiers => Set<ExternalResourceIdentifier>();
|
||||||
public DbSet<ClinicalUser> ClinicalUsers => Set<ClinicalUser>();
|
public DbSet<ClinicalUser> ClinicalUsers => Set<ClinicalUser>();
|
||||||
public DbSet<ClinicalAuditLog> ClinicalAuditLogs => Set<ClinicalAuditLog>();
|
public DbSet<ClinicalAuditLog> ClinicalAuditLogs => Set<ClinicalAuditLog>();
|
||||||
|
public DbSet<PhiAccessLog> PhiAccessLogs => Set<PhiAccessLog>();
|
||||||
|
|
||||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
|
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
|
||||||
|
|
||||||
|
if (_phiCrypto is not null)
|
||||||
|
modelBuilder.ConfigurePhiConverters(_phiCrypto);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,9 @@ public class PatientConfiguration : IEntityTypeConfiguration<Patient>
|
|||||||
builder.Property(p => p.Allergies).HasColumnName("allergies");
|
builder.Property(p => p.Allergies).HasColumnName("allergies");
|
||||||
builder.Property(p => p.EmergencyContactName).HasColumnName("emergency_contact_name").HasMaxLength(200);
|
builder.Property(p => p.EmergencyContactName).HasColumnName("emergency_contact_name").HasMaxLength(200);
|
||||||
builder.Property(p => p.EmergencyContactPhone).HasColumnName("emergency_contact_phone").HasMaxLength(20);
|
builder.Property(p => p.EmergencyContactPhone).HasColumnName("emergency_contact_phone").HasMaxLength(20);
|
||||||
|
builder.Property(p => p.NameSearchToken)
|
||||||
|
.HasColumnName("name_search_token")
|
||||||
|
.HasMaxLength(64);
|
||||||
builder.Property(p => p.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
|
builder.Property(p => p.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("NOW()");
|
||||||
|
|
||||||
// MRN uses exact-match unique index — MRN lookups are always equality checks,
|
// MRN uses exact-match unique index — MRN lookups are always equality checks,
|
||||||
@@ -29,5 +32,6 @@ public class PatientConfiguration : IEntityTypeConfiguration<Patient>
|
|||||||
// equality match — so no index here; full ILIKE is intentionally unindexed
|
// equality match — so no index here; full ILIKE is intentionally unindexed
|
||||||
// at this scale (pg_trgm GIN would be warranted at >500k patients).
|
// at this scale (pg_trgm GIN would be warranted at >500k patients).
|
||||||
builder.HasIndex(p => p.Mrn).IsUnique();
|
builder.HasIndex(p => p.Mrn).IsUnique();
|
||||||
|
builder.HasIndex(p => p.NameSearchToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||||
|
|
||||||
|
public class PhiAccessLogConfiguration : IEntityTypeConfiguration<PhiAccessLog>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<PhiAccessLog> builder)
|
||||||
|
{
|
||||||
|
builder.ToTable("phi_access_logs");
|
||||||
|
builder.HasKey(p => p.Id);
|
||||||
|
builder.Property(p => p.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()");
|
||||||
|
builder.Property(p => p.AccessType).HasColumnName("access_type").HasMaxLength(20).IsRequired()
|
||||||
|
.HasConversion(v => v.ToDbString(), v => PhiAccessTypeExtensions.FromDbString(v));
|
||||||
|
builder.Property(p => p.PatientId).HasColumnName("patient_id");
|
||||||
|
builder.Property(p => p.UserId).HasColumnName("user_id").IsRequired();
|
||||||
|
builder.Property(p => p.UserDisplayName).HasColumnName("user_display_name").HasMaxLength(200).IsRequired();
|
||||||
|
builder.Property(p => p.ResourcePath).HasColumnName("resource_path").HasMaxLength(500).IsRequired();
|
||||||
|
builder.Property(p => p.SearchQueryHash).HasColumnName("search_query_hash").HasMaxLength(64);
|
||||||
|
builder.Property(p => p.ResultCount).HasColumnName("result_count");
|
||||||
|
builder.Property(p => p.IpAddress).HasColumnName("ip_address").HasMaxLength(45);
|
||||||
|
builder.Property(p => p.CorrelationId).HasColumnName("correlation_id").HasMaxLength(100);
|
||||||
|
builder.Property(p => p.AccessedAt).HasColumnName("accessed_at").HasDefaultValueSql("NOW()");
|
||||||
|
|
||||||
|
builder.HasIndex(p => p.PatientId);
|
||||||
|
builder.HasIndex(p => p.UserId);
|
||||||
|
builder.HasIndex(p => p.AccessedAt);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
public static class PatientPhiConverterConfigurator
|
||||||
|
{
|
||||||
|
public static void ConfigurePhiConverters(
|
||||||
|
this ModelBuilder modelBuilder,
|
||||||
|
IPhiEncryptionService crypto)
|
||||||
|
{
|
||||||
|
var entity = modelBuilder.Entity<Patient>();
|
||||||
|
|
||||||
|
entity.Property(p => p.FirstName)
|
||||||
|
.HasConversion(
|
||||||
|
v => crypto.Encrypt(v),
|
||||||
|
v => crypto.Decrypt(v));
|
||||||
|
|
||||||
|
entity.Property(p => p.LastName)
|
||||||
|
.HasConversion(
|
||||||
|
v => crypto.Encrypt(v),
|
||||||
|
v => crypto.Decrypt(v));
|
||||||
|
|
||||||
|
entity.Property(p => p.Allergies)
|
||||||
|
.HasConversion(
|
||||||
|
v => v == null ? null! : crypto.Encrypt(v),
|
||||||
|
v => v == null ? null : crypto.Decrypt(v));
|
||||||
|
|
||||||
|
entity.Property(p => p.EmergencyContactName)
|
||||||
|
.HasConversion(
|
||||||
|
v => v == null ? null! : crypto.Encrypt(v),
|
||||||
|
v => v == null ? null : crypto.Decrypt(v));
|
||||||
|
|
||||||
|
entity.Property(p => p.EmergencyContactPhone)
|
||||||
|
.HasConversion(
|
||||||
|
v => v == null ? null! : crypto.Encrypt(v),
|
||||||
|
v => v == null ? null : crypto.Decrypt(v));
|
||||||
|
|
||||||
|
// DateOfBirth stored as encrypted ISO string
|
||||||
|
entity.Property(p => p.DateOfBirth)
|
||||||
|
.HasConversion(
|
||||||
|
v => crypto.Encrypt(v.ToString("yyyy-MM-dd")),
|
||||||
|
v => DateOnly.Parse(crypto.Decrypt(v)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,9 @@ public class Patient
|
|||||||
public string? Allergies { get; set; }
|
public string? Allergies { get; set; }
|
||||||
public string? EmergencyContactName { get; set; }
|
public string? EmergencyContactName { get; set; }
|
||||||
public string? EmergencyContactPhone { get; set; }
|
public string? EmergencyContactPhone { get; set; }
|
||||||
|
|
||||||
|
/// <summary>HMAC token for name search. Not PHI — enables lookup without decrypting all rows.</summary>
|
||||||
|
public string? NameSearchToken { get; set; }
|
||||||
public string Status { get; set; } = "active";
|
public string Status { get; set; } = "active";
|
||||||
public DateTimeOffset CreatedAt { get; set; }
|
public DateTimeOffset CreatedAt { get; set; }
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
public class PhiAccessLog
|
||||||
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public PhiAccessType AccessType { get; set; }
|
||||||
|
public Guid? PatientId { get; set; }
|
||||||
|
public Guid UserId { get; set; }
|
||||||
|
public string UserDisplayName { get; set; } = null!;
|
||||||
|
public string ResourcePath { get; set; } = null!;
|
||||||
|
public string? SearchQueryHash { get; set; }
|
||||||
|
public int? ResultCount { get; set; }
|
||||||
|
public string? IpAddress { get; set; }
|
||||||
|
public string? CorrelationId { get; set; }
|
||||||
|
public DateTimeOffset AccessedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
public enum PhiAccessType
|
||||||
|
{
|
||||||
|
View,
|
||||||
|
List,
|
||||||
|
Search,
|
||||||
|
Create,
|
||||||
|
Update
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class PhiAccessTypeExtensions
|
||||||
|
{
|
||||||
|
public static string ToDbString(this PhiAccessType t) => t switch
|
||||||
|
{
|
||||||
|
PhiAccessType.View => "VIEW",
|
||||||
|
PhiAccessType.List => "LIST",
|
||||||
|
PhiAccessType.Search => "SEARCH",
|
||||||
|
PhiAccessType.Create => "CREATE",
|
||||||
|
PhiAccessType.Update => "UPDATE",
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(t))
|
||||||
|
};
|
||||||
|
|
||||||
|
public static PhiAccessType FromDbString(string v) => v switch
|
||||||
|
{
|
||||||
|
"VIEW" => PhiAccessType.View,
|
||||||
|
"LIST" => PhiAccessType.List,
|
||||||
|
"SEARCH" => PhiAccessType.Search,
|
||||||
|
"CREATE" => PhiAccessType.Create,
|
||||||
|
"UPDATE" => PhiAccessType.Update,
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(v))
|
||||||
|
};
|
||||||
|
}
|
||||||
+1291
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,55 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace VigilCareClinicalAPI.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddPatientNameSearchToken : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AlterColumn<string>(
|
||||||
|
name: "date_of_birth",
|
||||||
|
table: "patients",
|
||||||
|
type: "text",
|
||||||
|
nullable: false,
|
||||||
|
oldClrType: typeof(DateOnly),
|
||||||
|
oldType: "date");
|
||||||
|
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "name_search_token",
|
||||||
|
table: "patients",
|
||||||
|
type: "character varying(64)",
|
||||||
|
maxLength: 64,
|
||||||
|
nullable: true);
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_patients_name_search_token",
|
||||||
|
table: "patients",
|
||||||
|
column: "name_search_token");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropIndex(
|
||||||
|
name: "IX_patients_name_search_token",
|
||||||
|
table: "patients");
|
||||||
|
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "name_search_token",
|
||||||
|
table: "patients");
|
||||||
|
|
||||||
|
migrationBuilder.AlterColumn<DateOnly>(
|
||||||
|
name: "date_of_birth",
|
||||||
|
table: "patients",
|
||||||
|
type: "date",
|
||||||
|
nullable: false,
|
||||||
|
oldClrType: typeof(string),
|
||||||
|
oldType: "text");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1361
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,58 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace VigilCareClinicalAPI.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddPhiAccessLogs : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "phi_access_logs",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
|
||||||
|
access_type = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
|
||||||
|
patient_id = table.Column<Guid>(type: "uuid", nullable: true),
|
||||||
|
user_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||||
|
user_display_name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
|
||||||
|
resource_path = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
|
||||||
|
search_query_hash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
|
||||||
|
result_count = table.Column<int>(type: "integer", nullable: true),
|
||||||
|
ip_address = table.Column<string>(type: "character varying(45)", maxLength: 45, nullable: true),
|
||||||
|
correlation_id = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
|
||||||
|
accessed_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "NOW()")
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_phi_access_logs", x => x.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_phi_access_logs_accessed_at",
|
||||||
|
table: "phi_access_logs",
|
||||||
|
column: "accessed_at");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_phi_access_logs_patient_id",
|
||||||
|
table: "phi_access_logs",
|
||||||
|
column: "patient_id");
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_phi_access_logs_user_id",
|
||||||
|
table: "phi_access_logs",
|
||||||
|
column: "user_id");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "phi_access_logs");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -828,8 +828,9 @@ namespace VigilCareClinicalAPI.Migrations
|
|||||||
.HasColumnName("created_at")
|
.HasColumnName("created_at")
|
||||||
.HasDefaultValueSql("NOW()");
|
.HasDefaultValueSql("NOW()");
|
||||||
|
|
||||||
b.Property<DateOnly>("DateOfBirth")
|
b.Property<string>("DateOfBirth")
|
||||||
.HasColumnType("date")
|
.IsRequired()
|
||||||
|
.HasColumnType("text")
|
||||||
.HasColumnName("date_of_birth");
|
.HasColumnName("date_of_birth");
|
||||||
|
|
||||||
b.Property<string>("EmergencyContactName")
|
b.Property<string>("EmergencyContactName")
|
||||||
@@ -866,6 +867,11 @@ namespace VigilCareClinicalAPI.Migrations
|
|||||||
.HasColumnType("character varying(20)")
|
.HasColumnType("character varying(20)")
|
||||||
.HasColumnName("mrn");
|
.HasColumnName("mrn");
|
||||||
|
|
||||||
|
b.Property<string>("NameSearchToken")
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)")
|
||||||
|
.HasColumnName("name_search_token");
|
||||||
|
|
||||||
b.Property<string>("Status")
|
b.Property<string>("Status")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
@@ -879,9 +885,81 @@ namespace VigilCareClinicalAPI.Migrations
|
|||||||
b.HasIndex("Mrn")
|
b.HasIndex("Mrn")
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
|
|
||||||
|
b.HasIndex("NameSearchToken");
|
||||||
|
|
||||||
b.ToTable("patients", (string)null);
|
b.ToTable("patients", (string)null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("PhiAccessLog", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("id")
|
||||||
|
.HasDefaultValueSql("gen_random_uuid()");
|
||||||
|
|
||||||
|
b.Property<string>("AccessType")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(20)
|
||||||
|
.HasColumnType("character varying(20)")
|
||||||
|
.HasColumnName("access_type");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("AccessedAt")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("timestamp with time zone")
|
||||||
|
.HasColumnName("accessed_at")
|
||||||
|
.HasDefaultValueSql("NOW()");
|
||||||
|
|
||||||
|
b.Property<string>("CorrelationId")
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("character varying(100)")
|
||||||
|
.HasColumnName("correlation_id");
|
||||||
|
|
||||||
|
b.Property<string>("IpAddress")
|
||||||
|
.HasMaxLength(45)
|
||||||
|
.HasColumnType("character varying(45)")
|
||||||
|
.HasColumnName("ip_address");
|
||||||
|
|
||||||
|
b.Property<Guid?>("PatientId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("patient_id");
|
||||||
|
|
||||||
|
b.Property<string>("ResourcePath")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(500)
|
||||||
|
.HasColumnType("character varying(500)")
|
||||||
|
.HasColumnName("resource_path");
|
||||||
|
|
||||||
|
b.Property<int?>("ResultCount")
|
||||||
|
.HasColumnType("integer")
|
||||||
|
.HasColumnName("result_count");
|
||||||
|
|
||||||
|
b.Property<string>("SearchQueryHash")
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("character varying(64)")
|
||||||
|
.HasColumnName("search_query_hash");
|
||||||
|
|
||||||
|
b.Property<string>("UserDisplayName")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(200)
|
||||||
|
.HasColumnType("character varying(200)")
|
||||||
|
.HasColumnName("user_display_name");
|
||||||
|
|
||||||
|
b.Property<Guid>("UserId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasColumnName("user_id");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("AccessedAt");
|
||||||
|
|
||||||
|
b.HasIndex("PatientId");
|
||||||
|
|
||||||
|
b.HasIndex("UserId");
|
||||||
|
|
||||||
|
b.ToTable("phi_access_logs", (string)null);
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("ReconciliationAlert", b =>
|
modelBuilder.Entity("ReconciliationAlert", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ using Microsoft.IdentityModel.Tokens;
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.OpenApi;
|
using Microsoft.OpenApi;
|
||||||
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
|
|
||||||
Log.Logger = new LoggerConfiguration()
|
Log.Logger = new LoggerConfiguration()
|
||||||
.WriteTo.Console()
|
.WriteTo.Console()
|
||||||
@@ -72,8 +73,10 @@ try
|
|||||||
.Enrich.WithThreadId());
|
.Enrich.WithThreadId());
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.Services.AddDbContext<AppDbContext>(opts =>
|
builder.Services.AddDbContext<AppDbContext>((sp, opts) =>
|
||||||
opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
|
{
|
||||||
|
opts.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"));
|
||||||
|
});
|
||||||
|
|
||||||
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
|
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
|
||||||
ConnectionMultiplexer.Connect(sp.GetRequiredService<IConfiguration>()["Redis:ConnectionString"]!));
|
ConnectionMultiplexer.Connect(sp.GetRequiredService<IConfiguration>()["Redis:ConnectionString"]!));
|
||||||
@@ -129,6 +132,14 @@ try
|
|||||||
builder.Services.Configure<PatientOptions>(
|
builder.Services.Configure<PatientOptions>(
|
||||||
builder.Configuration.GetSection(PatientOptions.Section));
|
builder.Configuration.GetSection(PatientOptions.Section));
|
||||||
|
|
||||||
|
builder.Services.AddDataProtection()
|
||||||
|
.PersistKeysToFileSystem(new DirectoryInfo(
|
||||||
|
builder.Configuration["DataProtection:KeyPath"] ?? "./data-protection-keys"))
|
||||||
|
.SetApplicationName("VigilCareClinical");
|
||||||
|
|
||||||
|
builder.Services.Configure<PhiEncryptionOptions>(
|
||||||
|
builder.Configuration.GetSection(PhiEncryptionOptions.Section));
|
||||||
|
|
||||||
builder.Services.AddCors(options =>
|
builder.Services.AddCors(options =>
|
||||||
{
|
{
|
||||||
options.AddPolicy("Dashboard", policy =>
|
options.AddPolicy("Dashboard", policy =>
|
||||||
@@ -180,6 +191,8 @@ try
|
|||||||
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
|
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
|
||||||
builder.Services.AddScoped<IAuthService, AuthService>();
|
builder.Services.AddScoped<IAuthService, AuthService>();
|
||||||
builder.Services.AddScoped<IAuditService, AuditService>();
|
builder.Services.AddScoped<IAuditService, AuditService>();
|
||||||
|
builder.Services.AddSingleton<IPhiEncryptionService, PhiEncryptionService>();
|
||||||
|
builder.Services.AddScoped<IPhiAccessLogService, PhiAccessLogService>();
|
||||||
|
|
||||||
builder.Services.AddHostedService<ThresholdCacheLoader>();
|
builder.Services.AddHostedService<ThresholdCacheLoader>();
|
||||||
builder.Services.AddHostedService<KafkaTopicProvisioner>();
|
builder.Services.AddHostedService<KafkaTopicProvisioner>();
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
public interface IPhiAccessLogService
|
||||||
|
{
|
||||||
|
Task LogViewAsync(Guid patientId, string resourcePath);
|
||||||
|
Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null);
|
||||||
|
Task LogCreateAsync(Guid patientId, string resourcePath);
|
||||||
|
Task LogUpdateAsync(Guid patientId, string resourcePath);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
public interface IPhiEncryptionService
|
||||||
|
{
|
||||||
|
string Encrypt(string plaintext);
|
||||||
|
string Decrypt(string ciphertext);
|
||||||
|
string ComputeNameSearchToken(string firstName, string lastName);
|
||||||
|
bool IsEncrypted(string value);
|
||||||
|
}
|
||||||
@@ -8,17 +8,26 @@ public class PatientService : IPatientService
|
|||||||
private readonly IExternalIdentifierService _identifiers;
|
private readonly IExternalIdentifierService _identifiers;
|
||||||
private readonly IAuditService _audit;
|
private readonly IAuditService _audit;
|
||||||
private readonly PatientOptions _options;
|
private readonly PatientOptions _options;
|
||||||
|
private readonly IPhiEncryptionService _crypto;
|
||||||
|
private readonly IPhiAccessLogService _phiAccess;
|
||||||
|
private readonly IHttpContextAccessor _http;
|
||||||
|
|
||||||
public PatientService(
|
public PatientService(
|
||||||
AppDbContext db,
|
AppDbContext db,
|
||||||
IExternalIdentifierService identifiers,
|
IExternalIdentifierService identifiers,
|
||||||
IAuditService audit,
|
IAuditService audit,
|
||||||
IOptions<PatientOptions> options)
|
IOptions<PatientOptions> options,
|
||||||
|
IPhiEncryptionService crypto,
|
||||||
|
IPhiAccessLogService phiAccess,
|
||||||
|
IHttpContextAccessor http)
|
||||||
{
|
{
|
||||||
_db = db;
|
_db = db;
|
||||||
_identifiers = identifiers;
|
_identifiers = identifiers;
|
||||||
_audit = audit;
|
_audit = audit;
|
||||||
_options = options.Value;
|
_options = options.Value;
|
||||||
|
_crypto = crypto;
|
||||||
|
_phiAccess = phiAccess;
|
||||||
|
_http = http;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Patient> RegisterAsync(RegisterPatientRequest req)
|
public async Task<Patient> RegisterAsync(RegisterPatientRequest req)
|
||||||
@@ -37,6 +46,7 @@ public class PatientService : IPatientService
|
|||||||
EmergencyContactPhone = req.EmergencyContactPhone,
|
EmergencyContactPhone = req.EmergencyContactPhone,
|
||||||
CreatedAt = DateTimeOffset.UtcNow
|
CreatedAt = DateTimeOffset.UtcNow
|
||||||
};
|
};
|
||||||
|
SetNameSearchToken(patient);
|
||||||
_db.Patients.Add(patient);
|
_db.Patients.Add(patient);
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -260,4 +270,10 @@ public class PatientService : IPatientService
|
|||||||
.SingleAsync();
|
.SingleAsync();
|
||||||
return $"{_options.MrnPrefix}-{seq.ToString($"D{_options.MrnDigits}")}";
|
return $"{_options.MrnPrefix}-{seq.ToString($"D{_options.MrnDigits}")}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void SetNameSearchToken(Patient patient)
|
||||||
|
{
|
||||||
|
patient.NameSearchToken = _crypto.ComputeNameSearchToken(
|
||||||
|
patient.FirstName, patient.LastName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
public class PhiAccessLogService : IPhiAccessLogService
|
||||||
|
{
|
||||||
|
private readonly AppDbContext _db;
|
||||||
|
private readonly ICurrentUserService _currentUser;
|
||||||
|
private readonly IHttpContextAccessor _http;
|
||||||
|
private readonly PhiEncryptionOptions _options;
|
||||||
|
|
||||||
|
public PhiAccessLogService(
|
||||||
|
AppDbContext db,
|
||||||
|
ICurrentUserService currentUser,
|
||||||
|
IHttpContextAccessor http,
|
||||||
|
IOptions<PhiEncryptionOptions> options)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_currentUser = currentUser;
|
||||||
|
_http = http;
|
||||||
|
_options = options.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task LogViewAsync(Guid patientId, string resourcePath) =>
|
||||||
|
await WriteAsync(PhiAccessType.View, patientId, resourcePath);
|
||||||
|
|
||||||
|
public async Task LogCreateAsync(Guid patientId, string resourcePath) =>
|
||||||
|
await WriteAsync(PhiAccessType.Create, patientId, resourcePath);
|
||||||
|
|
||||||
|
public async Task LogUpdateAsync(Guid patientId, string resourcePath) =>
|
||||||
|
await WriteAsync(PhiAccessType.Update, patientId, resourcePath);
|
||||||
|
|
||||||
|
public async Task LogListAsync(string resourcePath, int resultCount, string? searchQuery = null)
|
||||||
|
{
|
||||||
|
if (!_options.LogListAccess)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var accessType = string.IsNullOrWhiteSpace(searchQuery)
|
||||||
|
? PhiAccessType.List
|
||||||
|
: PhiAccessType.Search;
|
||||||
|
|
||||||
|
await WriteAsync(accessType, null, resourcePath, resultCount, searchQuery);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task WriteAsync(
|
||||||
|
PhiAccessType accessType,
|
||||||
|
Guid? patientId,
|
||||||
|
string resourcePath,
|
||||||
|
int? resultCount = null,
|
||||||
|
string? searchQuery = null)
|
||||||
|
{
|
||||||
|
if (!_currentUser.IsAuthenticated || _currentUser.UserId is null)
|
||||||
|
return; // machine/integration paths may skip — Phase 31 Integration role should still auth
|
||||||
|
|
||||||
|
_db.PhiAccessLogs.Add(new PhiAccessLog
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
AccessType = accessType,
|
||||||
|
PatientId = patientId,
|
||||||
|
UserId = _currentUser.UserId.Value,
|
||||||
|
UserDisplayName = _currentUser.DisplayName ?? _currentUser.Username ?? "Unknown",
|
||||||
|
ResourcePath = resourcePath,
|
||||||
|
SearchQueryHash = searchQuery is null ? null : HashQuery(searchQuery),
|
||||||
|
ResultCount = resultCount,
|
||||||
|
IpAddress = _currentUser.IpAddress,
|
||||||
|
CorrelationId = _http.HttpContext?.Items["CorrelationId"]?.ToString(),
|
||||||
|
AccessedAt = DateTimeOffset.UtcNow
|
||||||
|
});
|
||||||
|
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HashQuery(string query)
|
||||||
|
{
|
||||||
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(query.Trim().ToLowerInvariant()));
|
||||||
|
return Convert.ToHexString(hash).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
public class PhiEncryptionService : IPhiEncryptionService
|
||||||
|
{
|
||||||
|
private readonly IDataProtector _protector;
|
||||||
|
private readonly byte[] _searchKey;
|
||||||
|
|
||||||
|
public PhiEncryptionService(
|
||||||
|
IDataProtectionProvider provider,
|
||||||
|
IOptions<PhiEncryptionOptions> options)
|
||||||
|
{
|
||||||
|
var opts = options.Value;
|
||||||
|
_protector = provider.CreateProtector(opts.ProtectorPurpose);
|
||||||
|
_searchKey = Convert.FromBase64String(
|
||||||
|
Convert.ToBase64String(Encoding.UTF8.GetBytes(opts.SearchTokenKey))[..44]); // normalize dev key
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Encrypt(string plaintext)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(plaintext))
|
||||||
|
return plaintext;
|
||||||
|
return _protector.Protect(plaintext);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Decrypt(string ciphertext)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(ciphertext))
|
||||||
|
return ciphertext;
|
||||||
|
if (!IsEncrypted(ciphertext))
|
||||||
|
return ciphertext; // migration transition: plaintext rows still readable
|
||||||
|
return _protector.Unprotect(ciphertext);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsEncrypted(string value) =>
|
||||||
|
value.StartsWith("CfDJ8", StringComparison.Ordinal) || // DataProtection prefix
|
||||||
|
value.Length > 50; // heuristic for protected payloads
|
||||||
|
|
||||||
|
public string ComputeNameSearchToken(string firstName, string lastName)
|
||||||
|
{
|
||||||
|
var normalized = $"{firstName.Trim().ToLowerInvariant()}|{lastName.Trim().ToLowerInvariant()}";
|
||||||
|
using var hmac = new HMACSHA256(_searchKey);
|
||||||
|
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(normalized));
|
||||||
|
return Convert.ToHexString(hash).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -196,5 +196,13 @@
|
|||||||
"Audience": "VigilCareClinical.Dashboard",
|
"Audience": "VigilCareClinical.Dashboard",
|
||||||
"SigningKey": "DEV-ONLY-REPLACE-WITH-256-BIT-SECRET-IN-PRODUCTION-abc123xyz",
|
"SigningKey": "DEV-ONLY-REPLACE-WITH-256-BIT-SECRET-IN-PRODUCTION-abc123xyz",
|
||||||
"ExpirationMinutes": 480
|
"ExpirationMinutes": 480
|
||||||
|
},
|
||||||
|
"PhiEncryption": {
|
||||||
|
"ProtectorPurpose": "VigilCare.PatientPhi.v1",
|
||||||
|
"SearchTokenKey": "DEV-ONLY-HMAC-KEY-REPLACE-IN-PRODUCTION-32bytes!!",
|
||||||
|
"LogListAccess": true
|
||||||
|
},
|
||||||
|
"DataProtection": {
|
||||||
|
"KeyPath": "./data-protection-keys"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user