Chapter 19 / 24 · System Design

Identity, authorisation and the security basics

Customers, restaurants and riders read the same order row. Who is calling, which slice of it they may see and when, and how to trust a payment webhook.

This chapter lets you decide how Dabba knows who is calling, what each kind of caller is allowed to see and change, and how to trust messages that arrive from outside, such as a payment provider telling us an order is paid. It is not a security course. It covers the decisions a system designer cannot hand to someone else.

Dabba has three kinds of user, and they want different things from the same data. A customer wants to see their own orders. A restaurant wants to see the orders placed with it, including what was ordered, but not the customer’s card. A rider wants to see the pickup and drop-off for the order they are delivering right now, including an address and a way to call the customer, and nothing about any other order. An order row contains all of this at once. Security for Dabba is mostly the question of which slice of that row each caller gets, and when.

The failure to keep in mind is unusual. Most broken systems stop working, and someone notices. A broken authorisation check keeps working perfectly, for the wrong person, and nobody notices until the data is somewhere it should not be.

From an OTP to a credential on every request

Authentication establishes who the caller is. Dabba customers and riders prove control of a phone number with an OTP; restaurant staff log in to a tablet app with a phone number and OTP too, tied to a restaurant account. After that one proof, the app needs something to present on every request that says “this is customer 551” without repeating the OTP. There are two common shapes.

A server-side session is an opaque random string. The app sends it with each request and the server looks it up in a session store to find the user. Revoking it means deleting the row. Its cost is that lookup on every request: a cache read, around a millisecond, and a session store that every service depends on.

A signed token, typically a JWT, carries the claims itself (“subject: customer 551, role: customer, expires 20:15”) and a signature. Any service holding the public key can verify it locally with no lookup. Its cost is the reverse of the session’s: the server cannot take it back. A token signed at 20:00 with a 15-minute life is valid until 20:15 whatever happens in between.

Dabba uses the common combination. A short-lived access token (a JWT, 15 minutes) is sent on every API call and verified locally by the gateway and services. A long-lived refresh token (an opaque string stored server side, valid for, say, 60 days) is used only to obtain new access tokens. Every refresh rotates it: the old refresh token is marked used and a new one issued. If an old refresh token is ever presented again, someone has a copy, and the whole chain for that device is revoked. On the phone, tokens live in the platform’s secure storage (Keychain on iOS, Keystore-backed storage on Android). On the restaurant web dashboard, the session lives in a cookie marked HttpOnly (scripts cannot read it), Secure (sent only over TLS) and SameSite (not sent on requests started by other sites).

Predict first

A rider is suspended for fraud at 20:00. Their app received a fresh 15-minute access token at 19:58, and their refresh token is revoked at 20:00. Until when can they act as a rider, and what should the design do about it?

Show the worked answer

The access token stays valid until 20:13. Any endpoint that checks only the token’s signature and role will treat them as an active rider until then. They cannot get a new access token after that, because the refresh is refused.

Whether 13 minutes matters depends on the action. Reading their own earnings page for 13 minutes is harmless. Accepting a new order and collecting a cash-on-delivery payment is not. So the actions that matter check the rider’s current state, not just the token: the assignment service already reads the rider’s row when offering an order, and that row says status = 'SUSPENDED'. The general rule is that a token proves who the caller was when it was issued; decisions with consequences read the current state. Shortening the token to two minutes is the other lever, at the cost of more refresh traffic.

Authorisation is a relationship, not a role

Authorisation decides whether this caller may perform this action on this object. The first instinct is roles: customers can call customer endpoints, riders rider endpoints. Roles are necessary and nowhere near sufficient. Every rider is allowed to call GET /rider/orders/:id. The question that matters is whether this rider is assigned to this order.

Write down, per resource, the relationship that grants access. For an order in Dabba:

CallerMay see the order whenSeesNever sees
Customerthey placed iteverything about their orderrider’s personal phone number
Restaurant staffit was placed with their restaurantitems, notes, customer first nameaddress, phone, payment details
Ridercurrently assigned, from acceptance until delivery + 30 minpickup, drop-off address, masked phoneorder history, other orders, payment
Support agenta ticket references itwhat the ticket needs, loggedfull card data (Dabba never has it)

