Zero trust for an API, from the request to the database
When implementing a zero trust API, there are several layers that must be considered. First and foremost there are the HTTP requests themselves. These should of course require authentication and be completely atomic. Next is introducing proof of work into any sort of form presented to an unauthenticated user. Additionally, in the case of a WebSockets implementation it is imperative that the connection be authenticated at the handshake, with a token that lives only long enough to open it, since we trust that connection for as long as it stays open. Finally, it is crucial that data be appropriately segmented and safeguarded, encrypted wherever it travels between machines and, for the most sensitive of it, encrypted before it reaches the database.
On a client portal we built for accounting firms, where a firm's staff and its clients share documents, returns and messages, we check the password at sign-in with Argon2id; for an email address that has no account, we run an Argon2id verification of the same cost against a dummy hash, so that a prober cannot tell from the response time whether the address has an account. Every time someone signs in with a correct password, we also email a six-digit code to the account's address, which the person enters to finish signing in. After the fifth failed attempt, our server locks the account for 5 seconds, doubling the lockout with each further failure up to a limit of 15 minutes. While an account is locked, however, we answer a sign-in attempt exactly as we answer a wrong password, after running the same Argon2id verification, because from a 429 status or a Retry-After header the sender would learn that the account was locked and when the lockout would end. We let the account's owner know about the lockout by email instead, since a person at the sign-in form who is not the owner has no access to the owner's mailbox. Once the lockout reaches 60 seconds, our server sends the owner one email for that run of failed attempts, with no countdown and no link, because phishers often imitate a security notice that contains a link.
Once a person has signed in, we give the browser an opaque session token, a random value in an httpOnly, Secure, SameSite=Lax cookie, and keep only the token's hash in the database, where someone who read a copy of the sessions table would find no token they could use. On every request, our server looks the session up by that hash and checks that we have neither revoked it nor let it pass its expiry, so we authenticate each request on its own and trust nothing from an earlier one.
We built the API for two programs, the portal and the firm's marketing site. In production, therefore, we treat a request that our own frontend would never send as either a bug of ours or someone probing the API. For that reason, we declare each request model to forbid any field it does not list. In production, we answer a malformed request with a bare 400 Bad request, because a sender who received a validation error for each field would learn which fields our request models accept and what type each one expects. We log the method, the path, the source address and the location and type of each failure, leaving the submitted values out of the log. When the mistake is ours, we diagnose it from that log and from our development server, which returns the full validation error for each field. We also serve the OpenAPI document and its Swagger page on the development server alone, since a sender who read them in production would learn every field our request models accept and the type each one expects.
We put a proof of work in front of the portal's sign-in form and the marketing site's contact form, using Altcha, which we host ourselves. We issue and verify each Altcha challenge on our own server, so a visitor's browser exchanges the challenge with our server and with no outside service; we chose Altcha over reCAPTCHA for that reason. We sign each challenge with HMAC and write its expiry into the signed part, so that we can verify a solution later without keeping a row for the challenge. The visitor's browser solves the challenge with SHA-256 through Web Crypto as the page loads, at a cost we set low enough that the browser finishes in about a tenth of a second. We accept the solution for 30 minutes, because the browser solves it before the person starts typing, giving the person time to fill in the form at their own pace.
On our own site, we put the same kind of proof of work in front of Lumo, the chat assistant, where the browser also solves it with Web Crypto, with no widget and no WebAssembly. Altcha's maintainers also offer a challenge built on Argon2id, which a caller cannot solve much faster on a GPU than in a browser. We declined it, however, because we use the proof of work there for one purpose, which is to make a caller spend some computing time before our server opens a chat session. We protect the language model itself with four other layers: a token our server signs when the page loads, nginx rate limits, a budget for each session and a limit of two inferences at once on the one GPU. A caller who solved the SHA-256 challenge faster on a GPU would still meet the rate limits and that limit of two, so we kept the challenge that a browser can solve with Web Crypto alone.
Where a second program has to check a token without a database lookup, as our push broker does for a WebSocket connection, we sign a compact token of our own with HMAC-SHA256 (the payload in base64url, a period, then the signature in base64url), using the same HMAC function with which we sign the six-digit codes we email at sign-in. We wrote that token format ourselves so that we could leave JSON Web Tokens (JWTs), and any library for them, out of the portal entirely. The push broker, a separate program that holds each person's WebSocket connection, accepts such a token when the browser connects. The portal API mints it for the signed-in person with a life of 60 seconds, long enough for the browser to go from the API call to the WebSocket handshake. The broker checks the token's signature and expiry without reading a database; from then on, the broker treats the connection as authenticated for as long as it is open.
We sign the Accept links in our hand-off emails the same way. When a firm user hands a client a file, such as an engagement letter, to accept, we email a separate link to the address of each of the client's logins, signed under a key we derive for those links alone, so that our server never accepts a token we minted for the push broker as an Accept link. We put the ids of the firm, the hand-off and the client's login in each link's token, along with an expiry 30 days after we send the email. We keep no row for a link; however, our server checks the hand-off and the login on every use, refusing the link once the client accepts the file, a firm user takes the file back or the client can no longer sign in with that login.
Within the portal's database, we gave each firm its own Postgres schema and its own database role, while the API logs in to Postgres as a role to which we granted no privilege on any table. When a request arrives, our server opens a transaction, looks up the firm whose id we stored in the caller's session and runs SET LOCAL ROLE to that firm's role, along with SET LOCAL search_path to the firm's schema; Postgres drops the role again when the transaction commits or rolls back, returning the connection to the API's own role. By isolating access to each firm's schema in that way, we made any attempt at cross-schema access result in a Postgres error. We applied zero trust (never trust, always verify) at the database in this way: we start every request with no access and have our server take on one firm's role for one transaction at a time. We left the boundary between firms to those grants and wrote our queries without a WHERE clause for it, which means a developer cannot open a gap between firms by forgetting one.
We protect the access log (who opened which client's file on which day) with the same kind of grant, giving the firm's role SELECT and INSERT on that table and no other privilege. We cannot, in other words, update or delete a row in it through our own API.
Inside a firm, however, staff and clients share the same tables, so we enforce the boundary between one client and another in the queries themselves. OWASP ranks a failure at this boundary, which it calls broken object-level authorization (a caller reading another party's record by supplying its id), first on its API Security Top 10. Once per transaction, our server works out which clients the caller may see and turns that into a list of client ids: every client of the firm for a firm administrator, the clients assigned to a contractor for the current tax season, and, for a client who signs in, that client's own id. We compute that list for every role in one function, building the client_id = ANY($1) condition in the same module as the list, where a developer who changes the condition finds the list beside it. We add that condition to every query that lists records. Also, when a caller asks for one document by its id, our server applies the same condition in the same statement that fetches the document, which means a caller who supplies another client's document id gets the same 404 as a caller who supplies an id that does not exist. We generate the ids themselves with Postgres's gen_random_uuid(), giving each record a random (version 4) UUID that a caller cannot guess by counting.
In an early version of that function, we returned None to mean every client in the firm and an empty tuple to mean no clients at all. A developer who tested the result with a plain if in Python would get false for both values, however, and could not tell every client from no client in the result our server uses to decide whose tax data a caller sees. Presently, in place of None, our server fetches every client id in the firm for a firm administrator with one query against a few dozen rows, leaving an empty list to mean only that the caller may see no client's records.
We wanted to confirm after every deploy that these boundaries still held in production, so we wrote two checks. For the first check, we only read from the database: for each kind of caller, we count the records that caller can see in a live firm schema and compare those counts with the numbers we expect from the schema's totals, so we can run it against production after every deploy. In fact, when we introduced a regression in what a staff member sees while acting as a client, we ran the unit tests and every one still passed, while we saw the regression in the first check's counts within a second of running it. For the second check, we build a throwaway firm schema from the full template, confirm as that firm's role that Postgres denies access to every other firm's schema and drop the throwaway schema when we finish.
On that portal, we serve every request over TLS, from the visitor's browser to nginx. We also encrypt client content in the application before it reaches Postgres, with AES-256-GCM in three tiers. We encrypt each document under a fresh data key; we wrap each client's data keys with a key-encryption key for that client (or, for a document the firm itself owns, with a key for the firm); finally, we wrap each of those keys with a root key. We bind the client's id, as additional authenticated data, both into each document's ciphertext and into each wrapped data key, so that anyone who moved a ciphertext or a wrapped key to another client's row could not decrypt it. Anyone who took a database dump, read the raw disk or read the tables as the Postgres superuser would find only ciphertext. We also mint a key for each chat conversation, which we wrap with the firm's key, and encrypt each SSN or EIN in the column where we store it; to find a taxpayer by that number, we look up a one-way HMAC of it under a key we derive for each firm, so we keep no searchable copy of the number in the database.
The portal also passes the pages of every return in flight through freestream, the event-streaming library we wrote and publish under the MIT license, which writes its log segments to disk on that same host. We seal each record's key, value and headers in freestream's own code with AES-256-GCM, bound to the record's offset, so that anyone who copied a sealed record to another offset could not open it. We keep the key in a file of its own, apart from any product's settings. We weighed dm-crypt on the host instead and chose to encrypt in freestream's code, because a setting on the host would end up being something we forget about over time. Producers and consumers reach the freestream server over a unix socket on the same host, where we decide through the socket's filesystem permissions who may connect. When we move a page reader to a machine of its own, we plan to add a TCP listener with TLS beside the socket, serving the same protocol.
We of course rein in our enthusiasm for safeguards like these where we find that one slows our queries or makes it harder for us to change the application as it grows. In fact, we reached both limits with row-level security, which we chose at first as the boundary between clients and removed two months later, once we had measured how much it slowed our queries and complicated our data migrations, but that story is for another conversation.