Health data and break-glass

This page shows how Custodian handles special-category data, using the Clinic sample. It covers purposes tied to roles, the care relationship as the basis for treatment access, fields whose every read is audited, what the front desk and analysts see, and break-glass access for clinicians in an emergency.

Roles, purposes and the violation mode

The clinic maps each application role to a database role and to the purposes it may process for. It then says what happens when someone reads outside those purposes. The default is Deny. Analysts get Mask. Clinicians get BreakGlass.

o.Roles.Map(ClinicRoles.Clinician, DbRole.Writer, purposes: [Purposes.Treatment, Purposes.Scheduling]);
o.Roles.Map(ClinicRoles.Reception, DbRole.Writer, purposes: [Purposes.Scheduling]);
o.Roles.Map(ClinicRoles.Analyst, DbRole.Reader, purposes: [Purposes.Research]);
o.Roles.Map(ClinicRoles.PrivacyOfficer, DbRole.Privacy, purposes: []);
o.Roles.Map(ClinicRoles.Administrator, DbRole.Writer, purposes: [Purposes.Employment]);

o.Access.OnPurposeViolation(ViolationMode.Deny);
o.Access.ForRole(ClinicRoles.Analyst).OnPurposeViolation(ViolationMode.Mask);
o.Access.ForRole(ClinicRoles.Clinician).OnPurposeViolation(ViolationMode.BreakGlass, b => b
    .JustifyWithin(JustifyWithin)
    .RemindAfter(RemindAfter)
    .EscalateTo(EscalateTo));

The privacy officer holds no purposes. The role exists for oversight and sees ids, never patient data. Roles and purposes explains the mapping in general.

Custodian records the Art. 6 lawful basis of each purpose. It has no place for the Art. 9(2) condition that special-category data also needs. The clinic states that condition in the XML docs of Purposes and in its README.

Fields whose every read is audited

Mark health data with [SpecialCategory]. A field marked this way is personal data without a further [PersonalData] attribute. Custodian encrypts it and audits every read of it, whether you ask for that or not.

/// <summary>
/// What the patient comes in for. Health data (Art. 9), only for treatment. It is a separate entity from the
/// <see cref="Appointment"/> because it serves a narrower purpose: the front desk schedules visits and has no purpose
/// that reaches this table, whichever way it asks. Recorded by the treating practitioner and deleted when the medical
/// record expires.
/// </summary>
[PersonalDataEntity(Purpose = Purposes.Treatment, LawfulBasis = LawfulBasis.Contract,
                    Retention = Retention.MedicalRecords, Anchor = RetentionAnchor.LastActivity, OnExpiry = ExpiryAction.Delete)]
public sealed class VisitReason
{
    public Guid Id { get; set; }

    [DataSubject]
    public Guid PatientSubjectId { get; set; }

    public Guid AppointmentId { get; set; }

    /// <summary>Encrypted with the patient's key, and every read is audited.</summary>
    [SpecialCategory, Encrypted]
    public string? Reason { get; set; }
}

On the Appointment the practitioner link is special category too, because seeing a specialist reveals health.

The care relationship decides the purpose

Custodian knows roles and purposes. It does not know who treats whom. The clinic checks the care relationship itself and declares the purpose that matches.

public async Task<string> PurposeForAsync(SubjectId patient, CancellationToken cancellationToken)
{
    var practitioner = await CurrentPractitionerOrNullAsync(cancellationToken);
    using var scope = processing.Begin(Purposes.Scheduling, patient);

    var carers = await db.CareRelationships
        .Where(care => care.PatientSubjectId == patient.Value)
        .Select(care => care.PractitionerSubjectId)
        .ToListAsync(cancellationToken);

    return practitioner is { } me && carers.Contains(me) ? Purposes.Treatment : Purposes.EmergencyCare;
}

treatment is a purpose the Clinician role holds. emergency-care is a purpose no role holds and no entity is processed for, so every personal field read under it is out of purpose. OpenAsync begins the purpose it is given and queries with plain EF Core. It has no branch for emergencies.

The application says only whether a care relationship exists. Custodian decides what an out-of-purpose read means for the reader's role.

The care relationship is itself special-category data. The clinic never asks the database to filter on it. It reads the patient's relationships for scheduling and compares them in the application.

Reception never sees the reason for a visit

The front desk books visits. It needs to know who comes, to whom and when, and it does not need to know why. The clinic therefore keeps the reason out of the appointment. It is its own entity, VisitReason, shown above, held for treatment only. The Reception role holds only scheduling and its violation mode is Deny, so the read throws.

[Theory, EachProvider]
public async Task A_receptionist_sees_the_appointment_but_not_the_reason_for_the_visit(DatabaseProvider provider)
{
    await using var clinic = await ClinicScenario.OpenAsync(servers, provider);
    var greta = await clinic.Admit(Patients.Greta, toCareOf: Staff.DrLind);

    var reading = clinic.As(Staff.Receptionist).ReasonForVisitOf(greta);

    await Assert.ThrowsAsync<PurposeViolationException>(() => reading);
}

The front desk still sees who comes in, with whom and when (A_receptionist_sees_who_comes_in_today_with_whom_and_when). The refused attempt is audited as a purpose violation (A_receptionists_attempt_to_read_the_reason_for_a_visit_is_audited).

