ealeng

Episode 48 of 55 · Security

29 access tests passed, and 15,336 requests for other customers' invoices were answered: broken authorization and tenants

A hand-written list of 29 access tests passed with a planted bug in place: an invoice endpoint that checked only that the caller was logged in. A fuzzer that replays recorded requests with other customers' order ids found the leak at its second request, and all 15,336 swapped invoice requests were answered. In one orders table shared by 50 tenants, a search that forgot its tenant filter returned other tenants' rows on all 2,030 of its calls. Row-level security, where the database adds the filter itself, leaked none, for about 0.7 ms more at the median. Then one tenant at ten times its load took everyone else's p99 from 15.9 ms to 2.9 seconds, until a per-tenant limit brought it back to 22.5 ms.

Lab 20 · Security, Auth and Multi-Tenancy12 min read
Video transcript9:13

0:00Cold open

0:01

My orders service has hand-written tests for who may see what. I planted two bugs in it on purpose, to see if they would notice.

0:10

Every test passed.

0:13

Then a tool replayed recorded requests with other people's ids. It found the bug on its second try. Fifteen thousand three hundred thirty-six requests for someone else's invoice, and every one was answered.

0:28

And in the same database, one search that forgot a single filter returned other companies' orders on every call.

0:37

So how do tests that pass let all of that through?

0:43Intro

0:44

Hands-on system design, part forty-eight.

0:47

Today: authorization, finding the check nobody wrote, and keeping fifty companies out of each other's data.

0:56Meet Lucía

0:57

I'm Lucía, a platform engineer. Our orders service is shared by fifty companies, called tenants. Each has an admin, a support agent, and eighteen customers.

1:08

Every request asks two questions. First, authentication: who are you? You log in once, and get a pass the service checks on every request.

1:19

Second, authorization: may you touch this one? This order, this invoice, this document.

1:25

Think of a hotel. Authentication is your key card working in the building. Authorization is it opening your room, and only yours. Each company is a floor. My bug is one door that opens for any guest's card.

1:4201 · What you need

1:43

To run it yourself: Docker, for the service, its Postgres database, Redis, and OpenFGA, which I'll explain in a moment.

1:53

The quick tests, including the rules and the fuzzer itself, run without Docker in a couple of seconds. No cloud, nothing to pay for.

2:0402 · The rules

2:05

The service checks three kinds of rule. Ownership: a customer reads only their own orders. Support and the admin read their company's.

2:15

Roles: only a company's admin may delete an order.

2:20

And relationships: you can open a document if your group can open its folder. Those links live in OpenFGA, a service built to answer questions like that.

2:32

And the bug I planted: the invoice for an order checks that you're logged in. Nothing else.

2:40

I checked OpenFGA against a sixty-line checker I wrote myself, on one thousand and eighty questions. They agreed on all of them, so I trust my checker as the fuzzer's answer key for documents.

2:5503 · The tests

2:56

First, the usual way: a list of hand-written cases. Each one is a user, a request, and whether it should be allowed. Twenty-nine of them, including fake and expired passes.

3:09

With the bug in place, all nineteen cases that should be refused were refused. The tests passed.

3:17

Because nobody wrote a case for the invoice. A list only tests what someone thought to list.

3:2504 · The bug, in code

3:26

In code, the order endpoint, the address that returns one order, asks: may this user read this row? Same company, and either your own order, or you're support or the admin.

3:39

The invoice endpoint finds the same row, and only checks that it exists. The ownership check below it is switched off. That's the bug.

3:48

Then it answers. Being logged in was enough. Security people call this broken object-level authorization. It tops OWASP's list of the ten biggest risks for APIs, the interfaces programs call.

4:0405 · The fuzzer

4:06

The other way is a fuzzer: a tool that tries inputs nobody wrote by hand. Mine records test customers opening their own orders, invoices and documents. Then it replays those requests with ids they don't own. Any success is a leak.

4:23

Thirty-one thousand swapped requests. How many do you think got through?

4:30

Every swapped invoice: fifteen thousand three hundred thirty-six of fifteen thousand three hundred thirty-six. The orders and the documents: none.

4:41

The first leak came at request two. Shuffled twenty more times, it took between one and five.

4:49

Why so fast? About half the swaps were invoices, and every one leaked. So each request is a coin toss: two tries, on average. And the fuzzer didn't need to know that endpoint existed. It was in the recorded traffic.

5:0506 · After the fix

5:07

The fix: the invoice runs the same check as the order. Same thirty-one thousand swaps: zero leaks.

