Chapter 31 — Security & Cryptography Engineering Fundamentals
Part VI · Security, Reliability & Observability | Prerequisites: Ch 6, Ch 10–Ch 12 | Builds: Pulsely threat-modeled, secrets managed, PHI encrypted at rest
For thirty chapters you have been building the membrane — the trust boundary where untrusted claims become rulings you stand behind. This chapter turns and faces the people on the other side of it: the ones who want to push a bad claim through and have it honored as truth. Security is not a feature you bolt on after the feature works. It is the discipline of running the membrane correctly when the input is not merely sloppy but actively hostile. And cryptography is the small box of mathematical tools that lets you make hard guarantees — this came from who it says, was not altered, cannot be read by the wrong party — across a network you do not control and a database that may someday be stolen. In healthcare those guarantees have teeth: the data behind the membrane is a patient's chart, and a claim let through as truth can leak a diagnosis, misroute a prescription, or expose someone's HIV status to a stranger.
This is a concept-dense, primitive-focused chapter. We are not building the login flow here — that is Chapter 32, and it sits on top of the crypto you are about to learn. Our job is narrower and deeper: make you fluent in the four cryptographic verbs, never confuse them again, and operationally protect Pulsely's secrets, PHI, and integrations without ever inventing your own crypto. Get the primitives right and most breaches become impossible by construction. Get them confused and no amount of careful application code will save you.
1. The problem: defenders must be perfect; attackers need one mistake
It is 2 a.m. A Pulsely support engineer pastes a patient dump into a Slack channel to debug a scheduling complaint — full names, dates of birth, MRNs, home addresses, phone numbers, and the diagnosis codes on their last encounter, all in plaintext, because that is how they sit in the database. That alone is a reportable HIPAA breach — protected health information (PHI) disclosed to an unauthorized channel, notifiable to the patients and to HHS. But it gets worse on inspection: the .env file that seeded the production config was committed to the repository eight months ago "just to unblock a teammate," and the read-replica credential inside it — a live key to the chart database — still works. Anyone who cloned the repo in the last eight months — every contractor, every laid-off engineer, every fork — holds a live key to patient data. Nothing was "hacked." Every door was simply left unlocked, and someone finally noticed.
Walk the failures, because each is a category error, not a clever exploit:
- The dump was plaintext because nobody decided which columns were PHI and encrypted them. Confidentiality was never engineered; it was assumed.
- The credential leaked via git because secrets lived in the artifact instead of being referenced by it. And deleting the commit does nothing — git history is forever, and you must assume anything ever committed is compromised. The only fix is rotation.
- The credential still worked because nobody rotated it on a schedule, so a leak from eight months ago is indistinguishable from a leak today.
Now layer the fallacy that lets teams sleep through this: "it's behind a VPC, we're fine." A single network perimeter is one wall, and walls have doors. Suppose Pulsely's document-import fetcher accepts a user-supplied URL — "import this insurance card or referral document from this link." An attacker submits http://169.254.169.254/latest/meta-data/iam/security-credentials/, the cloud metadata endpoint. Your server, sitting inside the trusted VPC, dutifully fetches it and hands the attacker temporary IAM credentials for the whole instance role.
In plain terms: every cloud server has a special internal-only URL — that
169.254.xaddress — that hands out the server's own login credentials to anything that asks from inside the machine. It's how the server proves its identity to the cloud (so your code can read from S3 without a hard-coded password). If your code can be tricked into fetching an attacker-chosen URL, it can be tricked into fetching that one and leaking the keys to your whole AWS account — including the KMS keys guarding every patient's chart.
That is SSRF (server-side request forgery), and it walked straight past the perimeter because the request originated inside it. One wall is not a strategy. Defense in depth — many independent layers, each assuming the others may fail — is.
There is a deeper asymmetry here that you must internalize before any technique makes sense. The defender must close every hole; the attacker needs to find one. You can write ten thousand perfect lines and one logged secret, one string-concatenated SQL query, one == token comparison undoes all of them. Security is therefore a property of the weakest path through your system, never the average quality of your code. This is the same weakest-link shape you already know: a chain is as strong as its weakest link, and an attacker spends all their time finding that link.
🚫 A framing this book rejects. "Security is the security team's job; I write features." In a backend, every endpoint you write is a door in the trust boundary, reachable by everyone on the internet including people who wish you harm. You cannot delegate the correctness of your own doors. The security team sets policy and builds tooling; whether your query is parameterized, your secret is referenced rather than committed, and your chart-read checks the caller may see this patient is, irreducibly, yours.
None of this means chasing perfection. Security is risk engineering under a budget: you raise the attacker's cost-to-exploit above the value they'd extract, spending your finite build-time where it buys the most risk reduction. Encrypting a patient's SSN and diagnosis is worth it; encrypting the public provider-directory listing (Dr. Rao, Cardiology) is not. The skill is not absolutism — it is knowing which holes are load-bearing.
2. The mental model: trust boundaries, four verbs, and a key hierarchy
Three pictures carry this chapter. Hold all three.
Trust boundaries are the primary object
A trust boundary is any line where data crosses from "I control this" to "I do not." Draw them explicitly, because every crossing is a checkpoint that demands four decisions — authenticate (who is this?), authorize (may they, and may they see this specific record?), validate (is the input well-formed and safe?), and encrypt (should this be private/tamper-evident in flight?). Pulsely's boundaries:
client ──①──▶ API gateway ──②──▶ service ──③──▶ database
(patient │ (+ KMS)
portal, ④
provider app, ▼
partner) 3rd-party APIs
(clearinghouse, labs,
eligibility, e-Rx)
- ① client → API — the original, most hostile boundary. Everything here is a claim (the membrane). Taint everything until validated.
- ② gateway → service and ③ service → DB — internal boundaries people forget. A compromised service, or an SSRF'd one, is now an attacker inside. This is why service-to-service identity (mTLS) and least-privilege DB credentials exist.
- ④ service → 3rd party — outbound trust. When you submit a claim to the clearinghouse, are you really talking to the clearinghouse (TLS cert)? When a lab calls your result webhook, is it really them (signature)?
🧭 Mental model. Security is just the membrane's question — "did we actually run the membrane, or did we let a claim through as if it were truth?" — asked at every boundary, not only the front door. The 2 a.m. dump, the SSRF, the leaked credential are all the same failure: a boundary that was assumed safe instead of made safe.
Authorization in healthcare is more than a yes/no at the door. Two extra invariants ride on every PHI boundary, and you should meet them now even though the mechanics land in Chapter 32:
- Minimum-necessary access. HIPAA requires that each caller sees only the PHI they need for their job — not the whole chart. A biller reconciling a claim needs the diagnosis code and the charge, not the psychotherapy note; a patient on the portal sees only their own record; a provider sees the panel they treat. These are scopes, and "authenticated" is nowhere near "authorized to read this field of this patient."
- Tenant isolation per clinic. Pulsely is multi-tenant: many independent clinics share one database. Clinic A must never read Clinic B's patients — a single missed
WHERE clinic_id = $1is a cross-tenant PHI leak. The strong enforcement is row-level security (RLS) — the database itself filters every query to the caller's tenant rows, so a forgotten clause in application code can't leak across clinics. - Break-glass. Emergencies don't respect scopes: an ER physician may need a chart they have no normal relationship to. So access is not simply denied — it is granted under break-glass: the provider must supply a written justification, the access is flagged, and it writes an immutable record ("Dr. Lee viewed patient 8842's chart via break-glass at 02:14, reason: 'unconscious ED admit'") that compliance reviews after the fact. Deny-by-default would be unsafe; audit-heavy allow is the healthcare answer.
The CIA triad, mapped to primitives
Three properties name what "secure" even means, and each maps to a tool:
- Confidentiality (only the intended party can read it) → encryption.
- Integrity (it was not altered; it is from who it claims) → hashing, MACs, signatures.
- Availability (it is there when needed) → rate limits, quotas, the resilience patterns of the next two chapters.
Authentication and authorization sit orthogonally — they answer "who are you?" and "may you?" and are built in Chapter 32 on top of these primitives.
The four verbs you must never blur
This is the single most valuable table in the chapter. Most catastrophic crypto bugs are one of these used where another was needed.
| Verb | Goal | Reversible? | Needs a key? | Use it for |
|---|---|---|---|---|
| Encode | make data transportable | yes, by anyone | no | base64 in a URL, hex in a header — never security |
| Hash | one-way fingerprint | no | no | password storage (with a KDF), integrity checks, dedup |
| MAC / Sign | prove authenticity + integrity | n/a | yes | webhook signatures, JWT integrity, API request signing |
| Encrypt | hide content | yes, with the key | yes | PHI at rest, secrets, message bodies |
The decision tree that generates this table:
┌─ Do you need the data back?
│
yes ─┤── Is there a secret/key involved?
│ yes ──▶ ENCRYPT (confidential, reversible with key)
│ no ──▶ ENCODE (transport only — NOT security)
│
no ──┤── Who must be able to verify it?
anyone ──▶ HASH (fingerprint, no key)
keyed parties ──▶ MAC / SIGN (authenticity, needs key)
🔑 The non-confusion invariant. Encoding is not encryption (base64 protects nothing). Hashing is not encryption (you cannot get the data back — that is the point). A MAC proves a message was not tampered with but does not hide it. Storing a password "encrypted" is wrong (it should be hashed with a KDF); calling a base64 cookie "encrypted" is wrong (it is plaintext anyone can decode); a JWT is signed, not encrypted (its payload is readable by anyone). If you can name which verb a task needs, you have prevented the majority of crypto incidents.
Keys form a hierarchy
You do not secure a million rows by re-securing every byte. You secure a small, rotatable key, and let it protect the data. This is the key hierarchy, and it underpins all key management:
Root key (HSM / KMS, never leaves)
│ protects
▼
KEK (Key-Encrypting Key, in KMS)
│ encrypts
▼
DEK (Data-Encrypting Key, used in your app's memory)
│ encrypts
▼
the actual data (PHI columns, note bodies)
Protect the top, rotate at the level that fits, and you never have to touch the data to change your security posture. We make this concrete in §4 (envelope encryption).
🧭 The attacker is a user with different goals. Every input field, header, cookie, query param, and inbound webhook is attacker-controlled until you have validated it. The mental discipline is taint-until-validated: data arriving from across a boundary is "tainted," and may not influence durable state, a query, an outbound request, or a privilege decision until it has passed an explicit check that removes the taint.
3. Theory & invariants: STRIDE, KDFs, AEAD, and the difference between signing and MAC
A mental model tells you where to look. Invariants tell you what must hold no matter what. These are load-bearing.
STRIDE: a generative checklist for threats
You will not out-imagine attackers by brainstorming. STRIDE is a checklist you run against every element and data flow on your trust-boundary map; each letter names a threat class and points at its mitigation:
| Letter | Threat | "An attacker…" | Mitigation class |
|---|---|---|---|
| S | Spoofing | …pretends to be someone else | authentication (Ch 32) |
| T | Tampering | …modifies data in flight or at rest | integrity: MAC, signatures, hashes; TLS |
| R | Repudiation | …denies doing it; you can't prove they did | audit logs, signed records |
| I | Information disclosure | …reads what they shouldn't | encryption, access control |
| D | Denial of service | …exhausts a resource | rate limits, quotas, load shedding |
| E | Elevation of privilege | …gains rights they shouldn't have | authorization, least privilege |
The value is coverage: walk each boundary crossing, ask all six questions, and you systematically surface threats your intuition skips. In healthcare, R (repudiation) is not a footnote — the immutable audit log that records who viewed which chart is a HIPAA requirement in its own right (the observability chapter builds it), and I (information disclosure) is a reportable breach, not a bug ticket. We apply STRIDE to Pulsely in §5's increment.
Hashing invariants — and why fast hashes are wrong for passwords
A cryptographic hash is deterministic (same input → same output), fixed-length, and resistant in three ways: preimage (given a hash, you can't find an input), second-preimage (given an input, you can't find another with the same hash), and collision (you can't find any two inputs that collide). SHA-256 and SHA-3 satisfy all of this — and are exactly the wrong tool for passwords.
Why? Because SHA-256 is designed to be fast — billions of hashes per second on a GPU. That speed serves you for integrity checks and helps the attacker for passwords: if your provider-login table leaks, a fast hash lets them try billions of password guesses per second against it. The defense is a hash deliberately made slow and expensive.
🔑 Passwords need a KDF, not a hash. A password is stored using a key derivation function with a tunable work factor, a unique random salt per password (so identical passwords get different stored values and precomputed "rainbow tables" are useless), and optionally a pepper (a secret kept outside the database, so a DB-only leak still can't be cracked). The three you should know:
- bcrypt — cost factor (e.g. 12); battle-tested; gotcha: it silently truncates input to 72 bytes, so very long passwords lose entropy.
- scrypt — memory-hard (deliberately needs lots of RAM to run, not just fast math — so an attacker can't just throw more, cheaper cores at it; its
N/r/pparameters tune that memory/time cost). Resists GPU/ASIC cracking (ASIC = a custom brute-forcing chip built for one task) by demanding RAM, not just compute.- Argon2id — the current default; tunable on memory, time, and parallelism; resists both GPU cracking and side-channel attacks (leaking secrets by measuring timing or power draw rather than breaking the math). Reach for this unless you have a reason not to.
The invariant across all three: tunable work factor + unique salt + algorithm parameters stored alongside the hash (so you can raise the cost later and migrate gradually).
Symmetric vs asymmetric encryption — and always use AEAD
Symmetric crypto uses one shared key to encrypt and decrypt. It is fast, and the modern choices are AES-GCM and ChaCha20-Poly1305. Both are AEAD — Authenticated Encryption with Associated Data — meaning they give you confidentiality and integrity in one operation: the ciphertext carries an authentication tag (a short cryptographic checksum) that detects any tampering on decrypt. Use AEAD always; "encryption without integrity" lets an attacker flip bits in your ciphertext undetected.
Asymmetric crypto uses a keypair: a public key anyone can hold and a private key you guard. It is slow, so it is used not for bulk data but for two jobs: key exchange (agree on a symmetric session key over an open channel) and signatures (RSA, ECDSA, Ed25519). This is exactly the TLS handshake you already met: asymmetric crypto establishes a shared symmetric key, then symmetric crypto encrypts the bulk traffic — because asymmetric is too slow for every byte.
🔑 The two hard rules of symmetric encryption. (1) Never roll your own mode — use a vetted AEAD construction; "I'll just XOR with a key" or "AES-ECB" are how you end up with the famous penguin still visible through your "encryption." (2) Nonce/IV uniqueness is non-negotiable.
In plain terms: GCM turns your key + nonce into a one-time pad — a stream of random-looking bytes it XORs over your data to hide it. Reuse the same nonce under the same key and you reuse the same pad twice; anyone holding both encrypted messages can cancel the pad out and read the difference between your two plaintexts, and can forge valid authentication tags. A nonce is not a secret, but it must never repeat.
A React-flavored way to feel it: treat the nonce like a React
key. Reuse a key across two list items and React quietly conflates them into one — a visible bug. Reuse a nonce and GCM quietly conflates two encryptions the same way, except the failure isn't a flickering UI, it's a silent breach of two patients' encrypted records. Generate the nonce from a CSPRNG (or a counter at very high volume), never fromMath.random.
Signing vs MAC: who is allowed to produce valid messages?
Both prove integrity and authenticity. The difference is who can create a valid one:
- HMAC (hash-based MAC) uses a shared secret. Both parties hold it, so either party can produce a valid MAC. Great when sender and verifier are the same trust domain (you sign your own webhooks and verify your own JWTs). It is symmetric and fast.
- Digital signature uses a private key to sign, public key to verify. Only the holder of the private key can sign; anyone can verify. This gives non-repudiation — the signer cannot deny it, because no one else could have produced it.
🔑 Choose by the question "should the verifier also be able to forge?" If the verifier is you (you both sign and check), HMAC is simpler and faster. If the verifier must be unable to mint valid messages — e.g. a third party verifying your signature, or you verifying theirs — you need asymmetric signatures. Using HMAC where you needed non-repudiation means anyone who can verify can also forge.
TLS/PKI, recapped and made operational
Earlier you built the TLS handshake byte by byte; here is the security-engineering distillation. A server presents a certificate — its public key, signed by a Certificate Authority whose root your client already trusts. The client verifies the chain up to a trusted root and that the certificate's name matches the hostname it dialed. Then asymmetric key exchange establishes a symmetric session key, and bulk traffic is symmetric AEAD.
🛑 What we deliberately did not re-explain. The byte-level handshake, cipher-suite negotiation, and session resumption are Chapter 6's territory; we built on them, not over them. We are also not building authentication, sessions, JWT validation, OAuth, RBAC, or IDOR defenses here — those are Chapter 32, which consumes the primitives (HMAC, signatures, constant-time compare, KDFs) you are learning now. This chapter owns the crypto; the next owns identity.
🛑
rejectUnauthorized: falsedefeats the entire point of TLS. Disabling certificate verification (the Node flag,curl -k, "trust all certs") means you encrypt a channel to whoever answered — including a machine-in-the-middle who terminated your connection. Encryption without authentication of the peer is theater. The only legitimate use is a pinned self-signed cert in a closed system, where you verify against a specific known certificate, not "anyone." For service-to-service identity inside your own network — Pulsely's API talking to its claims worker — the strong answer is mTLS — both sides present and verify certificates, so each end cryptographically proves who it is.
📎 Borrowed on credit: encoding is not security. base64, hex, and URL-encoding are reversible by anyone — they exist to make bytes transportable over text channels, nothing more. The fact that a token "looks encrypted" (a long base64 blob) tells you nothing about whether it is confidential. A JWT is three base64url segments; its payload is plain reading for anyone. We use this fact constructively in Chapter 32 — never put PHI or secrets in a JWT payload — but the principle is a §2 verb: encoding has no key, so it has no security.
4. Under the hood: the Node crypto toolbox, correctly used
Theory becomes safe only when wired correctly. Node's crypto module (and a couple of well-chosen libraries) give you everything; the danger is in the details. Every snippet below is minimal-but-correct.
Randomness: CSPRNG, never Math.random. Security-relevant random values — salts, nonces, tokens, keys — must come from a cryptographically secure generator. Math.random() is predictable and seedable; an attacker who sees a few outputs can predict the rest.
import { randomBytes } from 'node:crypto';
const token = randomBytes(32).toString('base64url'); // 256 bits of CSPRNG entropy — a real secret
// const bad = Math.random().toString(36); // predictable; NEVER for anything security-relevant
Constant-time comparison: the timing-attack defense. Comparing two secrets with === (or any short-circuiting comparison) leaks timing — it returns faster when the first byte differs, and an attacker can recover a secret byte-by-byte by measuring response time. Always compare secrets, MACs, and tokens with timingSafeEqual on equal-length buffers.
import { timingSafeEqual } from 'node:crypto';
function safeEqual(a: Buffer, b: Buffer): boolean {
if (a.length !== b.length) return false; // length itself can leak; hash first if lengths vary
return timingSafeEqual(a, b); // compares in time independent of where they differ
}
Password hashing with Argon2id. Use the argon2 library (argon2id is the default variant). It embeds the algorithm, parameters, and salt inside the output string — so verification needs no separate parameter storage, and you can raise the cost later and rehash transparently on next login.
import argon2 from 'argon2';
const OPTS = { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 };
async function hashPassword(plain: string): Promise<string> {
return argon2.hash(plain, OPTS); // output embeds algo+params+salt, e.g. "$argon2id$v=19$m=19456,t=2,p=1$..."
}
async function verifyPassword(stored: string, plain: string): Promise<boolean> {
const ok = await argon2.verify(stored, plain); // constant-time inside the library
if (ok && argon2.needsRehash(stored, OPTS)) { // cost was bumped since this hash was made →
/* recompute and persist a stronger hash now that we have the plaintext */
}
return ok;
}
That needsRehash-on-login pattern is algorithm agility: you store the cost with the hash, so you can strengthen it over time without forcing a password reset.
🏭 Skippable JVM aside — the transferable idea only. Spring Security does the same thing with
DelegatingPasswordEncoder: a{bcrypt}/{argon2}prefix on the stored hash records which encoder made it, so old and new hashes coexist and migrate on login. You don't need the Java vocabulary — the payoff is the portable rule: store the algorithm alongside the hash so you can migrate later. Node just makes you reach for it by hand.
AEAD encryption with AES-256-GCM. Note the explicit, fresh IV per message and the separately stored auth tag — both are mandatory.
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
function encrypt(plaintext: Buffer, dek: Buffer) {
const iv = randomBytes(12); // 96-bit nonce — UNIQUE per encryption under this key
const cipher = createCipheriv('aes-256-gcm', dek, iv);
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const authTag = cipher.getAuthTag(); // integrity tag — store it; decrypt fails without it
return { ciphertext, iv, authTag };
}
function decrypt(ciphertext: Buffer, dek: Buffer, iv: Buffer, authTag: Buffer): Buffer {
const decipher = createDecipheriv('aes-256-gcm', dek, iv);
decipher.setAuthTag(authTag); // tampering → final() throws; never returns altered data
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
}
Envelope encryption for a PHI column, end to end
This is the production pattern for encrypting PHI at rest and the reason the key hierarchy from §2 exists. You do not call KMS to encrypt every patient SSN — KMS is rate-limited and slow. Instead: generate a random DEK locally, encrypt the field with it (fast, in-process), then ask KMS to encrypt the tiny DEK with the never-leaving KEK, and store the encrypted DEK next to the ciphertext.
ENCRYPT a PHI field:
1. DEK = randomBytes(32) // fresh data key, in memory only
2. {ciphertext, iv, authTag} = AES-256-GCM(field, DEK)
3. encryptedDek = KMS.Encrypt(KEK, DEK) // KMS wraps the small key
4. store row: { ciphertext, iv, authTag, encryptedDek, keyVersion }
5. zero out DEK in memory
DECRYPT:
1. DEK = KMS.Decrypt(encryptedDek) // one KMS call (cache the result briefly)
2. field = AES-256-GCM-decrypt(ciphertext, DEK, iv, authTag)
async function encryptPhi(field: string, kms: Kms, keyVersion: string) {
const dek = randomBytes(32);
const { ciphertext, iv, authTag } = encrypt(Buffer.from(field, 'utf8'), dek);
const encryptedDek = await kms.encrypt(dek, keyVersion); // KMS holds the KEK; the DEK never leaves un-wrapped
dek.fill(0); // best-effort scrub
return { ciphertext, iv, authTag, encryptedDek, keyVersion };
}
The keyVersion column is what makes rotation possible without re-encrypting the whole chart table at once: new writes use the new KEK version; old rows decrypt with their recorded version until a background job lazily re-wraps them. And it enables the retention/erasure superpower we discuss in §5: crypto-shredding — destroy the DEK (or the KEK version) and the ciphertext is permanently unrecoverable without ever touching the rows.
Webhook signing internals (the primitive Ch 12 deferred here)
Chapter 12 introduced webhooks as an integration pattern and explicitly deferred the signing crypto to this chapter. Here it is. When Pulsely sends an outbound event to a partner — a "result ready" or "claim status changed" notification — the receiver must verify (a) it really came from Pulsely and (b) it was not altered or replayed. The same verification runs in reverse when Pulsely is the receiver of an inbound callback: a lab posting an HL7/FHIR result, a clearinghouse posting an 835 remit, an eligibility 271, or an e-Rx acknowledgement.
The recipe: HMAC-SHA256 over timestamp + "." + rawBody, with a shared secret, transmitted in headers — and crucially, sign the raw body bytes, not the parsed-then-reserialized JSON, because re-serialization changes whitespace/key-order and breaks the signature.
import { createHmac, timingSafeEqual } from 'node:crypto';
// SENDER (Pulsely → partner)
function signWebhook(rawBody: Buffer, secret: string) {
const timestamp = Math.floor(Date.now() / 1000).toString();
const sig = createHmac('sha256', secret)
.update(`${timestamp}.`).update(rawBody) // sign timestamp + raw bytes — never JSON.stringify again
.digest('hex');
return { 'X-Pulsely-Timestamp': timestamp, 'X-Pulsely-Signature': `v1=${sig}` };
}
// RECEIVER — verify with constant-time compare AND a replay window
function verifyWebhook(rawBody: Buffer, headers: Record<string,string>, secret: string): boolean {
const ts = Number(headers['x-pulsely-timestamp']);
if (Math.abs(Date.now()/1000 - ts) > 300) return false; // reject if outside a ±5-min window (skew both ways) → blocks replay
const expected = createHmac('sha256', secret)
.update(`${ts}.`).update(rawBody).digest();
const given = Buffer.from((headers['x-pulsely-signature'] ?? '').replace(/^v1=/, ''), 'hex');
return given.length === expected.length && timingSafeEqual(given, expected); // constant-time
}
The timestamp + skew window is the replay defense: a captured-and-resent request is rejected once it ages out, so an attacker can't replay a valid "result ready" or "claim paid" event tomorrow to trigger a duplicate action.
🏭 The JWT-verification break, mechanically. Two famous attacks live in this same crypto family and are worth understanding now (Chapter 32 builds JWT auth on the fix). First,
alg: none— a JWT header can claim "no signature," and a naive verifier honors it, accepting an unsigned, attacker-written token that says"role":"provider".Second, algorithm confusion (RS256 → HS256). Take it in two beats:
- Normal path. The server uses RS256 (asymmetric): it verifies with the public key. That's safe to publish, because only the matching private key can produce a valid signature — the public key can only check, never sign.
- The attack. The attacker flips the token header to
alg: HS256— the shared-secret (symmetric) mode — and signs the token using that public key as the HMAC shared secret. HS256 verification just asks "was this signed with the secret?" The server, trying to be helpful, uses its public key as that secret — and the attacker did sign with exactly that value, so the check passes. The server handed the attacker the key by publishing it.Both are the same root cause: trusting the attacker to tell you which algorithm to use. The fix is a strict server-side allow-list of algorithms, never reading
algas an instruction. This is the §2 invariant in action — a signature you didn't actually verify is just encoding.
5. In production: secrets, KMS, OWASP, PHI governance, and the Pulsely increment
Primitives are necessary; operating them is where breaches actually happen. Here is the production playbook, ending in Pulsely's concrete increment.
Secrets management: stop committing .env
The 2 a.m. incident began with a secret in git. The production posture:
- Reference, don't embed. Secrets live in a secret store — AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager, or SSM Parameter Store — and are injected at boot (or via a sidecar) into the process environment or fetched at startup. The repo and the built image contain references, never values.
- Prefer short-lived dynamic credentials over static ones. Vault and cloud IAM can mint a database credential that expires in an hour; a leaked one-hour credential is a far smaller incident than a static password that works forever.
- Rotate with dual-version overlap. Rotation must not cause downtime: publish the new secret, let both old and new be valid for an overlap window while consumers pick up the new one, then retire the old. Rotation is also your leak response.
- Scan before and after commit. Run
gitleaks/trufflehogas a pre-commit hook and in CI, so a secret is caught before it ever lands. And the critical operational rule:
🔑 After a leak, rotate — do not just delete the commit. git history is permanent and distributed; once a secret is pushed, assume the entire internet has it. Deleting the commit hides it from
HEADand nothing else. The only correct response is to rotate the secret immediately and treat anything it protected as potentially compromised. The eight-month-old.envcredential was a live incident the moment it was committed, not the moment it was noticed.
KMS in practice
Envelope encryption (§4) exists precisely so KMS does not become a bottleneck: the DEK never leaves KMS un-wrapped, but it also never has to — you wrap/unwrap a tiny key, not the data. Key practices:
- Version your keys (
keyVersioncolumn) so rotation re-wraps lazily instead of re-encrypting everything at once. - Least-privilege IAM: only the services that need
Decryptget it, and everyDecryptcall is audit-logged — a spike in decryptions of chart data is a breach signal. - Use HIPAA-eligible KMS under a BAA. In AWS, KMS is a HIPAA-eligible service and must sit under a signed Business Associate Agreement (more on the BAA in the cloud chapter); the same goes for every service that ever touches PHI.
- Plan for KMS being a hard dependency: a KMS regional outage means PHI reads fail. Cache decrypted DEKs in memory for a short TTL (never cache the plaintext PHI), so a transient KMS blip doesn't take down the app — see §8.
OWASP Top 10 for APIs, operationalized
The OWASP Top 10 is a list of the failure modes that actually cause breaches. Operationalized for a backend:
- Injection — never build queries by string concatenation. Use parameterized queries / an ORM so user data can never be parsed as SQL. (This applies to every query language, including the operators of a NoSQL store, not just Postgres.)
- Broken object-level authorization (BOLA/IDOR) —
GET /patients/:id/chartreturning any patient's chart when the caller just increments the id. This is OWASP API #1, the single most common API breach, and in healthcare a broken access check is a reportable HIPAA breach — one clinician (or a stranger with a token) pulling a patient they have no relationship to, one guessed id at a time. The fix lives in Chapter 32 (authorize the caller may see this patient on every object, backed by RLS per clinic), but the crypto-side, defense-in-depth mitigation you own here is unguessable IDs so enumeration is hard — never as a substitute for the authorization check. - SSRF — the metadata-endpoint attack from §1. Defend with an egress allow-list, resolve the URL's IP and block private/link-local ranges (
169.254.0.0/16,10/8,127/8,::1), never let user-supplied URLs hit internal services, and don't follow redirects to re-validate the final host. - Security misconfiguration — default credentials, verbose error stacks leaked to clients, wide-open CORS, missing security headers. Each is a free win for an attacker.
- Supply-chain / dependency risk — see below.
PHI & data governance (HIPAA)
Compliance is mostly knowing where the data is, controlling who reads which part of it, and being able to prove and to destroy it:
- Inventory and classify what is PHI in Pulsely (name, DOB, MRN, SSN, insurance member ID, address, phone, and any diagnosis/medication/result) versus public (the provider-directory entry: name and specialty). You cannot protect what you haven't named.
- Minimum-necessary, enforced as scopes. A biller's queries return billing fields; a patient's portal session returns only their own record; a provider's app is scoped to their panel. Wire these as authorization scopes (Chapter 32) plus RLS so the database refuses cross-scope and cross-clinic reads even if application code forgets a filter.
- Break-glass with mandatory justification. Emergency access is allowed but never silent — the accessor supplies a reason, and the event writes an immutable audit record that compliance reviews. Denying an ER doctor is unsafe; allowing-and-recording is the answer.
- Log every view, not just every write. The immutable, append-only, tamper-evident audit trail of "who viewed which patient's chart, when, and why" is a first-class HIPAA obligation with a long retention window. The observability chapter builds it; here, note that it is required, not optional, and that your crypto (signed/hash-chained records) is what makes it tamper-evident.
- Retention & destruction via crypto-shredding: instead of hunting every copy of a patient's data across replicas, backups, and indexes when a retention window closes or a record must be destroyed, destroy that patient's DEK (or the key version). The ciphertext everywhere becomes permanently unrecoverable. This is the operational payoff of envelope encryption.
- Encryption-at-rest vs in-transit are different controls: in-transit (TLS) protects the wire; at-rest (column/envelope encryption) protects the stored bytes. You need both, and watch where logs leak PHI — a
console.log(req.body)on an intake endpoint quietly writes plaintext PHI into your log store, which is itself a breach.
Supply-chain hygiene
Your dependencies run with your privileges. Lockfiles + integrity hashes pin exact versions; npm audit / Dependabot / Renovate surface known-vulnerable packages; pin base images by digest. Know the typosquat / dependency-confusion attack — a malicious package named like yours (or matching an internal name on the public registry) gets pulled in — and mitigate with scoped/internal registries and explicit registry routing.
Security headers & TLS hygiene
For anything you serve: HSTS (force HTTPS), CSP (for served HTML), Secure / HttpOnly / SameSite cookies (Chapter 32 leans on these), TLS 1.2+ only, and automated cert rotation/renewal so a certificate never silently expires.
The Pulsely increment
This chapter's build, mapped to the threat-boundary diagram:
-
STRIDE threat model of Pulsely's auth, claim-submission, and chart-access flows. A sample of the claim-submission and chart-read table:
Element / flow STRIDE Threat Mitigation Residual risk client → POST /claimsTampering client edits charge_amountre-derive the charge server-side from the encounter + fee schedule (the authority invariant) low client → POST /claimsSpoofing forged identity token auth (Ch 32) deferred to Ch 32 result/remit webhook out T / replay partner replays a "result ready" / "835 paid" event HMAC + timestamp window (§4) low service → DB (PHI) Info disclosure DB/backup theft envelope-encrypted columns DB+KMS joint compromise GET /patients/:id/chartElevation / I read another patient's chart (reportable breach) object-level authz + RLS per clinic (Ch 32) deferred to Ch 32 break-glass chart access Repudiation "I never opened that chart" mandatory justification → immutable audit log low login endpoint DoS credential-stuffing flood rate-limit + separate pool (§8) medium -
Secrets out of the repo into a referenced secret store, injected at boot, with
gitleaksin CI and a written rotation runbook that assumes the old.envleaked. -
PHI encrypted at rest: envelope-encrypt
patients.full_name,patients.dob,patients.ssn,patients.member_id,patients.address,patients.phonewith KMS-backed DEKs, akeyVersioncolumn, a short-lived DEK decrypt-cache, and crypto-shredding wired into record retention/destruction. -
Hardened inputs across scheduling, orders, claims, and patient-search endpoints: parameterized queries, egress allow-list on the document-import fetcher (SSRF), validation at every boundary.
-
Signed outbound webhooks for clinical and claim-status events per §4.
📎 Borrowed on credit: the searchability problem of encrypted PHI. Encrypting
member_idorfull_namemeans you can no longer doWHERE member_id = $1— the ciphertext differs every time (different IV), yet the front desk still needs exact patient lookup by MRN or member ID. Pulsely's fix, sketched here and detailed in Ch 22's indexing terms, is a blind index: store a separate keyed-HMAC of the normalized identifier for equality lookup only, alongside the AEAD ciphertext for reading it back. The HMAC is deterministic (so it's searchable) but reveals nothing about the value. We name the tension here; §7 frames it as a tradeoff.
The ADR: "Secrets management & PHI-encryption approach"
ADR-031 — Secrets management & PHI encryption Status: Accepted Context: Secrets were committed to git; PHI sits plaintext in Postgres; HIPAA retention/destruction is manual and unreliable; multi-tenant clinics share one database. Decision:
- Secret store: AWS Secrets Manager (we are AWS-native and under a BAA; managed rotation; least-ops). Injected at boot via IAM role; nothing secret in repo or image.
- Encryption strategy: envelope encryption (KMS KEK → per-record DEK → AES-256-GCM) on PHI columns, not TDE/full-disk only — our threat model is app/DB-account compromise, which TDE does not cover.
- Per-field handling:
full_name/dob/ssn/member_id/address/phone→ encrypted (must read back) + blind index on MRN and member_id for lookup;password→ Argon2id hashed (never reversible); patient copay card PAN → tokenized via the payment provider (out of our trust boundary entirely).- Tenant isolation & minimum-necessary: RLS per clinic plus role scopes (patient / provider / biller) enforced in the database, so a missed application-code filter can't leak across clinics or scopes.
- Rotation: KEK rotated annually + on suspected compromise, with
keyVersionoverlap and lazy re-wrap; secrets rotated quarterly with dual-version overlap.- Blast-radius containment: least-privilege IAM per service; every KMS
Decryptaudited; crypto-shredding (drop the DEK) implements retention-window destruction. Consequences: KMS becomes a hot dependency (mitigated by DEK caching, §8); encrypted columns lose native indexing (mitigated by blind index); rotation introduces a multi-version decrypt window we must keep open until re-wrap completes.
6. Common pitfalls
Each is signature → fix — the symptom you'll observe, then the principle that resolves it.
Plaintext or fast-hashed passwords. Signature: identical passwords produce identical stored values; a leaked table is cracked in hours on a GPU because it's SHA-256. Fix: Argon2id (or bcrypt/scrypt) with a unique per-user salt and a tuned cost factor. The work factor is the whole point — make each guess expensive.
== comparison of tokens or MACs.
Signature: auth feels flaky under load; a determined attacker recovers a secret by measuring response timing.
Fix: crypto.timingSafeEqual on equal-length buffers, every time you compare a secret.
AES-GCM nonce/IV reuse (or an IV from Math.random).
Signature: two ciphertexts that XOR to reveal plaintext; forged auth tags accepted.
Fix: a unique CSPRNG nonce per encryption under a given key; a counter at very high volume. Never repeat a nonce.
A "base64-encrypted" cookie / a JWT trusted without verifying the signature.
Signature: an attacker base64-decodes the cookie, edits "role":"provider", re-encodes, and is now staff.
Fix: encoding is not encryption — encrypt or sign. For JWTs, verify the signature, pin alg to an allow-list, reject none. (Built in Ch 32.)
SSRF via a URL/document fetcher.
Signature: an outbound request to 169.254.169.254 (or an internal host) appears in egress logs.
Fix: egress allow-list; resolve the host's IP and block private/link-local ranges; reject redirects to internal hosts; never let user URLs reach internal services.
Signing the parsed JSON body instead of the raw bytes (webhooks). Signature: signature verification fails intermittently after the body is re-serialized with different whitespace/key order. Fix: capture and sign the raw request buffer; verify against the same raw bytes.
Secrets or PHI in logs, error stacks, or APM payloads.
Signature: a token or credential is grep-able in your log store; req.body of an intake endpoint is logged in full, writing patient data to plaintext logs.
Fix: redaction middleware with a structured-logging allow-list of safe fields; never log request bodies for auth/PHI endpoints. (The observability chapter builds structured logging.)
Trusting the perimeter (rejectUnauthorized: false, "it's in the VPC").
Signature: TLS "works" but to anyone who answers; an internal service trusts any caller inside the network.
Fix: verify certificates always; use mTLS for service-to-service identity; treat internal boundaries as boundaries.
7. Tradeoffs
Senior engineering names the spectrum and says why it stands where it stands.
Encrypt vs hash vs tokenize PHI. Hash when you only need equality/lookup and never need the value back (but plain hashing of low-entropy PHI like a member ID is crackable — hence a keyed blind index). Encrypt when you must read the value back (name for a chart header, address for correspondence, DOB for identity matching). Tokenize to remove the data from your trust boundary entirely — a provider's vault holds the real value and you hold an opaque token (the right call for a patient's copay card number). You reverse toward deterministic encryption or a blind index when query patterns (exact patient lookup by MRN) force searchability onto encrypted data.
Column-level encryption vs full-disk/TDE only. TDE (transparent disk encryption) is cheap and invisible but protects only against a stolen disk — a compromised app or DB account reads plaintext straight through it. Column encryption shrinks the blast radius to "attacker also needs KMS access," but it kills native indexing/joins on those columns and adds KMS latency. You reverse toward TDE-only when your threat model is genuinely physical-theft, not application compromise.
KDF cost tuning. A higher Argon2 cost is stronger but adds login latency and creates a DoS vector — an expensive auth endpoint is a lever an attacker pulls. Tune to roughly 100–250 ms per verification and rate-limit login so the cost can't be weaponized.
Pepper vs no pepper. A pepper (app-side secret added before hashing) means a DB-only leak can't be cracked — but if the app secret leaks with the DB, it adds nothing, and it complicates rotation (changing the pepper invalidates every hash). Worth it only when DB and app-secret compromise are genuinely independent.
Managed KMS vs self-hosted Vault. Managed KMS is less ops and tightly IAM-integrated but means cloud lock-in and trusting the provider with your key custody. Vault is portable and gives you dynamic secrets, but it is infrastructure you now operate and must keep more available than the things it protects.
Build vs buy crypto. The line is bright: never build cryptographic primitives — use vetted libraries for hashing, encryption, signing. Building protocol glue on top of those primitives (your webhook-signing scheme, your envelope-encryption wrapper) is acceptable and sometimes necessary — but compose well-reviewed primitives, never invent the math.
8. Security & scale notes
Security and performance are the same property viewed twice; this chapter's primitives have real cost curves.
Crypto is a CPU/latency tax on the hot path. Argon2 on every login deliberately burns tens to hundreds of milliseconds, which bounds your authentication throughput — a busy provider-login endpoint is CPU-heavy by design. Per-request PHI decryption adds latency to every chart read. The mitigations: cache decrypted DEKs in memory (the key, never the plaintext PHI), batch KMS calls where possible, and isolate the crypto-heavy path (a separate worker pool or process) so a login storm can't starve the chart-read path. This is the bulkhead idea you'll formalize in the reliability chapter, applied to crypto.
KMS is a hard dependency and a rate-limited bottleneck. Under load, naive per-record Decrypt calls will hit the KMS QPS ceiling and serialize your PHI reads. Envelope encryption + DEK caching is what keeps you off that limit — you unwrap a DEK once, cache it briefly, and decrypt many records locally. Plan explicitly for a KMS regional outage: it means PHI reads fail, so decide whether degraded-without-PHI is acceptable per endpoint, and cache aggressively (with a short TTL) to ride out blips.
Login endpoints are prime DoS targets because they're expensive. The same KDF cost that protects you is a lever an attacker pulls: flooding login forces maximum CPU per request. Defend with dedicated rate limits on auth, escalating proof-of-work / CAPTCHA under suspected abuse, and a separate connection/worker pool for auth so its saturation can't drain the pool serving everything else.
A secret store concentrates risk — its IAM is your real perimeter. Once secrets live in one store, that store's access policy is the crown-jewel control. Audit it like one. And key rotation introduces a multi-version decrypt window: old key versions must remain available until every record encrypted under them has been re-wrapped, so you cannot delete a key version the instant you rotate — you retire it only after re-encryption completes (or, for crypto-shredding, you delete it deliberately to render data unrecoverable).
Constant-time everywhere on the auth path, and beware that encryption can silently break database guarantees: an encrypted column can no longer enforce a UNIQUE constraint or participate in dedup (every ciphertext differs), so you must move uniqueness (e.g. one MRN per patient) onto a blind index or accept its loss — a correctness consequence of a security decision, exactly the kind of cross-cutting effect senior review catches.
9. Interview lens & exercises
Interview questions
Backend security interviews probe whether you reason about adversaries or merely recite acronyms.
"Walk me through storing a password."
- Junior answer: "Hash it with SHA-256 and a salt."
- Senior answer: "Argon2id with a unique per-user salt and a tunable cost factor stored alongside the hash, rehash on login when I bump the cost, constant-time verification — and I'd name the tradeoff: cost tuning bounds auth throughput and creates a DoS surface, so I tune to ~150 ms and rate-limit login. SHA-256 is wrong here because it's fast, which helps the attacker."
"Difference between hashing, encryption, and signing — when do you use each?"
- Junior: defines the three terms.
- Senior: frames them by goal — "hashing is a one-way fingerprint, no key, for passwords and integrity; encryption is reversible-with-a-key for data I must read back; signing/MAC proves authenticity and integrity, MAC when I'm both signer and verifier, asymmetric signature when the verifier must not be able to forge" — and gives a per-field decision for Pulsely (password→hash, member_id/name→encrypt+blind-index, result webhook→HMAC)."
"How do you encrypt PHI at rest but still support HIPAA data destruction?"
- Junior: "Encrypt the column."
- Senior: "Envelope encryption — KMS KEK wraps a per-record DEK that AES-GCM-encrypts the field — with a
keyVersionfor rotation; then destruction at the end of a retention window is crypto-shredding: destroy the DEK and the ciphertext is unrecoverable everywhere, including backups, without touching the rows. I'd note the blast-radius reasoning: column encryption beats TDE here because my threat is app-compromise, not disk theft — and it all sits under a signed BAA."
"You find an SSRF in the document-import fetcher — impact and fix?"
- Junior: "Validate the URL."
- Senior: "Impact first: it can hit the cloud metadata endpoint (
169.254.169.254) and steal the instance IAM credentials, then pivot to internal services behind the VPC — including KMS, which guards every chart — because the request originates inside. Fix: egress allow-list, resolve the host and block private/link-local IP ranges, no user URLs to internal services, and don't follow redirects to a re-validated host."
"How do you verify a webhook is authentic?"
- Junior: "Check a shared API key."
- Senior: "HMAC-SHA256 over the raw body plus a timestamp, transmitted in a header, verified with constant-time compare and a timestamp skew window to block replay — and I sign the raw bytes, not re-serialized JSON, or the signature breaks. I'd also support secret rotation with overlapping valid secrets — this is exactly how I'd verify an inbound lab result or 835 remit."
Exercises & the Pulsely increment
Do these with a text file and a real Node REPL. Fluency, not perfection.
-
STRIDE the claim-submission and login flows. Produce a threat-model table for Pulsely's claim-submission, login, and chart-access flows: for each element/crossing, walk all six STRIDE letters, name the threat, the mitigation class, and the residual risk. Mark which mitigations land in this chapter versus deferring to Chapter 32, and flag which failures would be reportable HIPAA breaches.
-
Build envelope encryption + crypto-shredding. Implement encrypt/decrypt for
patients.full_name,patients.ssn,patients.member_idwith a (mock or real) KMS DEK, including thekeyVersioncolumn and a short-TTL DEK decrypt-cache. Then implement retention-window destruction as crypto-shredding — drop the DEK and prove the ciphertext no longer decrypts. -
Migrate secrets out of the repo. Move Pulsely's secrets into a secret store, add
gitleaksto CI, and write the rotation runbook. Assume the old.envalready leaked and document the response: rotate first, investigate second. -
Harden three endpoints. (a) Replace a raw string-concatenated query with a parameterized one (injection). (b) Add an egress allow-list + private-IP block to the document-import fetcher (SSRF). (c) Add HMAC verification to the outbound clinical-event webhook (the primitive Chapter 12 deferred here) — sign raw bytes, verify constant-time, enforce a replay window.
-
The four-verbs drill. Take ten real tasks ("store a password," "stamp a signed download link for a lab-result PDF," "let a partner verify a payload came from us," "stash a session in a cookie," "dedup uploaded scanned documents," "send a copay card number to a processor") and, for each, name which of encode / hash / MAC-sign / encrypt it needs — and why the other three are wrong. If this is reflexive, you have inoculated yourself against most crypto incidents.
Key takeaways
- Defenders must be perfect; attackers need one mistake. Security is a property of the weakest path, not your average code quality — and it's risk engineering under a budget, not absolutism. In healthcare, a broken access check is a reportable HIPAA breach, not a bug ticket.
- Trust boundaries are the primary object. Every crossing — client→API, service→service, service→3rd-party — needs authn, authz, validation, and encryption decisions. Internal boundaries are still boundaries; "it's in the VPC" is not a control.
- PHI carries extra invariants: minimum-necessary scopes (patient / provider / biller), RLS tenant isolation per clinic, break-glass with mandatory justification, and an immutable audit log of every view.
- Never blur the four verbs: encode (transport, no security), hash (one-way, no key), MAC/sign (authenticity, needs a key), encrypt (confidential, reversible with a key). Most catastrophic crypto bugs are one used where another was needed.
- Passwords need a KDF (Argon2id) with a tunable work factor and unique salt — not a fast hash. Use AEAD (AES-GCM) for encryption, with a unique nonce every time. Compare secrets in constant time.
- Envelope encryption (root → KEK → DEK → data) protects PHI by protecting a small rotatable key; crypto-shredding (destroy the DEK) is your retention-window destruction mechanism.
- Operate it right: reference secrets from a store (never commit), rotate after any leak, parameterize queries, block SSRF egress, sign webhooks over raw bytes with a replay window, and treat KMS and login as expensive hot-path dependencies to isolate.
- You set up the crypto here; Chapter 32 builds identity on it — authentication, JWT/session validation, OAuth, RBAC, and IDOR defenses all consume these primitives.
← Previous: Ch 30 — Performance Engineering & Tail Latency · Up: Part VI overview · Master TOC · Next: Ch 32 — Authentication & Authorization →