Skip to content

2026-05-29 — Active-patient isolation sweep (REQ-MED-15)

Version: 1.2 Last Updated: 2026-05-29 22:56:28

Status: Shipped — repo + VPS production (deploy-20260529-2251, migration V099 applied 2026-05-29).

REQ-MED-14 scoped medicine pickers and row labels to the active patient, but several surfaces still present or export data for all patients in the tenant regardless of who is selected in PatientContext. On a production tenant with two patients (Mum, Peter), selecting Peter still shows Mum’s medication trends, analytics, alerts, and a full-account export. This is a cross-patient privacy breach: the “currently selected person” lives only in frontend state, so every aggregate/chart/export read must thread patient_id, and the backend must accept and enforce it via ensure_patient_access.

The rule (REQ-MED-15): when a person is selected, only that person’s clinical data may be viewed or exported. Anyone allocated to that person may see it, but only after selecting them.

#SurfaceSeverityAction
1Dashboard medication trends (time-series, earliest-dispensing-date)CriticalAdd patient_id param; pass activePatient.id; refetch on switch
2Analytics page (heatmap, heatmap/medicines, by-reason)CriticalAdd patient_id param; add usePatient(); pass + refetch
3Alerts inbox + badge (/alerts, /alerts/open-count)MediumInbox passes patient_id; open-count gains patient_id; scope to active patient
4Data export ZIPPolicy → per-patientMake export scope to the active patient only
5History → Audit tabMediumaudit_log.patient_id column + write + filter; FE default to active patient, admin toggle to all
6analytics daily/trend/timelineLow (latent)Add patient_id param even though unused by SPA
7Observations soft-deleteresolvedAlready scoped by patient_id in current code
8Dispensing POST script_id↔patient_idLowValidate the script belongs to the target patient

dispensings.patient_id is NOT NULL and backfilled (V039), so AND d.patient_id = %s is a sound, lossless filter.

  • New shared helper auth.append_single_patient_scope(ctx, patient_id, where, params, db, *, table_alias="d") is not used — instead each analytics endpoint accepts optional patient_id: int | None. When provided: await ensure_patient_access(ctx, patient_id, db) then add AND <alias>.patient_id = %s. When omitted: existing behaviour (append_dispensing_patient_scope_for_member) is retained so admin/account-wide tooling still works.
  • Carer-facing SPA pages always send patient_id.

audit_log gains a nullable patient_id column (migration V092). utils.audit.write_audit accepts optional patient_id and stores it. Clinical audit call sites (dispensings, scripts, medication groups) pass the patient. Backfill derives patient_id for existing rows by joining entity_id to the owning table per entity_type. GET /api/audit gains an optional patient_id filter. Frontend History audit tab defaults to the active patient with an admin-only “All people” toggle.

  • Backend: admin with two patients — every analytics endpoint with ?patient_id=A returns only A’s data; ensure_patient_access 403 for an unrelated patient; alerts open-count scoped; export contains only the requested patient; audit filtered by patient.
  • Frontend: Dashboard + Analytics call analytics with the active patient id and refetch on switch.
  • Full per-patient medicines.patient_id migration (debt D23).
  • Reworking the alert-generation pipeline (only the read/badge scope changes here).

Follow-up hardening (2026-05-29 evening, v1.1)

Section titled “Follow-up hardening (2026-05-29 evening, v1.1)”

A second pass closed the residual gaps surfaced by a “what did we miss” review:

  1. Audit patient_id forward-population — DONE. V099 backfilled history, but new care_shift, patient_appointment, key_contact, and contact_note audit rows were still written with patient_id = NULL, so they would have dropped out of the History “This person” filter going forward. All write_audit call sites in routers/care_shifts.py, routers/patient_appointments.py, and routers/key_contacts.py now pass patient_id (path param / before snapshot). Every clinical audit entity type now populates patient_id forward.
  2. Clinical trends verified clean — no change. pain, vitals, observations, sleep, and mind reads/trends are all /patients/{patient_id}/... routes guarded by require_patient_access (member → patient_access row; admin → same-tenant; super_admin → allowed). Writes use require_carer_role, which builds on the same path-bound check. No tenant-wide aggregate path exists for these, so the analytics-only leak does not extend to them.
  3. Write-side cross-patient guard verified — no change. medication_groups and dispensings writes bind the path patient_id and enforce access; the dispensing POST additionally validates script_belongs_to_patient. A user cannot write onto a patient they cannot access.
  4. Export scope — admin-only by design. POST /api/billing/export/download requires require_tenant_admin. Per-patient export sends patient_id (validated by ensure_patient_access); the account-cancellation portability flow omits it to export the whole account (the data controller’s own data before deletion). Non-admin carers cannot export.
  5. Shared-device active-patient selection. PatientContext now scopes the localStorage key per user id (lyncareos_active_patient:<userId>) and reloads the patient list when the authenticated user changes, clearing the in-memory list/selection on logout. The stored id was already validated against the live per-user list (falling back to the first accessible patient), so this is defence-in-depth against a stale selection on a multi-carer device — the backend always enforces.
  6. Tenant-isolation regression test repaired. tests/test_rls.py now reads full_name_enc via decrypt_patient (the name column was dropped by the PHI-encryption migrations V089–V091), so the cross-tenant RLS guarantee is genuinely exercised again.
  7. Frontend regression test added. frontend/src/test/components/PatientIsolation.test.tsx asserts the Dashboard requests analytics scoped to the active patient id and refetches with the new id on person-switch, and that the aggregate is never requested without a patient id.

Test-suite faithfulness fix (module access)

Section titled “Test-suite faithfulness fix (module access)”

The _FakeRedis test double lacked scan_iter, so cache_service.invalidate_tenant silently failed in tests — the per-user modules cache was never cleared, and the per-user module-access denial tests served stale data. Added scan_iter to the fake so invalidation behaves like production Redis. Also: MODULE_META now covers all shipped modules (added vitals_tracking, condition_templates, custom_observations, family_help); the catalog tests assert full metadata for the shipped set (read from moduleDelivery.ts) and drive off database.MODULES instead of a hardcoded subset. Coming-soon tier placeholders carry their display treatment on the frontend (debt D25).