5:15

And with three invoice cases added, the hand-written list caught it too, with two failures before the fix. Once someone knew to write them.

5:2507 · One table

5:27

Now the other half. All fifty companies' orders live in one table, with a company id on every row. Every query should say: only my company's rows. One kind, a search by tag, was written in a hurry, and forgets.

5:43

Every one of the two thousand and thirty tag searches leaked. The other four kinds: none. So a test of any of those would have passed.

5:53

Nearly forty thousand rows came back from another company. Each tag search looked across all fifty companies and returned twenty rows: about nineteen and a half were someone else's.

6:06

Then the same queries, the same bug, with row-level security: the database itself adds "only this company" to every query on the table. Zero rows leaked.

6:1908 · Row-level security, in code

6:20

In code, it's a policy on the table: a row is visible only if its company id matches the company set for this request.

6:30

Each request opens a short transaction, a batch the database runs together, sets its company, then runs the query, even a query that forgot to filter.

6:4209 · What it cost

6:44

What did that cost? With the filter in the app, a typical query took about one point three milliseconds.

6:52

With row-level security, about two. Seven tenths of a millisecond more.

6:58

Most likely, that's three extra round trips, a message to the database and back: begin, set the company, commit. The check itself is a simple comparison.

7:1110 · A noisy neighbour

7:12

Sharing a database also means sharing its capacity. Ten companies ask for a monthly report, thirty a second each. Reports share four database connections, and each runs one report at a time. Each report is padded to about six milliseconds, standing in for a bigger company's data, and a script plays the ten companies. Normally, the slowest one in a hundred took sixteen milliseconds.

7:38

Then one company asked ten times as often. Everyone else's slowest one in a hundred went to two point nine seconds. Nothing failed. Everyone just waited.

7:50

On paper, four connections at about six milliseconds a report is about six hundred seventy a second. The spike asked for five hundred seventy, and a queue still grew, so the real limit was lower.

8:04

Then a limit per company: sixty reports a second, and past that, a quick "too many requests". Everyone else: twenty-two and a half milliseconds, close to the normal sixteen.

8:17Back to Lucía

8:18

So, three lessons.

8:21

Hand-written tests only check what someone listed. Replay recorded traffic with other people's ids, and you test every endpoint in that traffic, listed or not.

8:33

Put the company filter where it can't be forgotten: in the database, for under a millisecond on a typical query.

8:41

And shared capacity needs a limit per tenant, or one busy neighbour slows everyone.

8:49

Next time: logging in. What a stolen login code is worth, what a password hash costs, and why locking accounts didn't stop the attack.

8:59

For today: try every door, and lock each company's floor.Lucía: Try every door. Lock the floor.

9:04Summary

9:05

Fuzz with recorded traffic, filter in the database, and limit each tenant.

Key takeaways

  • ✓A hand-written access test checks only the cases someone wrote: the 29-case matrix passed with the bug in place, refusing all 19 requests it expected to be refused, because none of its cases asked the invoice endpoint (GET /orders/{id}/invoice, the invoice of the order whose id is in the URL) for another customer's order.
  • ✓The bug is broken object-level authorization (BOLA): the invoice endpoint checked that the caller was logged in and never checked that the order was theirs, so all 15,336 requests that swapped in another customer's order id were answered with an invoice.
  • ✓An ID-swapping fuzzer, a program that replays recorded requests with other people's ids, found the leak at its second request in the full run and needed 1 to 5 requests in 20 other shuffles, because about half of its 31,081 swapped requests went to the invoice endpoint, and every one of those was answered.
  • ✓Adding the 3 invoice cases a reviewer would write made the matrix fail 2 of its 21 expected denials; once the invoice endpoint ran the same ownership check as the order endpoint, the same 31,081 fuzzer requests leaked 0.
  • ✓In one orders table shared by 50 tenants (companies), a tag search that forgot its tenant_id = filter leaked on all 2,030 of its calls, returning 39,818 of 160,460 rows (about a quarter) that belonged to other tenants, while the four other query kinds leaked none.
  • ✓Row-level security, a database policy that adds the tenant condition to every query on the table, leaked 0 rows with the same forgotten filter, at a median cost of 1.31 ms before and 2.04 ms after (the p99, the slowest 1 in 100, went from 2.86 ms to 5.55 ms).
  • ✓When tenant 1 sent ten times its normal load, the p99 of the other nine tenants went from 15.9 ms to 2,916 ms; a limit of 60 requests a second for tenant 1 brought it to 22.5 ms and refused 7,252 of its 9,064 requests with a 429 (too many requests) answer.

