Skip to content
~/rafael-ferreira

Multitenancy and security in Markmedi: one clinic never sees another

Row-level tenancy with a global scope, per-clinic RBAC, audit trails, hardened uploads and a Sentry that never sees personal data: the security decisions behind a healthcare SaaS.

In a SaaS for clinics, the worst possible bug has a well-known shape: clinic A opens a URL, changes a number in the address bar and sees a patient from clinic B. In any product that would be serious. In a system that holds medical records, it is a health data incident with legal consequences under LGPD, Brazil's data protection law. That is why isolation between clinics was one of the first decisions I made in Markmedi, and most of the other security decisions revolve around it.

One database, one column

I chose row-level tenancy: a single MySQL database, and every table that belongs to a clinic has a clinic_id column. A database per customer gives stronger isolation, but it multiplies migrations, backups and connections, and I run the product on my own. With a column, the risk becomes forgetting the filter somewhere. So the job is to make the filter the default and forgetting it hard.

The first mechanism is a trait, BelongsToClinic, which adds a global scope to models. The scope reads the current clinic from a container binding, current_clinic, and restricts every query to that clinic. Today dozens of models use the trait, from finance to CRM and automations.

trait BelongsToClinic
{
    protected static function bootBelongsToClinic(): void
    {
        static::addGlobalScope('clinic', function (Builder $query) {
            if (app()->bound('current_clinic')) {
                $query->where($query->qualifyColumn('clinic_id'), app('current_clinic')->id);
            }
        });
    }
}

Note the condition: the scope only kicks in when there is a current clinic. In jobs, console commands and public pages there is no "logged-in user's clinic", and a scope that tried to guess would be worse than none at all. The consequence is a coding rule: jobs receive the clinic explicitly in the constructor and query with forClinic($clinic). Anyone reading a job knows which clinic it deals with without relying on global state.

Resolving the clinic on every request

A user can belong to several clinics, for example a dermatologist who works in two places. The SetCurrentClinic middleware runs on every authenticated request. It clears the state left by the previous request, loads all of the user's memberships in a single query, discards suspended clinics, picks the clinic stored in the session (or the first available one) and binds it in the container. The authorization and plan services are registered as scoped, meaning they live for one request and die with it, so that no permission computed for one clinic leaks into the next.

The global scope has a known blind spot in Laravel: route model binding resolves the model before the clinic middleware runs. That is why there is a second barrier. The permission middleware compares the clinic_id of every model coming from the route with the current clinic and rejects the request if they differ. On some routes the response is 404 rather than 403, so as not to confirm that the record exists.

First barrier: the middleware sets the current clinic and the global scope filters by clinic_id. Second barrier: the permission middleware compares the clinic_id of the route models

The patient is global

A less obvious decision: the patient has no clinic_id. It is a global entity, identified by CPF (the Brazilian taxpayer ID), linked to clinics through a pivot table and through appointments. This lets the same person have a single portal, with appointments from different clinics, without duplicate registrations. The price is that patient scoping is done through relationships, and medical records, photos and clinical documents are always tied to the clinic that created them. Access to those records goes through the medical record policy, which checks the current clinic in addition to the role's permission.

The patient is global and is linked to each clinic through a pivot table; medical records, photos and documents stay tied to the clinic that created them

Permissions per clinic and per plan

Authorization has two layers. The first is per-clinic RBAC: each clinic has roles, each role has permissions drawn from a closed catalog defined in code, and each membership has roles. Gates are generated from that catalog, and the policies (there are more than forty) use the gates. The second layer is the plan: a feature can be outside the clinic's plan even if the role allows it. The reason for the denial (plan or role) is returned to the interface, which shows "upgrade" or "ask your administrator for access" accordingly.

Two-layer authorization: the role in the clinic must allow it and the plan must include the feature

Tests cover the cases that matter: the scope staying inert without a clinic, the scope restricting when there is one, the explicit opt-out, and an attempt to delete another clinic's record through the URL, which must end in a 403. There are specific isolation tests for clinical images, body mapping and treatments.

Authentication and abuse

Authentication uses Fortify with TOTP-based 2FA, requiring confirmation of the code and the password when enabling it. In production, the password policy requires at least 12 characters, upper and lower case, numbers, symbols and the uncompromised() rule, which checks Have I Been Pwned using k-anonymity. Deactivated users cannot log in, even with the right password.

Named rate limiters cover the sensitive points: login and 2FA, patient portal activation, portal uploads, document signing codes, gift cards, and resending appointment confirmations. Limits are per user, per IP or both combined, depending on what makes sense for each flow.

Audit trails

There are three append-only logs. The administrative actions log records who did what on the platform: clinic suspension, plan change, user deactivation, session revocation. The medical record access log records every view, edit, export, print and capture, with user, clinic, patient, IP and user agent. The RBAC log keeps the before and after of every role change.

Impersonation, which I use for support, has its own rules: only super administrators can impersonate, never another super administrator, no nested impersonation, and every start and end is audited. Impersonated sessions are also flagged and excluded from product metrics.

Files

Uploads are a classic entry point. Every public image is decoded and re-encoded with GD, which strips metadata and any content hidden in the file. Before decoding, the code checks dimensions and pixel count, so that an image that is small in bytes but huge in pixels cannot take down the worker. SVG is rejected. The stored Content-Type comes from the allow list, never from what the client declared. For clinical files, a rule checks the binary signature (the magic bytes) and requires the extension to match the content.

Private files live in a bucket separate from the public one, under a prefix per clinic and per patient. This makes the exports and deletions required by LGPD easier, since they become a prefix listing. Access is always through short-lived signed URLs, and exporting the full medical record uses a temporary signed route.

What leaves the system

Error monitoring is a leak path few people consider. Markmedi's Sentry runs with send_default_pii turned off, without SQL bindings and without breadcrumbs, and every event goes through a sanitizer that rebuilds the report: exception messages become [Filtered], frame variables are removed, and only the request's route and method survive. I lose a bit of debugging context and gain the guarantee that a medical record never shows up in a third-party dashboard.

Along the same lines, no third-party tag (GTM, GA4, PostHog, pixels) loads in the logged-in area. This is decided on the server, based on the route context, and a test walks through the routes to make sure. The session cookie has its own test that prevents the cookie domain from including the CDN host, so the session never ends up in a CDN log.

Webhooks from payment, WhatsApp, SMS and email providers are verified before any processing, using constant-time comparison (hash_equals) or, in the case of Amazon SNS, certificate signature verification.

The last layer

All of this protects access through the application. For the case where someone reaches the database by another route, medical record content is encrypted field by field with a per-clinic key, stored encrypted by AWS KMS. That model has an article of its own: Medical record encryption with a per-clinic key.

Wrapping up

None of these measures is sophisticated on its own. What makes the difference is making the safe path the default path, with automatic scoping, permissions generated from a catalog and tests that fail when someone strays off the rails. Real time follows the same rules, as I describe in Real time with Laravel Reverb. The full project is at Markmedi.