Skip to main content

Chapter 32 — Authentication & Authorization at Scale

Part VI · Security, Reliability & Observability | Prerequisites: Ch 31 | Builds: Pulsely OIDC login, rotating refresh tokens, RBAC, row-level multi-tenancy per clinic

Earlier you built the primitives — KDFs, AEAD, HMAC, signatures, the four verbs you must never blur. This chapter spends them. Authentication and authorization are where cryptography stops being a toolbox and becomes a system: a thing that has to keep telling the truth about who is asking and what they're allowed to touch, every millisecond, under load, while tokens leak and the people calling your API actively want to read each other's records. It is the part of the backend that fails most quietly and most catastrophically. A bug here doesn't crash the process or spike the latency graph — it just hands one patient another patient's chart, and you find out from a compliance officer. In healthcare that sentence has teeth: a broken access check is not a bug ticket, it's a reportable HIPAA breach — regulator notification, patient notification, the works.

The reframe for this chapter, said once so we can lean on it: a request carries claims, and your auth layer is the membrane that turns claims into a verified principal and a permit-or-deny ruling on a specific object. Two separate jobs — prove identity, then decide access — and the most expensive mistakes come from doing one and forgetting the other. We'll build Pulsely's real login flow against an external identity provider, issue tokens that can actually be revoked, and put two walls between one clinic and another clinic's PHI. This is a dense, opinionated chapter; the payoff is that "auth" stops being a vague anxiety and becomes a small number of invariants you can check on any endpoint in ten seconds.


1. The problem: every role check passed, and the data still leaked​

Start with the incident, because it is the most important paragraph in the chapter.

A patient is logged into the Pulsely portal. Their last visit summary lives at GET /encounters/1042. Idle curiosity — or worse — leads them to change the URL to /encounters/1043. The request sails through: they are authenticated (valid session), they have the patient role, the route allows patients to read encounters. The handler loads encounter 1043 and returns it. It belongs to a stranger. The response contains a diagnosis (ICD-10), a medication list, and the patient's MRN and date of birth. Every check the system performed passed. The bug is not that a check failed; the bug is that the check that mattered never ran. Nobody ever asked, "does this principal own this chart?" That single missing question is a leaked medical record — a reportable breach with a legally mandated clock attached.

This is BOLA — Broken Object-Level Authorization, also called IDOR (Insecure Direct Object Reference) — and it is OWASP's #1 API risk for a reason: it is invisible to role-based thinking. You can have flawless login, perfect RBAC, a beautiful permissions matrix, and still hemorrhage PHI, because roles answer "what kind of thing may this user do?" and IDOR lives in "may this user do it to this specific row?" Hold that distinction; half this chapter is built on it.

Now a second pain, on the authentication side. Someone steals a Pulsely refresh token — via an XSS payload that reads localStorage, or a token accidentally written to a log, or a malicious browser extension on a provider's laptop. The token was long-lived (good for 30 days) and the server kept no record of it: it was a self-contained signed JWT, valid because the signature was valid. The user notices nothing. They click "log out." Logout clears their own browser. The attacker, holding the stolen token, keeps minting fresh access tokens for a month — every one of which can pull charts. There was no record to revoke, so revocation was impossible. The system could prove the token was authentic and had no way to say "but I no longer trust it."

Third pain, the tenancy one. Pulsely is multi-tenant: each clinic (or provider organization) is a tenant, and its providers and staff belong to that tenant. An analyst writes a reporting query for a clinic's dashboard and forgets one clause — WHERE tenant_id = $1. The query is correct SQL. It runs. It renders one clinic's patient panel inside another clinic's dashboard. A single missing predicate is a cross-tenant PHI breach. And here is the systemic lesson: you cannot make correctness depend on every developer, forever, remembering to write a WHERE clause. Some Tuesday someone forgets, and the forgetting is the breach.