Twenty-nine hand-written access tests passed while the bug was in place. A fuzzer that swapped in other customers' order ids found it on its second request, and every one of the 15,336 swapped invoice requests was answered. This chapter covers why the passing tests were not proof, how an ID-swapping fuzzer finds what a list misses, and how one shared table can keep fifty companies apart when a query forgets its filter.

The examples come from Lab 20 (Security, Auth and Multi-Tenancy) of the system design labs. Its orders service is one process with the checks written into it, and the tests and attacks run from a client container against that service. The data is synthetic: 50 tenants, 1,000 users and 100,000 orders, loaded by a setup script. The lab ran in Docker Compose on an Apple M4 Max with Docker Desktop and 16 virtual CPUs, with Postgres 17 for the tables. Scripts 01_authz.py (the tests and the fuzzer) and 02_tenants.py (the shared table and the noisy neighbour) each write one results file, and each configuration is one recorded run. The lab also checks OpenFGA, a relationship-based authorization service, against a 60-line evaluator of its own.

Logged in is not the same as allowed

Every request asks two questions. Authentication asks who you are: you log in once and present a token the service checks each time. Authorization asks whether you may do this, to this object. An order, an invoice or a document each needs its own answer.

Think of a hotel. Your key card working in the building is authentication. The card opening your room, and only yours, is authorization. The bug in this lab is a door that opens for any guest's card.

Most of the damage in APIs (the interfaces programs call) comes from the second question being skipped for one object. The lab plants exactly that: the endpoint GET /orders/{id}/invoice returns the invoice for the order whose number is in the URL, and checks only that the caller is logged in. The security community names this broken object-level authorization, or BOLA. It is number one on OWASP's API Security Top 10, the standard list of the most common API risks.

The order endpoint, GET /orders/{id}, is correct. It asks whether the order is in the caller's tenant and whether the caller owns it, or is support or an admin. The invoice endpoint finds the same row, then answers without that check. Its response also includes the owner's username, so the leak is wider than the amount.

Why a passing test list is not proof

The usual first defence is a test file: a list of cases, each a user, a request, and whether the answer should be allowed or refused. The lab's matrix has 29 of them, including forged tokens (one with alg: none, which claims no signing method at all, and one signed with a guessed key) and an expired token. Nineteen of the cases should be refused.

With the bug in place, every one of those 19 refusals happened. The tests passed. They tested the order endpoint with another customer's id, and it refused. Nobody had written a case for the invoice, so the test had nothing to catch.

Adding the three invoice cases a reviewer would write changed the result at once. The matrix now failed two of its 21 expected refusals: carol, a customer, could read another customer's invoice and another tenant's invoice. The lesson is not that the matrix is useless. It tests only what someone thought to list.

The fuzzer: swap the ids, keep the answers that should be refused

The other way is to generate the cases instead of writing them. The lab's fuzzer (id_swap_fuzz in authz_matrix.py) works like this:

  1. Record traffic. Seventy-two customers in four tenants log in and make their ordinary requests: their first three orders, the invoice of each, and the documents they can open. That is 803 recorded requests.
  2. Swap ids. Each recorded request is replayed as the same user with another user's object id in the path. The fuzzer keeps only the swaps that should be refused, using an oracle, the rule that says who may see what. For orders and invoices, the oracle is each customer's own order list. For documents, it is the lab's 60-line relationship checker, which agreed with OpenFGA on all 1,080 checks.
  3. Count the 2xx answers. Any success, a status code from 200 to 299, for a swapped id the oracle says must be refused is a leak.

The full run sent 31,081 swapped requests. Of those, 15,336 targeted the order endpoint, 15,336 the invoice endpoint and 409 the document endpoint. The results by endpoint are in the table below.

The fuzzer does not need to know which endpoints exist. It replays whatever traffic it recorded, so an endpoint that is used is covered the day it ships, listed or not.

Try it · Two ways to test the same bugrecorded run, 01_authz.py

The 29 hand-written cases, with the invoice endpoint's bug in place. No case covers the invoice, so the matrix has nothing to catch.

Matrix: expected denials refused
19 of 19
Matrix failures
0
Fuzzer requests
31,081
Fuzzer leaks
15,336

Swapped-id requests answered, by endpoint

/orders/{id}
0 of 15,336
/orders/{id}/invoice
15,336 of 15,336
/docs/{id}
0 of 409