The classification gives this protection, and the clinic's services only follow it. A receptionist who queries the table directly while declaring scheduling is refused too (A_receptionist_who_queries_the_reasons_for_visits_directly_for_scheduling_is_refused), and cannot record a reason either (A_receptionist_cannot_record_the_reason_for_a_visit). The treating practitioner records it.

Give data its own entity when it serves a narrower purpose than the row it belongs to. A field on an entity is open to every purpose that entity declares, unless you reserve it. See Classifying personal data.

Analysts see only masked values

The Analyst role works for research. No entity is processed for research in identifiable form, so every personal field an analyst reads is out of purpose. The role's mode is Mask, so the query succeeds and each such field comes back masked. ResearchDesk is plain EF Core under that purpose.

Break-glass

With ViolationMode.BreakGlass an out-of-purpose read returns the data and holds the reader to account afterwards. The builder in the first snippet sets the terms.

Call Meaning Default
JustifyWithin(TimeSpan) Time allowed after the first access before the item is escalated. 72 hours
RemindAfter(TimeSpan) When the person who accessed is reminded. It must come before the deadline. No reminder
EscalateTo(string) The recipient passed to your notifier when the deadline passes. None
RequireDeclaration() The reader must declare the access before any data is returned. Off

Break-glass is never silent. The first read writes an audit entry flagged as break-glass and opens a justification item. See The_emergency_read_is_flagged_in_the_audit_trail and Break_glass_is_never_silent_the_first_read_opens_an_item_and_a_flagged_audit_entry.

Break-glass covers reads only. Custodian connects read-only for an out-of-purpose access, so a clinician outside the care relationship can read the record and cannot write in it. See A_clinician_cannot_write_in_the_record_of_a_patient_outside_her_care.

One item per user, subject and session

Custodian keeps one justification item per tenant, user, subject and session. The session is the correlation id of the request. Twelve reads in one emergency are one thing to explain.

[Theory, EachProvider]
public async Task Many_reads_in_one_session_are_one_emergency_to_explain(DatabaseProvider provider)
{
    await using var clinic = await ClinicScenario.OpenAsync(servers, provider);
    var greta = await clinic.Admit(Patients.Greta, toCareOf: Staff.DrLind);
    var emergencyShift = clinic.SignIn(Staff.DrBerg);
    await emergencyShift.OpenRecordRepeatedly(greta, times: 12);

    var banner = await emergencyShift.OutstandingJustifications();

    Assert.Single(banner);
}

A new session is a new item (Opening_the_record_again_in_a_new_session_is_a_new_access_to_explain). The item is due JustifyWithin after the first read (The_clinician_has_until_the_deadline_to_explain_the_access).

The review API

IBreakGlassReview lists and explains items. The clinic exposes it on three endpoints of its own.

app.MapGet("/break-glass/mine", (IBreakGlassReview review, CancellationToken ct) => review.GetMineAsync(ct));

app.MapPost("/break-glass/{item:guid}/justify",
    (Guid item, JustificationRequest justification, IBreakGlassReview review, CancellationToken ct) =>
        review.JustifyAsync(new BreakGlassItemId(item), new BreakGlassJustification(justification.ReasonCode, justification.Text), ct));

app.MapGet("/break-glass/outstanding", (bool? overdue, IBreakGlassReview review, CancellationToken ct) =>
        review.GetOutstandingAsync(new BreakGlassFilter(OverdueOnly: overdue ?? false), ct))
    .RequireAuthorization(policy => policy.RequireRole(ClinicRoles.PrivacyOfficer));

Explaining an item clears it from the banner (Explaining_the_access_clears_it_from_the_clinicians_banner). The explanation is audited as BreakGlassJustified. The free text is kept on the item and never reaches the audit table (The_free_text_explanation_never_reaches_the_audit_table). Do not put personal data about the patient in it.

Custodian also maps these calls under /gdpr/break-glass. See ASP.NET Core.

Reminders and escalation

Register an IBreakGlassNotifier to deliver reminders and escalations to email, chat or a SIEM. Without one, nothing is delivered. The interface has two methods, RemindAsync(item) and EscalateAsync(item, recipient). The sample tests register RecordingBreakGlassNotifier as a singleton.

IBreakGlassReview.ProcessDeadlinesAsync sends the due reminders and escalates overdue items. Call it on a timer.

Declaring up front

By default the reader declares nothing before reading. With RequireDeclaration() the read is refused until the reader calls IBreakGlassAccess.DeclareAsync for that subject in the session. The declaration is the explanation, so the item opens already justified. The Clinic sample does not use this. The tests are With_required_declaration_a_read_without_a_declaration_is_refused and After_declaring_the_read_is_revealed_and_its_item_is_already_explained.

Who never gets break-glass

Break-glass applies only where the reader's role is configured for it. A receptionist who opens a record is refused (A_receptionist_who_opens_a_record_is_refused_not_let_through_by_break_glass).

Machines never get it. A system principal that reads a field outside its declared list is denied, whatever the modes say. See Reading_a_field_outside_the_declared_list_is_denied_even_where_people_get_break_glass and System runs.

Next