Phase 4 of the tenant-marking series. Until now isolation depended on every
query remembering its own WHERE clause. With 82 entities and 844 tests, that is
not a guarantee — it is a hope. MariaDB has no row-level security, so the
backstop has to live in Doctrine.
TenantFilter appends (entity_type, entity_id) to every DQL query on a
tenant-owning entity. It ships disabled and TenantFilterSubscriber turns it on
per request.
The filter engages only for a **chosen** environment — an explicit clinic_uuid
on the request, or a stored UserActiveContext. EntityContext now records which
of the two produced it. Locking a user to the role fallback instead would hide
data they are entitled to: a clinic-member doctor who never switched context
lost every appointment belonging to that clinic. Five tests caught exactly that
before the gate was added. Admins and unauthenticated marketplace traffic stay
outside the filter by design.
Two findings from running it rather than reasoning about it:
- Dereferencing a lazy proxy whose target the filter excluded raises
EntityNotFoundException, which surfaced as 500 on four patient endpoints.
ExceptionSubscriber now maps it to 404: outside your environment means it does
not exist for you. It is logged at info level so a genuinely broken FK is still
visible.
- EntityManager::find() by primary key IS filtered in Doctrine ORM 3, contrary
to the limitation carried over from older versions. The stronger guarantee is
pinned by a test so a future regression is noticed, and the documented table
was corrected.
The filter also caught a real leak: a clinic secretary's appointment list
filtered by doctor id alone, so a doctor's personal-practice booking appeared in
the clinic list. The test had been asserting that behaviour.
GlobalTables classifies all 82 entities into four states — carries a tenant,
deliberately global, aggregate child, or recorded debt — and
TenantSchemaCoverageTest fails on anything unclassified. Aggregate children
declare their root explicitly, because several attach through a scalar FK rather
than a Doctrine association and cannot be inferred from metadata; the test walks
each chain to a tenant-owning root. Financial tables stay in DEFERRED with a
ceiling assertion so the list cannot grow quietly.
Deliberately not built: the prePersist assignment listener from the plan. The
tenant columns are NOT NULL without a default, so a missing assignTenant()
already fails loudly at flush — phase 2 surfaced 123 such failures. A listener
would add silent auto-assignment where the current behaviour is an explicit
crash.
EXPLAIN with the filter's conditions still picks idx_appointments_tenant_slot
and uniq_patient_record.
Tests: 844 passing. PHPStan unchanged at its 17 pre-existing errors, none in
files touched here.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>