The fuzzer's oracle says which orders each customer owns; a 2xx answer for any other customer's id is a leak. In the first run the first leak came at request 2 of the full run, and at 1 to 5 requests in 20 other shuffles.

The first leak came at request 2 of the full run. The lab then shuffled the same requests with 20 other seeds, and the first leak came between request 1 and request 5 in every one of them. The speed is a property of the traffic mix, not luck: about half the swaps hit the buggy endpoint, so each request was roughly a coin toss.

The fix, and what it proved

The fix runs the invoice endpoint through the same ownership check as the order endpoint. The lab switches it on with a configuration flag, fix_bola, and reruns everything. The matrix passes all 21 expected refusals, and the fuzzer's same 31,081 requests leak nothing: 0 of 15,336 order swaps, 0 of 15,336 invoice swaps, 0 of 409 document swaps.

The fixed run proves that this traffic no longer leaks. It does not prove that no other endpoint does. That is why the fuzzer should run on every release, and the matrix should grow every time a bug is found.

One table for fifty tenants

Now the second half of the problem. Fifty tenants share one orders table, and each row carries a tenant_id column that names the company it belongs to. A shared table is the cheapest way to host many customers, and the rule is simple: every query says WHERE tenant_id = ..., with the tenant the request belongs to. The lab's queries are five kinds: by id, by status, the most recent orders, by amount, and by tag.

The planted bug is the tag search. Written in a hurry, it filters by tag and forgets the tenant. Its WHERE clause takes the tenant as a parameter but never compares it with tenant_id.

Over 10,000 random queries from 200 users, using the five kinds in turn:

  • The tag search leaked on every call. All 2,030 tag searches returned rows from other tenants.
  • The other four kinds leaked nothing. Their queries all had the tenant filter. A test that sampled only those kinds would have passed.
  • A quarter of the rows were foreign. Of 160,460 rows returned, 39,818 belonged to other tenants. Each tag search returns up to 20 rows, so each returned about 19.6 other tenants' rows (the total divided by the number of tag searches, since the other kinds leaked none).

Row-level security: let the database add the filter

Postgres has a feature called row-level security (RLS). A policy on the table says which rows a session may see, and the database adds that condition to every query on the table, including one that forgot it. The lab's policy is one line: a row is visible only if its tenant_id equals the value of the setting app.tenant_id for this session.

The app sets that value inside a transaction, a group of statements that the database runs together: it begins, runs SET LOCAL app.tenant_id (a setting that lasts only until the transaction ends), runs the query, and commits. The same tag search, with the same missing filter, then returned 0 foreign rows in 10,000 queries.

Try it · One table, fifty tenantsrecorded run, 02_tenants.py

The same tag search, written without its tenant filter, run twice: once with only the app's filter, and once under row-level security, where the database adds the filter itself.

App filter onlyRow-level security
Queries that leaked (of 10,000)2,0300
Other tenants' rows (of 160,460)39,8180
p50 latency, ms1.312.04
p99 latency, ms2.865.55

Only the tag search kind leaked; the other four kinds returned no foreign rows in either run.

The cost was measurable. With the filter in the app, the median query (p50) took 1.31 ms, and the p99 took 2.86 ms. With row-level security it took 2.04 ms and 5.55 ms. The lab's notes attribute most of the 0.7 ms at the median to three extra round trips to the database, a message out and back for BEGIN, SET LOCAL and COMMIT. The policy check itself is a simple comparison on an indexed column. The lab did not time those round trips separately.

A noisy neighbour

Sharing a database also shares its capacity. In the lab's second test, ten tenants each call a monthly report 30 times a second. The report runs on a separate pool of four database connections, and each report holds one connection for about six milliseconds. The lab pads each report with a short sleep to stand in for a larger tenant's data. Then tenant 1 goes to ten times its load, while the other nine keep to 30 a second.

  • Normal load: the other tenants' p99 was 15.9 ms.
  • Tenant 1 at ten times its load, no limit: the other tenants' p50 rose from 8.7 ms to 867 ms, and their p99 to 2,916 ms. Nothing failed. Everyone waited, because the connections were shared and a queue grew.
  • Tenant 1 at ten times its load, with a per-tenant limit of 60 requests a second: tenant 1 was served 1,812 requests and refused 7,252 with a 429. The other tenants' p99 was 22.5 ms.

The limit is a token bucket, the same kind of limiter as in Lab 17 (rate limits and load shedding): each tenant has a bucket that refills at 60 tokens a second, and a request without a token is refused at once. A limit has to cost less than the work it saves, or refusing costs as much as serving.

The workflow and the results