Two features of this table carry most of the design. Access is time-bound: a rider who delivered an order at 20:40 has no reason to see that customer’s address at 23:00, or next week. And access is shaped: different callers get different projections of the same row, so the check is not only yes or no but also which fields. The phone number a rider sees is a masked relay number that forwards to the customer for the life of the delivery, so the customer’s real number never reaches the rider’s phone at all. Not holding data is the strongest protection for it.

The rule that makes the table enforceable is that each resource type has one function that answers the question, and every handler calls it.

def can_view_order(principal, order, now):
    if principal.role == 'customer':
        return order.customer_id == principal.id
    if principal.role == 'restaurant':
        return order.restaurant_id in principal.restaurant_ids
    if principal.role == 'rider':
        a = order.assignment
        return (a is not None and a.rider_id == principal.id
                and (a.delivered_at is None or now < a.delivered_at + minutes(30)))
    return False

When authorisation logic is copied into each handler, every new handler is a fresh chance to forget it. One function, tested with a table of cases like the one above, can be reviewed once and changed once.

Walk-through: the order ID that opened every order

Here is how it typically goes wrong. A developer adds a “share your order status” feature and a new endpoint, GET /orders/:id/summary, used by the customer app. The gateway checks that the request carries a valid customer token. The handler loads the order by ID and returns its summary: restaurant, items, delivery address, the customer’s name and phone. Tests pass, because the tests request the tester’s own orders.

Order IDs in Dabba follow the layout from the IDs chapter: 41 bits of milliseconds, 13 bits of logical shard and 10 random bits. They are not sequential, so subtracting one from your own ID finds nothing. That does not make them secret. The first leak is ordinary: IDs appear in shared tracking links, screenshots, support chats and logs, and a rider who has made 300 deliveries has 300 real IDs in the app’s history. A former rider with that list, calling the new endpoint with an ordinary customer token, gets 300 names, addresses and phone numbers, weeks after the deliveries ended.

The second leak is a narrowed search. Someone who wants one person’s address and knows they ordered from a particular restaurant around 20:15 already knows the shard bits (any order of their own from that restaurant carries them) and the time to within a minute. That leaves 60,000 milliseconds × 1,024 random values, about 61 million candidates, which a botnet at 2,000 requests a second covers in roughly eight hours. Ten random bits stop casual counting; they do not stop a search with a target in mind, and they do nothing for IDs that have already leaked. This class of bug is called an insecure direct object reference (IDOR), and broken access control of this kind sits at the top of the OWASP Top Ten for good reason. The bug was not in authentication. The caller was a genuine, logged-in customer. The missing check was the relationship: is this caller the order’s customer?

The fix has layers, in order of importance. First, the handler calls can_view_order, and returns 404 rather than 403 when it fails, so that the response does not confirm which IDs exist. Second, we make the check hard to forget by putting it in the data access layer: customer-facing code never calls “load order by ID”, only “load order by ID for this principal”, which adds AND customer_id = :caller to the query. A missing check then shows up as a function that does not exist rather than a line someone forgot. Third, a test that runs every customer endpoint with a second customer’s token and expects 404, so a new endpoint without the check fails CI.

Making IDs fully random (128-bit UUIDs instead of Dabba’s layout) is often proposed as the fix. It would make the narrowed search impractical, at the cost of the shard routing and index locality the IDs chapter wanted, and it is still not a fix. IDs leak: they appear in shared links, screenshots, support tickets and logs. An endpoint that returns any order to anyone holding its ID is only as private as every place the ID has ever been written. The check is the fix; the unguessable ID buys time when the check is missing somewhere.

The costs of the fix are worth naming. Every query now carries the caller, which complicates code that legitimately crosses customers, such as support tools and batch jobs. Those get separate, explicitly named access paths with their own audit logs, so the exception is visible rather than accidental. And per-relationship checks sometimes need data the handler did not have, such as the current assignment, which is another read on the request path.

A webhook is an anonymous request until you prove otherwise

Dabba does not handle card numbers. Customers pay on the payment provider’s hosted page or SDK, which keeps card data out of Dabba’s systems and most of the card industry’s compliance scope with it. When the provider captures a payment, it calls Dabba’s webhook, POST /webhooks/payments, with a body like {"event": "payment.captured", "order_id": 9182, "amount": 41800}. On that message, Dabba marks the order paid and sends it to the restaurant. The writes chapter built this handler to cope with webhooks that arrive late, twice or out of order, with a reconciliation job behind it for those that never arrive. Here the question is a different one: who sent it.