Why does this whole subject exist as its own discipline, separate from business logic? Because auth is cross-cutting (it touches every endpoint), adversarial (the inputs are chosen by someone trying to break it), and stateful in a hostile way (a token issued at noon must still be trustworthy at 3pm, or revoked the instant it isn't). Ordinary business logic gets to assume cooperative callers and can be locally reasoned about. Auth has to hold when the caller is hostile, the token has leaked, and the code path was written by your most junior engineer on their second week. That is a different engineering problem, and it earns its own chapter.

🧭 A useful distinction. "Auth" is two jobs wearing one word. Authentication (AuthN) answers "are you who you claim to be?" and produces a verified principal. Authorization (AuthZ) answers "is this principal allowed to do this action on this resource?" and produces a ruling. Login is AuthN. The chart leak was an AuthZ failure. The stolen-token problem was an AuthN-lifecycle failure. Whenever an auth bug confuses you, first ask which of the two jobs broke — the fix lives on different shelves.


2. The mental model: three rings, claims-not-truth, and ambient tenancy​

Picture every request to Pulsely passing through three concentric rings before it's allowed to touch durable state. Skip any ring and you have a named, classic vulnerability.

request ─▶ ┌─────────────────────────────────────────────────┐
│ RING 1 AUTHENTICATE │
│ credential/token → verified PRINCIPAL │
│ (who are you? — signature, iss, aud, exp) │
│ ┌───────────────────────────────────────────┐ │
│ │ RING 2 COARSE AUTHZ (role / scope) │ │
│ │ may this KIND of principal do this KIND │ │
│ │ of action? (requireRole, requireScope) │ │
│ │ ┌─────────────────────────────────────┐ │ │
│ │ │ RING 3 OBJECT/TENANT AUTHZ │ │ │
│ │ │ may THIS principal act on THIS │ │ │
│ │ │ resource? ownership / tenant / │ │ │
│ │ │ care-team — IDOR lives here ──────┼───┼──┼─▶ the leak
│ │ └─────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
▼ all three pass ▼
apply business logic → durable state

Ring 1 establishes a principal — a verified identity, not a claimed one. Ring 2 is the coarse check most people mean when they say "permissions": role or scope (is this a patient, a provider, a biller, an admin?). Ring 3 is the fine check almost everyone forgets: the relationship between this principal and this particular object — do they own it, is it in their tenant, are they on the patient's care team? The chart leak in §1 passed rings 1 and 2 and never reached ring 3. IDOR is the absence of ring 3. Tattoo that on the inside of your eyelids.

The second piece of the model: a token is a claim, not a truth. A JWT in an Authorization header is the request asserting "I am user 42, I am a provider, my tenant is northside-clinic." Those assertions are worth exactly nothing until you have (a) verified them — checked the signature against a key you trust, checked the issuer, audience, and expiry — and (b) cross-checked them against current server state, because some facts the token can't know: was it revoked since issue? is this provider still employed at that clinic? was their role downgraded an hour ago after they left? A token is a frozen photograph of permissions at login time; access decisions happen now, and now may disagree with the photograph.

The third piece is how to think about tenancy. The trap is to treat tenant_id as just another business column that each query happens to filter on. Don't. Model tenancy as an ambient mandatory predicate — a thing that is always in scope for every read and write, enforced by the data layer itself, that a query cannot opt out of without someone explicitly and visibly bypassing the guard. The clinic-dashboard breach happened because tenancy was a convention ("remember the WHERE clause") instead of a guarantee ("the database physically will not return other clinics' rows"). Conventions fail on a long enough timeline; guarantees don't.

There's a fourth idea that runs underneath all three rings and is specific to healthcare: minimum necessary. HIPAA doesn't just ask "is this person a provider?" — it asks "does this provider need this record to do their job right now?" A biller needs the diagnosis and the CPT codes to submit a claim, but not the full psychotherapy note. A front-desk scheduler needs the appointment, not the labs. So authorization here is not a single yes/no per role; it's a scoped yes that narrows what fields and which records each role can touch. Default-deny plus minimum-necessary is the whole posture: grant the least, and grant it per-object.

🧭 Mental model. Authorization is not a property baked into a token at login — it is a function evaluated at the moment of access: decide(subject, action, resource, context) → permit | deny. The token supplies subject (after verification). The route supplies action. The URL/body supplies resource. The server supplies context (current roles, tenant membership, care-team relationship, time). Every auth design in this chapter is just a different way to make that function correct, fast, and impossible to skip. When an endpoint feels under-protected, ask: which argument am I not actually checking?


3. Theory & invariants​

Invariants are the rules that must hold no matter who's calling or how clever the attack. These are the load-bearing ones for auth; if you can recite and apply them, you've prevented most of the bugs in this chapter.

🔑 The verified-principal invariant. A principal's identity is never derived from data the client could forge. The subject of an action comes from a verified token or session — never from a userId field in the request body, a query param, or a header the client controls. The body may say providerId: 99; the server takes the identity from the verified token and ignores the body entirely. This is the authority principle pointed straight at identity: the client asks, the server decides who's asking.

🔑 The token-verification invariant. Before a token is trusted, all of these must pass, in this spirit: signature valid under a key you trust → alg is on an explicit allow-list (never "whatever the header says") → iss (issuer) is the IdP you expect → aud (audience) names this service → exp/nbf put now inside the validity window. Failing any one is a hard reject. There is no "best effort" verification — a token is either fully validated or it is garbage, and garbage gets a 401.

🔑 The default-deny (minimum-necessary) invariant. The absence of an explicit grant is a denial. Authorization is allow-listing, never deny-listing: you enumerate what is permitted and refuse everything else, because the set of dangerous actions is unbounded and you will never enumerate it completely. In a PHI system this is also the minimum-necessary rule in code form — grant the narrowest access that lets the role do its job. A new endpoint shipped without an auth decision must fail closed (403), not fall through to permitted.

🔑 The object-level invariant. Every endpoint that accepts a resource identifier must prove the principal's relationship to that specific resource — ownership, tenant membership, care-team assignment, or an explicit share — before acting on it. This is ring 3, stated as law. "The user is logged in and has the right role" is necessary and never sufficient when an object ID is in play. Skipping it is the reportable-breach path from §1.

🔑 The tenancy invariant. No query returns or mutates a row outside the caller's tenant (clinic). This is a system guarantee enforced by the data layer, not a per-query convention enforced by developer memory. The correctness of multi-tenancy must not be a function of whether someone remembered a clause.

A few consequences and definitions that the rest of the chapter leans on:

Privilege escalation comes in two flavors, and they're different bugs. Vertical escalation is gaining a higher privilege level than you should have — a biller performing a provider-only action like signing a note; this is a ring-2 (role) failure. Horizontal escalation is accessing a peer's resources at your own privilege level — one patient reading another patient's chart, or one provider reading a patient outside their care team; this is a ring-3 (object) failure. The chart leak was horizontal. Naming which one you're defending against tells you which ring to fix.

The confused-deputy problem. Picture your API gateway — which can do almost anything — receiving a request from a low-privilege user and just forwarding it downstream with its own god-mode credentials, without re-asking "was this user even allowed to request this?" The powerful service got "confused" into spending its authority on someone else's behalf. That's the confused deputy: a high-privilege service performs an action on behalf of a less-privileged caller without re-checking the caller's right to ask. The canonical mistake in a microservice fleet: your api service trusts an end-user's token and forwards it (or its own service credential) to the e-prescribing service, which does no further check and writes a prescription the caller was never entitled to order. This is why §5 forbids reusing end-user tokens for internal hops.

📎 Borrowed on credit: idempotency. Refresh-token rotation (§4) needs exactly-once effects under retries — if a network blip makes a client retry a token refresh, you must not accidentally invalidate a good token family or mint two. The delivery-semantics and idempotency machinery this relies on were developed in the idempotency and delivery-semantics chapter; here we just assume "this write happens once even if the request arrives twice" and build on it. If that phrase isn't reflexive yet, that's its home.


4. Under the hood​

Time to open the boxes. We'll go in dependency order: passwords (even though we're replacing them, you must know them), then JWT mechanics and their sharp edges, then sessions-vs-tokens, then refresh rotation, then the OAuth2/OIDC flow Pulsely actually adopts, then row-level security in Postgres.

Password authentication done right (then mostly handed to an IdP)​

