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).
Problem
Section titled “Problem”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.
Findings (audit 2026-05-29)
Section titled “Findings (audit 2026-05-29)”| # | Surface | Severity | Action |
|---|---|---|---|
| 1 | Dashboard medication trends (time-series, earliest-dispensing-date) | Critical | Add patient_id param; pass activePatient.id; refetch on switch |
| 2 | Analytics page (heatmap, heatmap/medicines, by-reason) | Critical | Add patient_id param; add usePatient(); pass + refetch |
| 3 | Alerts inbox + badge (/alerts, /alerts/open-count) | Medium | Inbox passes patient_id; open-count gains patient_id; scope to active patient |
| 4 | Data export ZIP | Policy → per-patient | Make export scope to the active patient only |
| 5 | History → Audit tab | Medium | audit_log.patient_id column + write + filter; FE default to active patient, admin toggle to all |
| 6 | analytics daily/trend/timeline | Low (latent) | Add patient_id param even though unused by SPA |
| 7 | Observations soft-delete | resolved | Already scoped by patient_id in current code |
| 8 | Dispensing POST script_id↔patient_id | Low | Validate 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.
Backend contract
Section titled “Backend contract”- 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 optionalpatient_id: int | None. When provided:await ensure_patient_access(ctx, patient_id, db)then addAND <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 (#5) design
Section titled “Audit (#5) design”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.
Test plan
Section titled “Test plan”- Backend: admin with two patients — every analytics endpoint with
?patient_id=Areturns only A’s data;ensure_patient_access403 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.
Out of scope
Section titled “Out of scope”- Full per-patient
medicines.patient_idmigration (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:
- Audit
patient_idforward-population — DONE.V099backfilled history, but newcare_shift,patient_appointment,key_contact, andcontact_noteaudit rows were still written withpatient_id = NULL, so they would have dropped out of the History “This person” filter going forward. Allwrite_auditcall sites inrouters/care_shifts.py,routers/patient_appointments.py, androuters/key_contacts.pynow passpatient_id(path param /beforesnapshot). Every clinical audit entity type now populatespatient_idforward. - Clinical trends verified clean — no change.
pain,vitals,observations,sleep, andmindreads/trends are all/patients/{patient_id}/...routes guarded byrequire_patient_access(member →patient_accessrow; admin → same-tenant; super_admin → allowed). Writes userequire_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. - Write-side cross-patient guard verified — no change.
medication_groupsanddispensingswrites bind the pathpatient_idand enforce access; the dispensing POST additionally validatesscript_belongs_to_patient. A user cannot write onto a patient they cannot access. - Export scope — admin-only by design.
POST /api/billing/export/downloadrequiresrequire_tenant_admin. Per-patient export sendspatient_id(validated byensure_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. - Shared-device active-patient selection.
PatientContextnow 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. - Tenant-isolation regression test repaired.
tests/test_rls.pynow readsfull_name_encviadecrypt_patient(thenamecolumn was dropped by the PHI-encryption migrations V089–V091), so the cross-tenant RLS guarantee is genuinely exercised again. - Frontend regression test added.
frontend/src/test/components/PatientIsolation.test.tsxasserts 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).