That endpoint is on the public internet, and anyone can send it a request. If the handler trusts the body, anyone can mark their own order paid and eat for free. The provider solves this by signing each webhook: it computes an HMAC of the raw request body (and usually a timestamp) with a secret shared only with Dabba, and sends the result in a header. Dabba recomputes the HMAC and compares.

def verify(raw_body: bytes, header_sig: str, header_ts: str, secret: bytes):
    if abs(now() - int(header_ts)) > 300:          # 5 min: blocks replays
        return False
    expected = hmac_sha256(secret, header_ts.encode() + b"." + raw_body)
    return constant_time_equals(expected, header_sig)

Three details in those lines are where real integrations go wrong. The signature is over the raw bytes as received; a framework that parses the JSON and re-serialises it changes whitespace or key order and the signatures stop matching, and someone under pressure “temporarily” disables the check. The comparison is constant-time, so an attacker cannot learn the signature byte by byte from response timings. And the timestamp check, plus recording each event ID as processed, stops someone from replaying a genuine old webhook (say, a captured ₹418 payment) against a new order.

Dabba adds one more step for money: before marking an order paid, the handler asks the provider’s API for the payment’s status by its ID and checks the amount and the order reference. That costs an extra call per payment, about 42 a second in the dinner hour and 150 at the design target, and it turns a forged or misrouted webhook into a harmless no-op. The same idea applies to any message that triggers an irreversible effect: treat the message as a hint that something happened, and confirm it with the source.

Secrets, and the places they leak from

Dabba holds a handful of secrets that would be expensive to lose: the payment provider API key (which can issue refunds), the webhook signing secret, the SMS gateway key, database credentials, and the key that signs access tokens. Each needs a home, an owner and a way to be replaced.

The home is a secret manager (the cloud provider’s or a dedicated one), not a config file in the repository and not an environment variable baked into an image. Services fetch secrets at start-up with their own workload identity, so the notification service can read the SMS key and cannot read the payment key. That is least privilege, and it limits what a compromised notification service can do.

The mobile apps cannot hold secrets at all. Anything shipped in an APK or IPA can be extracted by anyone with the file. So the apps hold only keys that are designed to be public (a maps SDK key restricted to Dabba’s app signature, a payment provider’s publishable key), and anything privileged happens on Dabba’s servers. A design that needs the app to call the SMS gateway directly is a design with a public SMS key.

Replacement is the part teams skip until they need it. Suppose a developer commits the payment API key to a public repository by mistake. Deleting the commit does not help: scanners find keys in public repositories within minutes, and the key is in clones and caches. The only fix is rotation, and rotation must not cause an outage. The pattern is to support two valid secrets at once: create the new key, deploy services that use it, confirm traffic has moved, then revoke the old one. For the webhook secret, Dabba verifies against both old and new for the overlap period. A rotation that has been rehearsed takes an hour. One that has not tends to be done at 2 a.m. while the old key is being used to issue refunds to strangers.

Inside Dabba’s network, services talk over TLS and authenticate each other, typically with mutual TLS issued by a service mesh or the platform. The point is not that the network is hostile today, but that “internal” stops meaning “trusted” the first time any one service is compromised.

What would make us revisit this

These decisions fit a consumer app with three roles. They change when the shape of access changes. Corporate meal accounts, where a company admin sees all employees’ orders, add a new relationship and a new kind of tenant, and the single-function rule earns its keep. A support team of hundreds needs just-in-time access, field masking and audit review, not a role that reads everything. India’s Digital Personal Data Protection Act places duties on how long personal data is kept and what it is used for, which argues for deleting delivery addresses from old orders and for keeping analytics on pseudonymous IDs. And if Dabba ever stores card data itself, the compliance scope grows by an order of magnitude; the hosted payment page is worth a lot of product compromise to avoid that.

Equally, some controls are not worth it at Dabba’s scale. A full policy engine with its own language is overkill for four roles and a dozen resource types; a tested function per resource is easier to read. Revisit when the number of rules outgrows what one person can hold in their head.

So far each chapter has assumed that the services Dabba depends on answer promptly. The next chapter, on designing for failure, takes that away: the payment provider slows down at dinner peak, and we follow the slowness as it spreads, and design the timeouts, retries, breakers and fallbacks that stop it.