Authorization. 01_authz.py runs three times: the bug with the matrix as written, the bug with the invoice cases added, and the fixed service. The results file data/results/01_authz.json holds all three runs. The table below uses the recorded values.

Run Matrix cases Expected refusals refused Matrix failures Fuzzer leaks, of 31,081 requests Invoice swaps leaked
Bug, matrix as written 29 19 of 19 0 15,336 15,336 of 15,336
Bug, invoice cases added 32 19 of 21 2 15,336 15,336 of 15,336
Fixed 32 21 of 21 0 0 0 of 15,336

Tenants. 02_tenants.py runs 10,000 queries twice, once with the app filter and once under row-level security, and then the noisy-neighbour test, 30 seconds for each of its three runs. Its results are in data/results/02_tenants.json.

Isolation Queries that leaked Other tenants' rows p50 p99
App filter only 2,030 39,818 of 160,460 1.31 ms 2.86 ms
Row-level security 0 0 2.04 ms 5.55 ms

Caveats

  • One recorded run per configuration. The matrix and tenant results come from single runs on one laptop. The first-leak counts come from 20 extra shuffles of the same traffic, not from new traffic.
  • The oracle is the lab's own. The fuzzer knows the right answers from each customer's order list and from the 60-line checker, not from an owner column in a production database. A real system needs the same kind of oracle, and building it is where most of the work is.
  • The traffic is scripted. Each customer's requests are chosen by the script: their first three orders, their invoices, and the documents they can open. Real traffic includes more endpoints and more odd ids, and it may not swap as often.
  • Not every endpoint was swapped. The fuzzer covered three templates it could find in the traffic, the order, invoice and document endpoints. An endpoint that no customer had called in the recording was not tested.
  • The noisy-neighbour load is a script. The report pool is four connections, and each report is padded with a sleep to stand in for a bigger tenant's data. The lab's notes put the pool's capacity at about 500 requests a second, which is an estimate, not a measurement.
  • The row-level security cost is not broken down. The lab reports the total cost of the extra round trips, not each one. Its tests also run as a database role that bypasses row-level security for the app-filter run, so the two runs are measured on the same queries but under different roles.
  • Not covered here: logging in with OpenID Connect and PKCE, sessions and tokens, and credential stuffing. The next episode takes up logging in. Revocation, the cost of each check and rotating database credentials are in the lab's other exercises. Mutual TLS between services is in the lab, and none of this chapter's sources covers it.

The checklist

  1. Test the objects, not just the endpoints. For every endpoint that takes an id, one case should ask for another user's object and expect a refusal.
  2. Replay recorded traffic with other people's ids. A fuzzer over the traffic you already have finds the endpoints nobody listed.
  3. Put the tenant filter where it cannot be forgotten. Row-level security adds the condition in the database, so one query that forgot it leaks nothing.
  4. Set the tenant per transaction, not per session. A connection pool must not hand one tenant's setting to the next request.
  5. Limit each tenant's share of the shared capacity. One busy tenant should wait behind its own limit, not everyone else's requests.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A 29-case access test passed while an endpoint returned other customers' invoices. What is the most likely reason?

  2. 2.The fuzzer found the leak at its second request. Why so quickly?

  3. 3.A tag search forgot its tenant filter. Which change stops it from leaking without editing that query?

Check your understanding

Try each question before opening its answer.

The matrix had a case where carol asked for another customer's order and was refused. Why did that case not reveal the invoice bug?

Because that case called the order endpoint, GET /orders/{id}, which was correct. None of the 29 cases asked the invoice endpoint for another customer's order, so the bug on that endpoint was never exercised.

What changed in the fixed run, and what did the fuzzer find after the change?

The invoice endpoint ran the same ownership check as the order endpoint, switched on by the lab's fix_bola flag. The fuzzer sent the same 31,081 requests and leaked none: 0 of 15,336 invoice swaps, down from 15,336 of 15,336.

Why did the tag search leak on all 2,030 calls, while the by-id and amount searches never leaked?

Only the tag search left out the tenant_id filter. Every other query kind had WHERE tenant_id = $1 in its SQL, so its results were limited to the caller's tenant.

Row-level security added about 0.7 ms at the median. Where did that time go?

The lab's notes say most likely three extra round trips to the database, for BEGIN, SET LOCAL and COMMIT. The policy check itself is a simple comparison on an indexed column. The round trips were not timed on their own, so this is the likely cause, not a measured one.

Next up: logging in, what a stolen login code is worth, and what a password hash costs: Credential stuffing and password storage.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.