Even though Pulsely is moving to OIDC, you must understand password auth, because something stores passwords (your IdP, or you before you migrate), and the failure modes are exam-grade. The rules, building directly on the password KDFs you already met:

  • Hash with a password KDF, never a fast hash. Argon2id (current default), or scrypt/bcrypt. Never SHA-256/MD5 — they're built for speed, which is the attacker's friend. Per-password random salt (defeats rainbow tables and makes identical passwords hash differently). Optional pepper kept outside the DB (a secret added to every password so a DB-only leak isn't enough).
  • Compare in constant time. Verification uses the KDF's own verify (which is constant-time); never a plain === on hashes.
  • Be account-enumeration-safe. "Wrong email" and "wrong password" must be indistinguishable — same message, same status, same timing. If "no such user" returns in 5ms and "wrong password" takes 200ms (because it actually ran Argon2id), an attacker times your responses to harvest valid emails — and in healthcare, knowing that a given email belongs to a patient of an oncology clinic is itself a disclosure. Run a dummy hash on the no-user path to equalize timing.
  • Rate-limit and back off. Lockout or exponential backoff per account and per IP. Login is expensive (Argon2id is ~150ms by design), which makes it a DoS lever — separate, harder limits here.
  • Check breach lists on set. When a user picks a password, check it against Have I Been Pwned using k-anonymity (send the first 5 hex chars of the SHA-1, get back the suffix list, compare locally — you never send the full password or its full hash).
import argon2 from "argon2"; // @node-rs/argon2 is faster; same API shape

async function verifyLogin(email: string, password: string) {
const user = await users.findByEmail(email);
// Constant-time-ish: always run a hash, even when the user doesn't exist,
// so timing can't distinguish "no such account" from "wrong password".
const hash = user?.passwordHash ?? DUMMY_HASH;
const ok = await argon2.verify(hash, password); // constant-time internally
if (!user || !ok) return null; // identical failure for both

// Algorithm agility: if our cost factor was bumped since this hash was made,
// transparently rehash on successful login.
if (argon2.needsRehash(hash, CURRENT_PARAMS)) {
await users.updateHash(user.id, await argon2.hash(password, CURRENT_PARAMS));
}
return user;
}

🏭 Skippable JVM aside. In the JVM world, Spring Security encodes this algorithm-agility pattern explicitly: DelegatingPasswordEncoder stores the algorithm name as a prefix on the hash itself — {argon2}$argon2id$..., {bcrypt}$2b$... — so you can migrate hashing schemes user-by-user on login without a flag day. Node makes you hand-roll the same idea (the needsRehash check above). Ignore the Java vocabulary; the transferable payoff is the principle: store enough about how a secret was protected, alongside the secret, that you can change the method later.

JWT internals — and the pitfalls that own this section​

A JWT is three base64url chunks joined by dots: header.payload.signature.

eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjQtMDYifQ ← header {"alg":"RS256","kid":"2024-06"}
.eyJzdWIiOiJ1c2VyXzQyIiwiYXVkIjoicHVsc2VseS1hcGkiLCJleHAiOjE3...
← payload {"sub":"user_42","aud":"pulsely-api","exp":...}
.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ← signature over header.payload

Three facts that prevent most JWT disasters:

  1. A JWT is signed, not encrypted. The payload is readable by anyone who has the token — base64url is encoding, not secrecy. Never put PHI or a secret in a JWT payload. No diagnosis, no MRN, no SSN in a claim. Assume the user, their browser extensions, and any log that captured the token can read every claim.
  2. The signature proves integrity and origin, nothing else. HS256 uses a shared secret (symmetric HMAC — anyone who can verify can also forge, so the secret never leaves your trust boundary). RS256/ES256 use an asymmetric keypair — the IdP signs with a private key, you verify with the public key, which the IdP publishes at a JWKS endpoint (/.well-known/jwks.json). Asymmetric is what makes OIDC work: the IdP holds the private key, every service verifies with the public one, and a leak of your verifier reveals nothing.
  3. Verification is an allow-list discipline, not a parse. Decoding a JWT is trivial and meaningless; verifying it is the whole job.
import { jwtVerify, createRemoteJWKSet } from "jose";

// Cached JWKS: fetched from the IdP, refreshed on a kid-miss, TTL'd.
// Same stale-while-revalidate instinct as React Query — serve the cached
// keys, revalidate in the background, only block on a genuine cache miss.
const JWKS = createRemoteJWKSet(new URL("https://idp.pulsely.health/.well-known/jwks.json"));

async function verifyAccessToken(token: string) {
const { payload } = await jwtVerify(token, JWKS, {
issuer: "https://idp.pulsely.health", // iss MUST match
audience: "pulsely-api", // aud MUST name THIS service
algorithms: ["RS256"], // alg allow-list — the single most important line
});
// exp/nbf are checked by jwtVerify. Now cross-check live state:
if (await revoked(payload.jti)) throw new Error("revoked");
return payload; // the verified principal
}

Now the pitfalls — mechanics, not just warnings:

  • alg: none. The spec includes an "unsecured" mode where alg is none and there is no signature. A naïve verifier that honors the header's alg will accept a token with no signature at all. An attacker strips the signature, sets alg: none, edits the payload to "role":"admin", and walks in. Fix: never read alg from the token to decide how to verify; pass an explicit algorithms allow-list (as above) and none is never on it.
  • Algorithm confusion (RS256 → HS256). Subtler and nastier. In plain terms: RS256 uses two different keys — a private one to sign, a public one to verify — while HS256 uses one key for both signing and verifying. The attack tricks your server into HS256 mode, where the one key it happens to hold — your public verifier key, which the attacker also downloaded from your public JWKS endpoint — is now enough to forge a signature. Concretely: your service expects RS256 (asymmetric) and has the IdP's public key on hand to verify. An attacker crafts a token with alg: HS256, then signs it using your public key as the HMAC secret. If your verifier sees HS256 and dutifully runs HMAC with "the key it has" — the public key, which is public — the signature checks out and the forgery is accepted. Fix: pin the algorithm (algorithms: ["RS256"]); the verifier refuses to treat a public key as an HMAC secret because it refuses HS256 entirely.
  • kid injection. The header's kid (key ID) tells you which key to use. If you naïvely use it as a file path or SQL lookup, an attacker can path-traverse (kid: "../../public.pem") or inject. Fix: treat kid as an opaque lookup key into a trusted JWKS set, never as a path or query fragment.
  • Missing aud → cross-service replay. A token minted for the low-trust pulsely-scans service (it just stores uploaded document images) is presented to the high-trust pulsely-rx e-prescribing service. If pulsely-rx doesn't check aud, it accepts a token never meant for it — and now a scan-upload token can write a prescription. Fix: every service validates that aud names itself.
  • Trusting exp alone with no revocation path. exp only bounds the maximum damage window. With a 30-day token and no revocation, a stolen token is good for 30 days — exactly the §1 incident. Fix: short access-token TTL plus a revocable refresh mechanism (next sections).

Sessions vs tokens — the actual mechanics​

Two ways to remember "this caller is logged in," and the difference is where the truth lives:

  • Opaque session ID. The server hands the client a random, meaningless ID. On every request the server looks it up in a shared store (Redis) to find the associated user and permissions. Revocable instantly (delete the row), stateful (needs a fast shared store), costs one lookup per request.
  • Self-contained JWT. The token is the user info, signed. No lookup needed — verify the signature and read the claims. Stateless (any instance can verify with the public key, no shared store), scales horizontally for free, but revocation is hard (the token is valid until exp no matter what you wish).

The carrier matters as much as the format. If auth rides in a cookie, it must be HttpOnly (JS can't read it → XSS can't steal it), Secure (HTTPS only), and SameSite=Lax or Strict (mitigates CSRF), ideally with the __Host- prefix (binds it to the exact host, no subdomain leakage). But cookies are sent automatically by the browser, which is exactly what enables CSRF — a malicious site triggers a request to Pulsely and the browser helpfully attaches the cookie. The Authorization: Bearer <token> header, by contrast, is not sent automatically (your JS must attach it), so it's CSRF-immune — at the cost of living somewhere JS can reach, which reopens XSS theft. There's no free lunch; §5 picks Pulsely's poison deliberately.

Refresh-token rotation and reuse detection​

This is how you get the scalability of JWTs and real revocation. Two tokens, two lifetimes:

  • Access token: JWT, short-lived (5–15 min), stateless, sent on every API call. Its shortness is the revocation story for most cases — a stolen access token dies in minutes.
  • Refresh token: opaque (not a JWT), long-lived, single-use, used only to mint new access tokens. Stored hashed server-side (treat it like a password — if your token store leaks, the hashes aren't usable).

The magic is rotation with reuse detection. Every time a refresh token is used, you issue a new refresh token and invalidate the old one, recording them as members of a family (a lineage descending from the original login). The invariant: a refresh token is valid exactly once.

login ──▶ RT₀ ──use──▶ (issue RT₁, invalidate RT₀) ──use──▶ (issue RT₂, invalidate RT₁) ──▶ ...
│
└── if RT₀ is presented AGAIN (already rotated) ──▶ THEFT DETECTED
└─▶ revoke the ENTIRE family

Why this catches theft that nothing else does: suppose an attacker steals RT₁. Either the attacker uses it first (rotating to RT₂), and then the legitimate user later presents RT₁ — an already-rotated token — or vice versa. Either way, an already-used refresh token gets presented a second time, and that double-use is the unambiguous signal that the family has been compromised. You revoke the whole lineage, both the attacker and the victim are logged out, and the victim re-authenticates (annoying) while the attacker is locked out (the point). You can't tell which presenter is the thief, so you nuke the family and let the real user log back in.

OAuth2 / OIDC under the hood — what Pulsely actually adopts​

Pulsely stops storing passwords and delegates authentication to an external Identity Provider (Keycloak, Auth0, Cognito) via OpenID Connect, which is an identity layer on top of OAuth2. The only browser-correct grant today is Authorization Code + PKCE.

Browser/SPA Pulsely BFF IdP (idp.pulsely.health)
│ │ │
│ 1. click "Log in" │ │
│─────────────────────▶│ generate code_verifier, │
│ │ code_challenge=SHA256(v), │
│ │ state (CSRF), nonce (replay)│
│ 2. 302 redirect to IdP authorize? │
│ client_id, redirect_uri, scope=openid, │
│ code_challenge, state, nonce │
│───────────────────────────────────────────────────▶│
│ 3. user authenticates at IdP (password, MFA, SSO) │
│◀───────────────────────────────────────────────────│
│ 4. 302 back to redirect_uri?code=AUTH_CODE&state │
│─────────────────────▶│ verify state matches │
│ │ 5. POST /token │
│ │ code, code_verifier ──────▶│ verify SHA256(verifier)==challenge
│ │◀── id_token + access_token + refresh_token
│ │ 6. verify id_token: sig(JWKS),
│ │ iss, aud, nonce; mint session
│◀── set HttpOnly cookie│ │

The pieces that matter and why:

  • code_verifier / code_challenge (PKCE). The client invents a random secret (verifier), sends only its hash (challenge) when starting the flow, and sends the raw verifier only at the token exchange. Even if an attacker intercepts the code (it travels through the browser, e.g. via redirect), they can't exchange it without the verifier they never saw. PKCE kills authorization-code interception.
  • state. An opaque value you generate and verify on return — it ties the callback to the request you started, defeating CSRF on the login flow.
  • nonce. Echoed inside the id_token; you check it matches what you sent — defeats replay of a stolen id_token.
  • id_token vs access_token — the OIDC distinction people blur. The id_token is an authentication assertion: "the IdP confirms this is user 42, they logged in at this time." You consume it once to establish identity, then throw it away. The access_token is an authorization credential: "the bearer may call these APIs with these scopes." You attach it to API calls. Using an id_token to authorize API access, or sending an access_token and reading identity off it, are both category errors.
  • Discovery. /.well-known/openid-configuration tells you every endpoint and the JWKS URL — you configure one URL, not ten.
  • Client Credentials grant (no user, machine-to-machine) is the service analog — a service authenticates as itself to get a token. We use it in §5 for service-to-service.

🛑 What we deliberately did not explain. The full OAuth2 spec has grants we are not teaching because they're wrong for Pulsely or dead: the Implicit grant (tokens returned directly in the redirect URL) is deprecated — tokens in a URL leak into history, referer headers, and logs; PKCE replaced it. The Resource Owner Password Credentials grant (app collects the password and forwards it) defeats the entire point of delegation. We also skip token introspection endpoints, dynamic client registration, and the device-code flow (for TVs and clinical kiosks). They exist; they're not Pulsely's path. If you ever reach for Implicit, stop — that's PKCE's job now.

Row-Level Security in Postgres — the second tenancy wall​

The tenancy invariant says the database enforces isolation, so a forgotten WHERE can't breach. Postgres Row-Level Security (RLS) does exactly that: you attach a policy to a table, and Postgres silently appends it to every query.

ALTER TABLE patients ENABLE ROW LEVEL SECURITY;
ALTER TABLE patients FORCE ROW LEVEL SECURITY; -- applies even to the table owner

-- The policy reads a per-connection setting; every row not matching is invisible.
CREATE POLICY tenant_isolation ON patients
USING (tenant_id = current_setting('app.tenant_id')::uuid);

The application sets app.tenant_id from the verified token at the start of each transaction:

await db.tx(async (t) => {
// SET LOCAL is scoped to THIS transaction and auto-resets on commit/rollback.
await t.none("SET LOCAL app.tenant_id = $1", [principal.tenantId]);
// From here, even `SELECT * FROM patients` returns ONLY this clinic's rows.
return t.any("SELECT * FROM patients WHERE status = 'active'");
});

Two mechanics that bite people:

  • Connection pooling + RLS = danger if you're sloppy. Pooled connections are reused across requests. If you SET (not SET LOCAL) the tenant, the setting persists on the connection and the next request — a different clinic — inherits it. Cross-tenant PHI breach via the pool. Fix: SET LOCAL inside a transaction (auto-resets), or reset on checkout. This is the most common RLS footgun.

  • BYPASSRLS for migrations/admin. Schema changes and cross-tenant admin jobs need to see all rows; run those as a role with BYPASSRLS, never the request-path role. The request path never bypasses.

  • Strict current_setting fails closed-loud, not closed-quiet. First, a SQL subtlety this hinges on: comparing anything to NULL is never true — so tenant_id = NULL quietly matches no rows at all, rather than erroring or matching everything. That one fact decides how a missing tenant context fails:

    • One arg, current_setting('app.tenant_id') — throws if the tenant was never set. A request that forgot to set context errors out loudly, so you catch it in dev.
    • Two args, current_setting('app.tenant_id', true) — returns NULL instead, so the policy compares tenant_id = NULL, matches no rows, and returns an empty set silently: a mysteriously empty dashboard in production that nobody can explain.

    Both fail closed (no leak either way). Prefer the loud one — a caught error in dev beats a silent empty page in prod — unless an empty result for an unset tenant is genuinely correct.


5. In production: the auth system that actually runs​

The mechanics from §4 become an operable system only when you decide where every token lives, who makes the decision, and how you'll see it failing.

Where each token goes. This is a real decision with real tradeoffs, and Pulsely's answer is the BFF (Backend-For-Frontend) pattern: the browser talks only to a Pulsely backend, and tokens never reach the browser at all. The BFF holds the access and refresh tokens server-side and maps the browser to them via an HttpOnly, Secure, SameSite=Lax, __Host--prefixed session cookie. The browser can't read the cookie (XSS can't steal it), the tokens never touch JS, and CSRF is handled with the cookie's SameSite plus a CSRF token on state-changing requests. The alternative people reach for — access token in JS memory, refresh token in localStorage — is the §1 theft vector; never put a refresh token in localStorage. If you must hold tokens in the browser, access-in-memory + refresh-in-HttpOnly-cookie is the floor; BFF is better — and for a PHI portal, a leaked long-lived token is a leaked chart, so BFF is the default.

Centralize the decision; never scatter it. The single worst operational pattern in auth is if (user.role === 'admin') sprinkled across forty controllers — because the fortieth one will be wrong, and you'll never find it. Funnel every authorization through one guard that loads the resource, derives the principal-resource relationship, and calls one authorize():

// One guard. Every protected route declares its requirement; the guard enforces it.
function authorize(action: string, loadResource: (req) => Promise<Resource | null>) {
return async (req, res, next) => {
const p = req.principal; // ring 1: set by the verify middleware
if (!hasScope(p, action)) return res.sendStatus(403); // ring 2: coarse role/scope
const resource = await loadResource(req); // ring 3: the actual object
if (!resource) return res.sendStatus(404);
if (!onCareTeamOrOwns(p, resource)) return res.sendStatus(403); // the IDOR-killing check
req.resource = resource; // hand the loaded object to the handler
next();
};
}

// Usage — the object-level check is now structurally impossible to forget:
app.get("/encounters/:id",
authorize("encounter:read", req => encounters.findById(req.params.id)),
(req, res) => res.json(req.resource));

Notice the route cannot reach its handler without ring 3 running, because ring 3 is what loads req.resource. You made the safe path the only path. NestJS expresses this as Guards; Spring expresses it as @PreAuthorize("hasPermission(#id, 'Encounter', 'read')") method security — same idea, the framework's name for "one place, declarative, unskippable."

🏭 The 404 on a missing resource and 403 on a forbidden one is a real choice with a subtlety: returning 403 for resources that exist but aren't yours leaks their existence (an attacker probing IDs learns which MRNs are real patients). For PHI, return 404 for both "doesn't exist" and "not yours" so the existence of a patient record stays secret. For Pulsely charts we do exactly that.

Break-glass — emergency access, logged and justified. Minimum-necessary and care-team scoping are right almost all the time, and wrong in the one moment that matters most: an unconscious patient arrives in the ED and the treating physician is not on their care team, so default-deny would block the chart. Healthcare's answer is break-glass: a provider can override the object-level denial for a patient outside their normal scope — but only by explicitly invoking emergency access and typing a justification, which fires a high-priority, immutable audit event and flags the access for after-the-fact review. The access is granted; the accountability is total. Design it as a first-class path in the guard (a distinct emergency scope that requires a reason and cannot be silent), never as a role someone just carries around. The rule of thumb: break-glass makes the hard case possible while making the abuse case loud.

Tenancy operationalized — two walls. The tenant_id comes from the verified token, threaded through the request via AsyncLocalStorage (Node's mechanism for per-request ambient context — think of it as a value that's implicitly available for the whole request without being passed through every function argument) so it's available everywhere without threading it through every signature. Wall one: the repository layer asserts tenant_id on every query (app-layer scoping). Wall two: Postgres RLS enforces it even if the repository forgets (§4). Defense-in-depth — the breach in §1 needs both walls to fail simultaneously, which is far less likely than one developer forgetting one clause.

API keys done right (for partner integrations — a lab, a clearinghouse, or an eligibility service calling your API server-to-server). A key is prefix + random_secret — the prefix (plk_live_…) is for identification and log-safety, the secret is high-entropy. Store only a hash of the secret; show the full key once at creation and never again. Each key carries scopes (what it can do), supports rotation (overlap old and new), per-key rate limits, instant revocation, and a last-used audit timestamp. Treat API keys as low-trust, server-to-server only — they're long-lived bearer secrets, so scope them tightly and rotate on any suspicion.

Service-to-service auth — don't reuse user tokens. When Pulsely's api service calls its rx (e-prescribing) service, it must not forward the end-user's token (confused-deputy: rx would act with the user's authority and skip its own checks). Instead, services authenticate as themselves: either

  • mTLS — each service presents its own client certificate, and the certificate names the service the way an SSL certificate names a website. In bigger setups a service mesh hands out these identities automatically (SPIFFE is the standard format for them), so you don't issue certs by hand; or
  • short-lived signed service tokens — the service fetches a token by logging in as itself (the client-credentials grant from earlier in §4).

The end-user identity travels as data in the request (a sub claim rx can log), never as the credential for the hop.

Observability — but only the auth-relevant slice. Audit-log every authorization deny and every privileged action with subject / action / resource / decision / tenant. In a PHI system this obligation is far larger — every chart view is auditable, not just writes — and that immutable audit log gets its own treatment in the observability chapter. Here, alarm on two signals specifically: refresh-token reuse detections (a spike means token theft is happening right now) and bursts of 403s (someone is probing object IDs — an IDOR attack against patient records in progress).

📎 Borrowed on credit: the reliability and observability of the auth service itself. The auth service is now on the critical path of every request — if it's slow, everything is slow; if it's down, nobody logs in and no chart opens. How to give it timeouts, circuit breakers, and bulkheads so a slow JWKS fetch doesn't take down the fleet (Chapter 33), and how to build the immutable, append-only HIPAA audit log that records who viewed which record and lets you answer "who accessed this chart?" — plus tracing an auth decision across services and alerting on burn-rate rather than raw 403 counts (Chapter 34) — are reliability and observability problems, not auth-correctness problems. We're flagging the dependency, not solving it here. The JWKS-stampede risk in §8 is the teaser; the cure is two chapters away.


6. Common pitfalls​

Each is signature → fix: the symptom you'll see, then the principle that resolves it.

Trusting userId from the body or even the JWT for ownership. Signature: a user reads or edits another's record by supplying a different ID; the handler used the request's claimed user/owner instead of checking the loaded resource. Fix: derive the subject from the verified token only; check ownership / care-team relationship against the actually-loaded resource, never against an input field.

Role check with no object check. Signature: requireRole('provider') passes, then the handler acts on any encounter ID — horizontal escalation / IDOR. The §1 leak. Fix: ring 2 and ring 3 are both mandatory; after the role check, verify the principal-resource relationship at the resource. Centralize so it can't be skipped.

alg not pinned during JWT verification. Signature: a forged token with alg: none or an HS256/RS256 confusion forgery is accepted; "admin" appears in logs for a user who isn't one. Fix: explicit algorithms: ['RS256'] allow-list; never derive the verification algorithm from the token header.

Long-lived access tokens / "logout" doesn't revoke. Signature: a stolen token pulls charts for days or weeks; clicking logout changes nothing for the attacker. Fix: short access TTL (5–15 min) + rotating, revocable refresh tokens + family revocation. Logout invalidates the refresh family server-side.

Refresh token not single-use. Signature: a refresh token replays indefinitely; theft is undetectable because reuse looks normal. Fix: rotate on every use and detect reuse of an already-rotated token → revoke the whole family.

Sequential / guessable resource IDs treated as the defense. Signature: /encounters/1043 enumeration; or the team "fixed" IDOR by switching to UUIDs and stopped there. Fix: object-level authorization is always mandatory. UUIDs reduce blast radius (unguessable) but are not an access control — never rely on "they can't guess the ID." A guessable MRN plus a missing ring-3 check is a breach.

Tenant ID taken from a request header or param. Signature: trivial cross-tenant access by changing X-Tenant-Id; the client picks its own clinic. Fix: tenant comes from the verified token; enforce via RLS so even a code bug can't cross clinics.

Missing aud/iss validation. Signature: a token minted for a low-trust service is accepted by a high-trust one. Fix: every service validates iss is the expected IdP and aud names itself.

Connection-pool leaks RLS context. Signature: intermittent wrong-tenant data under load; impossible to reproduce in dev (single connection). Fix: SET LOCAL inside a transaction (auto-resets), or reset tenant on every pool checkout. Never plain SET.

OAuth flow without state / PKCE / nonce. Signature: login CSRF, authorization-code interception, or id_token replay. Fix: PKCE + state on every flow; nonce for OIDC id_tokens. Non-negotiable.


7. Tradeoffs​

Senior auth work is naming the spectrum and saying why you stand where you stand.

Stateless JWT ↔ server sessions. Pure JWT scales without any shared store (any instance verifies with the public key) but can't be instantly revoked and bloats as you stuff claims in. Pure server sessions revoke instantly (delete the row) but add a Redis lookup to every request and make Redis a hot dependency. Pulsely's choice: hybrid — short-lived JWT access tokens + opaque, revocable, server-stored refresh tokens. You get stateless verification on the hot path (every API call) and real revocation on the lifecycle path (refresh). You'd reverse toward pure sessions if you needed immediate global logout/ban (a 15-minute access-token window is unacceptable — e.g. instantly cutting off a terminated employee's access to PHI) and already run low-latency Redis. This is the first Pulsely ADR.

RBAC ↔ ABAC ↔ ReBAC. RBAC (roles) is simple, coarse, auditable, and great for "kinds of users" — patient / provider / biller / admin — but it explodes the moment you need exceptions like "a provider may amend their own encounter note but not another clinician's," because that's not a role, it's a relationship. ABAC (policies over attributes: if resource.clinic == user.clinic and user.onCareTeam) is flexible and expresses minimum-necessary well, but is hard to audit and test — you can't easily answer "who can access this patient?" ReBAC (Google Zanzibar-style relationship tuples: provider:42 is on care-team of patient:1043) models care-team and referral graphs naturally but is operationally heavy (a whole tuple store and check service). Pulsely's choice: RBAC for the coarse layer + a per-object care-team/ownership predicate — a pragmatic slice of ReBAC without the infrastructure. Adopt full ReBAC only when real clinical sharing arrives ("share this chart with these three consulting specialists"), which is when RBAC's exception-explosion becomes unbearable.

RLS ↔ app-layer scoping ↔ schema-per-tenant. RLS is enforced even when devs forget, but couples you to Postgres and has the pooling footgun. App-only WHERE tenant_id is portable and DB-agnostic but one missed clause is a breach (§1). Schema- or database-per-tenant is the strongest isolation and gives noisy-neighbor control, but is operationally costly (migrations across N schemas) and makes cross-tenant analytics painful. Pulsely's choice: RLS + app-layer scoping, defense-in-depth — two independent walls. You'd reverse toward DB-per-tenant for large regulated health-system tenants who contractually demand physical isolation of their patients' PHI. This is the second Pulsely ADR.

Own your IdP ↔ delegate via OIDC. Delegating (Pulsely's choice) removes password-handling liability, gets you SSO/MFA/social-login "for free," and means you never store a credential to leak — at the cost of a hard dependency on the IdP and redirect-flow complexity. Rolling your own keeps full control but makes credential breaches your problem. Most products should delegate; you own your IdP only when you are the identity product or have hard offline/air-gap constraints.

API keys ↔ OAuth tokens. Keys are simple and long-lived — perfect for machines (a lab or clearinghouse integration), dangerous if leaked (they're standing bearer secrets). OAuth tokens are short-lived and scoped but require a flow and a token endpoint. Use keys for partner server-to-server where simplicity wins and you can scope+rotate; use OAuth everywhere a user is involved.

🚫 A framing this book rejects. "Authentication is the hard part; once they're logged in, authorization is just a role check." This is exactly backwards in practice. Authentication is a largely solved problem you should delegate (OIDC, an IdP). Authorization — and specifically object-level authorization — is the part you cannot outsource, the part that's wrong in most codebases, and the part that leaks charts. The §1 incident had perfect authentication. Treat AuthZ, not AuthN, as the discipline that earns your attention.


8. Security & scale notes​

The threat surface this chapter introduces. Token theft (XSS, log leakage, referer headers, malicious extensions); algorithm confusion and alg:none; CSRF (whenever auth rides in cookies); replay (missing nonce/jti); confused-deputy (forwarding user tokens internally); account enumeration (login/forgot-password timing and message differences); vertical and horizontal privilege escalation; and tenant bleed across clinics. Every one has a named defense above; the point of listing them together is that auth is the most-attacked surface you own, so its defenses are a checklist, not a vibe.

Defenses that bound the damage. Short token TTLs shrink the theft window — a stolen access token that dies in 10 minutes is a far smaller incident than one good for 30 days. A jti (token ID) plus a short-lived replay cache stops one-time tokens from being used twice. Token binding / DPoP (binding a token to a client-held key so a stolen bearer token is useless without the key) defeats pure bearer-replay; reach for it when token theft is a top threat. And rate-limit auth endpoints separately and harder than the rest of the API, with CAPTCHA/backoff escalation against credential stuffing — because the login path is expensive by design (Argon2id) and thus a natural DoS target.

Scale behavior you must design for. Three sharp edges:

  • JWKS fetch stampede. Every service verifies tokens against the IdP's public keys (JWKS). If you fetch JWKS per-request, or all instances refresh simultaneously after a key rotation, you stampede the IdP and it becomes a single point of failure for all logins. Fix: cache JWKS with a TTL, refresh lazily on a kid-miss, and jitter refreshes. (The resilience patterns to make this safe under failure — circuit-break the JWKS call, serve the last-known-good keys — belong to the reliability chapter; flagged earlier.)
  • Revocation/session lookups are a hot dependency. The revocable side (refresh store, session store) sits on the request path; size and replicate it, or it becomes the bottleneck that the stateless JWT design was trying to avoid. Hybrid wins precisely because the hot path (access-token verification) stays stateless and only the cold path (refresh) hits the store.
  • Refresh rotation is write-amplifying. Every token refresh is a write (invalidate old, insert new). At scale this is real write volume on the token store — plan for it, and prune expired families.

🔑 Blast-radius asymmetry. A leaked tenant predicate is one clinic's exposure. A leaked signing key forges every token for every user across every clinic — which is exactly why signing keys are rotated via kid (publish the new key, sign new tokens with it, retire the old kid once its tokens expire) and never hardcoded. And RLS converts the tenancy threat from "every single query is a potential breach if someone forgets a clause" into "the policy is the one audited control point." The whole game is shrinking the set of things that, if they go wrong, go catastrophically wrong — and then guarding that small set ferociously.

RLS overhead is negligible; RLS misconfiguration is not. current_setting adds essentially nothing per query. But a pool that leaks tenant context (§6) can silently cross clinics — the cost isn't CPU, it's correctness, and in a PHI system that's a reportable breach. Get the SET LOCAL/checkout-reset discipline right and RLS is nearly free insurance.


9. Interview lens & exercises​

Interview questions​

"Someone stole a valid JWT. How do you revoke it before it expires?"

  • Junior answer: "Delete it from the database." (Reveals the misconception — a stateless JWT isn't in a database; there's nothing to delete.)
  • Senior answer: names the core stateless-JWT tradeoff out loud — "you can't truly revoke a self-contained token mid-life; you bound the damage instead" — then reaches for the real toolkit: short access TTL so the window is minutes; a revocable refresh family you can kill; a deny-list keyed on jti for the rare must-revoke-now case; and signing-key rotation as the nuclear option. Quantifies the exposure window and explains why each lever exists.

"A user changed the ID in the URL and saw another patient's chart. What failed, and how do you prevent the whole class of bug?"

  • Junior: "Make the IDs UUIDs so they can't guess them."
  • Senior: identifies it as BOLA/IDOR, distinct from role checks (ring 2 passed; ring 3 was missing), names it as a reportable HIPAA breach, and prescribes a centralized object-level authorization layer plus tests that prove the exploit 404s — not a one-off patch on one route. Notes UUIDs are defense-in-depth, never the control.

"Design multi-tenant isolation for a healthcare SaaS. Would you trust app-layer WHERE tenant_id?"

  • Junior: "Yes, just add the clause everywhere."
  • Senior: explains that one forgotten clause is a cross-clinic PHI breach and correctness can't depend on memory; weighs RLS vs schema-per-tenant vs app-scoping; lands on defense-in-depth (RLS + app scoping); and proactively raises the connection-pool footgun and SET LOCAL as the fix. Reverses toward DB-per-tenant for regulated health-system tenants.

"Why Authorization Code + PKCE instead of Implicit for an SPA?"

  • Junior: "Implicit is simpler — fewer round trips."
  • Senior: explains the code-interception threat and why returning tokens directly in a redirect URL is unsafe (history, referer, logs); describes PKCE's verifier/challenge defeating interception; and names the roles of state (login CSRF) and nonce (id_token replay). Notes Implicit is deprecated.

"RBAC vs ABAC vs ReBAC — pick one for 'a provider shares a patient's chart with three specific specialists.'"

  • Junior: "Add a shared role" (and then watches roles explode).
  • Senior: recognizes this as a relationship problem (ReBAC / Zanzibar tuples), explains why RBAC explodes (the permission is per-patient-per-relationship, not per-role), and notes the pragmatic middle: RBAC for coarse access + a care-team/ownership predicate, escalating to full ReBAC only when clinical sharing becomes central.

Exercises & the Pulsely increment​

Do these as real code against a real (or dev) IdP. The goal is a system you'd trust with a stranger's medical record.

  1. Pulsely OIDC login. Wire Authorization Code + PKCE against a dev IdP (Keycloak in Docker, or Auth0/Cognito). Generate code_verifier/code_challenge, state, and nonce; on callback, verify state, exchange the code, and fully verify the id_token (signature via JWKS, iss, aud, nonce, exp). Establish a BFF session cookie (HttpOnly, Secure, SameSite, __Host-). Confirm no token ever reaches browser JS.

  2. Rotating refresh + reuse detection. Implement single-use refresh tokens with family/lineage tracking, stored hashed. Then write the test that proves the security property: use a refresh token, then replay the now-rotated token, and assert the entire family is revoked and both the attacker and victim sessions die. If that test doesn't exist, you don't have reuse detection — you have a comment claiming you do.

  3. Kill an IDOR for real. Add a deliberately vulnerable GET /encounters/:id that returns any encounter. Write an exploit test where patient A reads patient B's chart (it should pass against the vulnerable version — make the breach real). Then introduce the centralized object-level authorize() guard and prove the same exploit now returns 404. Keep the exploit test forever as a regression guard. Bonus: add a break-glass path that grants emergency access only with a typed justification and emits an audit event.

  4. RLS multi-tenancy with two walls. Enable Postgres RLS on patients and encounters. Set tenant_id from the verified token via request context (AsyncLocalStorage) and SET LOCAL. Write a test proving clinic A cannot read clinic B — and a second test where the repository deliberately omits its WHERE tenant_id and the RLS policy still blocks the cross-clinic read. That second test is the whole point: it proves the guarantee survives a developer's mistake.


Key takeaways​

  • AuthN and AuthZ are two jobs. Authentication produces a verified principal; authorization produces a permit/deny ruling on a specific resource. Most catastrophic bugs come from doing one flawlessly and forgetting the other — and here a forgotten object check is a reportable HIPAA breach.
  • Three rings: authenticate → coarse role/scope check → object/tenant/care-team check. The third ring is the one everyone forgets, and its absence is IDOR/BOLA — invisible to role-based thinking and OWASP's #1 API risk. Layer minimum-necessary and break-glass on top.
  • A token is a claim, not a truth. Verify it (signature, pinned alg, iss, aud, exp) and cross-check live state (revocation, clinic membership) before trusting it. Pin the algorithm or eat alg:none and RS/HS confusion forgeries.
  • Stateless JWTs can't be revoked mid-life; sessions can't scale stateless. The hybrid — short JWT access + opaque, revocable, single-use rotating refresh tokens with reuse detection — gets both, and reuse detection is how you catch token theft no other mechanism sees.
  • Delegate authentication via OIDC (Authorization Code + PKCE; state for CSRF, nonce for replay; id_token = identity, access_token = API access). Don't store passwords if you don't have to.
  • Multi-tenancy is an ambient mandatory predicate, not a convention. Take tenant_id from the verified token, enforce it at the data layer with Postgres RLS, and scope it in the app — two walls, because correctness can't depend on remembering a WHERE clause when the stakes are one clinic reading another's PHI.
  • Centralize the authorization decision behind one guard so the object-level check is structurally impossible to skip; never reuse end-user tokens for service-to-service hops (confused deputy — use mTLS or client-credentials).

← Previous: Ch 31 — Security & Cryptography Engineering · Up: Part VI overview · Master TOC · Next: Ch 33 — Reliability Engineering →