15 min read
RBAC roles and permissions: who can do what
In one sentence: With RBAC, each account has a role (customer, delivery or admin) and each role, a list of permissions; the code asks about permissions, never about roles. And that's not enough: every route that receives an id also checks whose that data is, so a customer sees their own orders and not someone else's.
What you will learn
- Organize authorization with roles and permissions, and check permissions in the code, not role names.
- Check whose each order is, to close the most common flaw in APIs (BOLA).
- Choose between 401, 403 and 404 when someone can't do what they ask.
- Give each role and each key only the permissions it needs, and explain why a security hole is closed without warning.
Before you start, read: 04-oauth.md
The problem
Section titled “The problem”At the end of lesson 4, “OAuth”, the shop already knows who it’s talking to: Marta signs in with her password or with the provider, and Fast Delivery, with its key. But knowing who you are hasn’t changed what you can do. The API still hands all the orders to anyone, and creating products still asks for the shared ADMIN_TOKEN from the introduction.
Imagine that Carmen, a customer, looks at her order at /v2/orders/27 and tries 26. If the API answers, Carmen is reading Marta’s order. She hasn’t broken anything: she has changed a number.
This isn’t a textbook case. In 2018, an API of the United States Postal Service let any user with a session look up other users’ data: about 60 million accounts (KrebsOnSecurity). How does the shop decide what each person can do, and whose each piece of data is?
The analogy
Section titled “The analogy”The analogy
In a company, keys aren’t handed out person by person: they’re handed out by job. Whoever joins as a courier gets the courier key ring, which opens the warehouse and the loading dock, but not the safe. Whoever joins as an accountant gets a different one. The job is the role; each key on the ring, a permission.
And each employee has a locker. They’re all the same and numbered, and your key opens yours, not the one next to it. Being able to open lockers isn’t enough: it has to be yours.
Where the analogy breaks down
- A key ring once handed out is hard to get back. In the shop, the role lives in the database and is looked up on every request: if you change someone’s role, their next request already notices.
- Someone else’s locker can be seen, even if it can’t be opened. The API goes further: to whoever asks for someone else’s order, it answers that it doesn’t exist.
How it really works
Section titled “How it really works”Three roles, and a list of permissions for each one
Section titled “Three roles, and a list of permissions for each one”Start with what each one should be able to do in the shop:
| Customer (Marta, Carmen) | Delivery (Fast Delivery’s key) | Admin (Ana, Luis) | |
|---|---|---|---|
| Place orders | Yes | No | No |
| See orders | Their own | All | All |
| Change or cancel orders | Their own | No | All |
| Mark an order as shipped | No | Yes | Yes |
| Create and delete products | No | No | Yes |
Each row is a permission and each column, a role. Organizing authorization this way is called RBACRBAC stands for Role-Based Access Control.A way of organizing authorization in which each account has a role, like customer or administrator, and each role has a list of permissions. To change what someone can do, you change their role, not their permissions one by one.Go to definition, role-based access control. In the code, src/permissions.ts:
export type Role = 'customer' | 'delivery' | 'admin';
export type Permission = | 'orders:create' | 'orders:view-own' | 'orders:view-all' | 'orders:change-own' // change the quantity and cancel | 'orders:change-all' | 'orders:ship' // mark a paid order as shipped | 'products:manage'; // create and delete products
// Each role, with just what its job needs (least privilege): the delivery company sees the orders// and marks them as shipped, but it doesn't create products or cancel anything. If its key leaks,// the damage stays at that.const PERMISSIONS: Record<Role, readonly Permission[]> = { customer: ['orders:create', 'orders:view-own', 'orders:change-own'], delivery: ['orders:view-all', 'orders:ship'], admin: ['orders:view-all', 'orders:change-all', 'orders:ship', 'products:manage'],};RoleandPermissionare TypeScript types (lesson 3 of Phase 3): if you write'order:view-all', without thes,npm run checkfails.- The names,
resource:action, are a common habit: they read on their own. PERMISSIONSis the table above: each role, with its list.
Admin doesn’t have orders:create: in this shop, an order always belongs to a customer, and Ana doesn’t shop with her admin account.
The code asks about permissions, not roles
Section titled “The code asks about permissions, not roles”The tempting thing is to write if (role !== 'admin') in every route. The day a new role arrives, “customer support,” which must see all the orders without touching the products, you’ll have to find every if and decide one by one. With permissions, you add a line to PERMISSIONS, and the routes don’t change.
// The role of whoever makes the request: the session person's or the API key's.const roleOf = (c: Context<Env>): Role | undefined => (c.var.user ?? c.var.apiKey)?.role;
// The code asks about permissions, never about roles: "can they see all the orders?", and not "are// they admin?". If tomorrow there's a new role (customer support), giving it its permissions here// is enough.export function can(c: Context<Env>, permission: Permission): boolean { const role = roleOf(c); return role !== undefined && PERMISSIONS[role].includes(permission);}roleOftakes the role from the session’s account or, if there’s no session, from the API key.cananswers yes or no: does their role’s list include that permission?
Each route says what it needs with requirePermission, a MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition:
// A middleware for each route: it lets through if they have any of those permissions. If it doesn't// know who you are, 401 ("identify yourself"); if it knows and you can't, 403 ("I know who you// are, and no").export const requirePermission = (...permissions: Permission[]): MiddlewareHandler<Env> => async (c, next) => { if (roleOf(c) === undefined) return notIdentified(c); if (!permissions.some((permission) => can(c, permission))) { return httpProblem(c, 403, 'Your account does not have permission for this'); } await next(); };...permissionsaccepts one or several, and having any of them is enough. The routes that show orders userequirePermission('orders:view-own', 'orders:view-all').- In
src/contract.ts, each route carries it in its list:middleware: [requirePermission('products:manage')]. It goes before validating the body, like the guard in the middleware lesson.
401, 403 or 404
Section titled “401, 403 or 404”requirePermission gives two different responses, the ones from the status codes lesson in Phase 2:
- With no identity,
401, withWWW-Authenticate: the same response fromrequireIdentityyou saw in lesson 2, now in a function,notIdentified(src/middleware/session.ts), which both use. Identifying yourself can fix it. - With an identity and no permission,
403, withoutWWW-Authenticate: identifying yourself again changes nothing.
And there’s a third case, which requirePermission doesn’t see: the order exists, but it belongs to someone else. There the shop answers 404, because the 404 also hides things: a 403 would confirm to Carmen that order 26 exists.
Each customer, their own orders: BOLA
Section titled “Each customer, their own orders: BOLA”requirePermission lets Carmen through on GET /v2/orders/:id, because she has orders:view-own. But which order is she asking for? The role says what kind of things you can do; only the data says whose it is. Forgetting that second check is called BOLABOLA stands for Broken Object Level Authorization.The flaw in an API that lets you see or change someone else’s data, like an order or an invoice, just by changing its number in the URL. The API checks who you are, but not whether that data is yours. It’s very common: it tops OWASP’s list of API flaws.Go to definition (Broken Object Level Authorization).
It’s the first in the OWASPOWASP stands for Open Worldwide Application Security Project.An open community, backed by a nonprofit foundation, that publishes free guides and tools for building secure web applications. Its best-known document is the OWASP Top 10, the list of the ten most serious risks for web applications.Go to definition API Security Top 10 of 2023, the list of the most serious flaws in APIs. The fifth, Broken Function Level Authorization, is the other half: a route without its requirePermission.
First, each order needs an owner. It’s the second part of migration 009:
-- Whose each order is. It can be missing (NULL) in the orders that were already there: they were-- placed when the shop had no accounts, and nobody knows whose they are. From now on, each new-- order carries its own.ALTER TABLE orders ADD COLUMN customer_id integer REFERENCES users (id);
-- A customer's list of orders, from newest to oldest: the same order as migration 003's index,-- but starting with the customer.CREATE INDEX orders_by_customer ON orders (customer_id, created_at DESC, id DESC);customer_idcan beNULL: the 25 sample orders were placed when the shop had no accounts, and nobody knows whose they are. Only admin and delivery see them.- The index starts with the customer: a customer’s list comes out fast, as in the indexes lesson.
Then, every route that receives an id checks it, in src/v2.ts:
// An order, if whoever asks can see it or change it: with the "all" permission, any; if not, only// one of their own. It's the check most APIs forget (BOLA, the first in the OWASP API Top 10):// asking for /v2/orders/7, then 8, 9… and seeing other people's. If it isn't theirs, the route// answers 404, as if it didn't exist: a 403 would tell them that order exists.async function visibleOrder(c: Context<Env>, id: number, all: Permission) { const order = await findOrder(id); if (order === undefined) return undefined; if (can(c, all) || order.customerId === c.var.user?.id) return order; return undefined;}
v2.openapi(contract.getOrder, async (c) => { const order = await visibleOrder(c, c.req.valid('param').id, 'orders:view-all'); if (!order) return httpProblem(c, 404, 'No such order'); return c.json(order, 200);});- With the “all” permission, any order; if not, only one whose
customerIdis the session’s. - Someone else’s comes back as
undefined, just like one that doesn’t exist, and the route answers the same404. - The same function is used to see, change and cancel an order, and for its event stream: one check, in a single place.
The list doesn’t receive an id, but it filters too:
// A breaking change, on purpose and without warning: until lesson 5, anyone could see all the// orders of all the customers. A change like this used to be announced first (Deprecation and// Sunset, Phase 4), but this was a security hole: it's closed as soon as it's seen, in /v1 too.// The convenience of whoever used the API never weighs more than the customers' data.v2.openapi(contract.listOrders, async (c) => { const { limit, cursor, offset, status } = c.req.valid('query'); // With orders:view-all, all of them; if not (a customer, with view-own), only their account's. const customerId = can(c, 'orders:view-all') ? undefined : c.var.user!.id;customerId stays undefined for whoever sees all of them; for a customer, it’s their id, and src/pagination.ts adds the condition customer_id = … to the query.
When an order is created, the owner comes from the session (c.var.user), never from the request body: if the JSON could carry a customerId, anyone could place orders in someone else’s name.
Goodbye to the ADMIN_TOKEN: being an admin is an account’s role
Section titled “Goodbye to the ADMIN_TOKEN: being an admin is an account’s role”The first part of the migration gives a role to each account and to each key:
-- Each person has a role: customer (the usual: whoever signs up), delivery or admin. DEFAULT: the-- accounts that were already there, and the new ones, are customers'. Making someone admin is an-- UPDATE by hand, done by another admin person: never something asked for through the API.ALTER TABLE users ADD COLUMN role text NOT NULL DEFAULT 'customer' CHECK (role IN ('customer', 'delivery', 'admin'));
-- A key belongs to a program: delivery (just what the delivery company needs) or admin. Never-- customer: a program has no orders of its own.ALTER TABLE api_keys ADD COLUMN role text NOT NULL DEFAULT 'delivery' CHECK (role IN ('delivery', 'admin'));DEFAULT 'customer': Marta, and whoever signs up tomorrow, are customers.CHECKonly accepts the roles that exist, and a key is nevercustomer: a program has no orders of its own.- Making someone an admin is an
UPDATEby hand, never an API route.
ADMIN_TOKEN disappears from src/config.ts and .env.example, and src/middleware/admin-only.ts goes with it. The introduction’s problems go with it too: Ana and Luis each sign in with their own account, so the shop knows who makes each request; taking access away from one of them is changing their role, without touching the other; and the delivery key isn’t an admin key.
Least privilege, for the delivery key too
Section titled “Least privilege, for the delivery key too”Fast Delivery needs to see the orders and mark them as shipped, and nothing else. For that it has a new route, POST /v2/orders/{id}/shipment, with requirePermission('orders:ship').
If its key leaks, in a log or in a repository, whoever finds it sees orders and marks them as shipped, but doesn’t create products or cancel anything. It’s the Least privilegeThe rule of giving each user and each program only the permissions it needs, and no more. If something fails or someone gets in where they shouldn’t, the damage stays within the little it could touch.Go to definition from the permissions lesson in Phase 1, applied to the API. Every extra permission is possible damage if the key leaks.
It could be tightened further: delivery also sees the pending orders, which it doesn’t need. A stricter shop would give it only the paid ones.
A breaking change, on purpose
Section titled “A breaking change, on purpose”Until today, GET /v2/orders answered anyone. From this lesson on, with no identity, it answers 401, and a program that listed orders without identifying itself stops working: a Breaking changeA change in an API that makes a client that used to work fail, without anyone touching it. Removing or renaming a field, changing its type or its unit, or requiring a new piece of data breaks clients; adding an optional field doesn’t.Go to definition.
In the versioning lesson you learned to warn first, with Deprecation and Sunset, and to leave months of margin. Here there’s no warning, and /v1, which uses the same routes, closes the same way. The warning protects the convenience of whoever uses the API; here, what’s at stake is the customers’ data, and every day of warning is a day when anyone can read all the orders.
A security hole is closed as soon as it’s seen. Afterwards, the partners are told and given a way to identify themselves: Fast Delivery already has its key.
Try it
Section titled “Try it”The goal: make the same requests as five identities (nobody, Marta, Carmen, Fast Delivery and Ana) and check that each one sees and does only what’s theirs.
You’re going to try to read another person’s order in your own shop, on localhost. Doing it on a system that isn’t yours, without permission, is a crime.
Write the code
Section titled “Write the code”You start from your project from lesson 4, “OAuth”:
- Create
src/permissions.tsanddb/migrations/009-roles.sql. - In
src/schema.ts,roleinusersand inapiKeys, andcustomerIdinorders. Generate drizzle-kit’s snapshot withnpm run db:generate -- --name=roles, as in lesson 1. - In
src/contract.ts, replaceadminOnlywithrequirePermission, addrequirePermissionto the order routes and theshipOrderroute. Insrc/v2.ts,visibleOrder, the list and the shipment. Insrc/v1.ts,requirePermission. - Delete
src/middleware/admin-only.ts,ADMIN_TOKENfromsrc/config.tsand its line from your.env: a secret that no longer protects anything shouldn’t be left lying around.
Copy the rest from the step (the role in users.ts, sessions.ts and api-keys.ts, customerId in data.ts and pagination.ts, the role and the customerId in the responses of schemas.ts, notIdentified in middleware/session.ts and the per-account key in middleware/idempotency.ts). The accounts with their role and the tests come in its folder:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/28-roles.tar.gztar -xzf 28-roles.tar.gzcd shop-apicp ../28-roles/db/accounts.sql ../28-roles/db/seed.sql db/cp ../28-roles/test/*.ts test/1. The roles migration
npm run db:migrateWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 009-roles.sqlThe outputs are from Node 26.11.1 and PostgreSQL 18; your ids, keys and times will be different.
2. The practice accounts, with their role
npm run db:seedpsql -d shop -c 'SELECT id, email, role FROM users ORDER BY id;'What you will see:
> shop-api@1.0.0 db:seed> node --env-file-if-exists=.env scripts/seed.ts
Practice accounts ready (their passwords are in the README)The database already has products: the sample ones are not loaded againid | email | role----+--------------------+----------1 | marta@example.com | customer3 | ana@shop.example | admin4 | luis@shop.example | admin5 | carmen@example.com | customer6 | pablo@example.com | customer(5 rows)Marta is the account from lesson 1, a customer by default. The other four are the practice accounts, with their passwords in the project’s README: Ana and Luis, admin; Carmen and Pablo, customers. If you already had them, the command only gives them their role.
Number 2 is missing: Marta’s repeated sign-up in lesson 1 used it up. PostgreSQL hands out the number before trying to save the row, and doesn’t reuse it even if the INSERT fails. If your ids are different, use yours.
3. This lesson's tests
npm test -- test/roles.test.tsWhat you will see:
> shop-api@1.0.0 test> node --env-file=test/.env --test --test-concurrency=1 test/roles.test.ts
✔ the list of orders: without an identity, 401; a customer sees their own; admin and delivery, all (116.404942ms)✔ someone else's order: 404, as if it did not exist, its event stream too (15.28183ms)✔ changing or cancelling someone else's order: 404; their own, yes; admin, any (11.412119ms)✔ placing an order needs a customer's session, and the order belongs to whoever places it (7.180839ms)✔ the same Idempotency-Key from two customers: each one, their own order (8.249044ms)✔ the delivery company marks a paid order as shipped, and nothing else (11.286609ms)✔ admin manages the products: a customer or delivery, 403 without WWW-Authenticate (7.268679ms)✔ /v1 has the same protections (9.832832ms)ℹ tests 8ℹ suites 0ℹ pass 8ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 654.102242Each test makes the same request as several identities and compares the codes. If one fails, its name says which rule isn’t met.
Sign in as each one
Section titled “Sign in as each one”Start the API with npm start and, in another terminal, open a session for Marta, Carmen and Ana, each in her own file:
4. Three sessions
curl -s -w '\n' -c marta.txt --json '{"email":"marta@example.com","password":"a long sentence only I know"}' localhost:3000/v2/sessioncurl -s -w '\n' -c carmen.txt --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/sessioncurl -s -w '\n' -c ana.txt --json '{"email":"ana@shop.example","password":"ana-practice-2026"}' localhost:3000/v2/sessionWhat you will see:
{"id":1,"email":"marta@example.com","role":"customer"}{"id":5,"email":"carmen@example.com","role":"customer"}{"id":3,"email":"ana@shop.example","role":"admin"}The response now carries the role. The fifth identity is Fast Delivery’s key from lesson 3: save it in this terminal with KEY=, followed by yours.
With no identity: the breaking change
Section titled “With no identity: the breaking change”5. The list of orders, without signing in
curl -s -i -w '\n' 'localhost:3000/v2/orders?limit=3'curl -s -o /dev/null -w '%{http_code}\n' localhost:3000/v1/ordersWhat you will see:
HTTP/1.1 401 Unauthorizedcontent-type: application/problem+jsonvary: Originwww-authenticate: Bearer realm="shop-api"x-request-id: 70c2b75d-f53b-4f8f-92aa-1547560aa166content-length: 117Date: Wed, 14 Oct 2026 04:47:30 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Sign in, or identify yourself with your API key"}401It’s the first request from the introduction, which back then returned three orders. Now, 401 with its www-authenticate. The last line is /v1: closed the same way.
Each customer, their own orders
Section titled “Each customer, their own orders”Marta and Carmen place an order each:
6. Two new orders
curl -s -w '\n' -b marta.txt --json '{"productId":2,"quantity":1}' localhost:3000/v2/orderscurl -s -w '\n' -b carmen.txt --json '{"productId":1,"quantity":2}' localhost:3000/v2/ordersWhat you will see:
{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-14T04:47:30.251Z","customerId":1}{"id":27,"productId":1,"quantity":2,"status":"pending","createdAt":"2026-10-14T04:47:30.260Z","customerId":5}Look at customerId: the body didn’t send it, it comes from the session. If you get a 401, the cookie file isn’t in this folder.
7. Each one's list
curl -s -w '\n' -b marta.txt localhost:3000/v2/orderscurl -s -w '\n' -b carmen.txt localhost:3000/v2/ordersWhat you will see:
[{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-14T04:47:30.251Z","customerId":1}][{"id":27,"productId":1,"quantity":2,"status":"pending","createdAt":"2026-10-14T04:47:30.260Z","customerId":5}]The same route, two responses: each one sees her own. The 25 sample orders don’t show up, because they belong to nobody.
If your database was empty when you ran npm run db:seed, db/seed.sql gave them owners (the odd ones, Carmen; the even ones, Pablo), and Carmen will see hers too.
Now Carmen does what the introduction did: she tries numbers.
8. Carmen tries numbers
curl -s -w '\n' -b carmen.txt localhost:3000/v2/orders/26curl -s -o /dev/null -w '%{http_code} ' -b carmen.txt 'localhost:3000/v2/orders/[24-27]'; echoWhat you will see:
{"type":"about:blank","title":"Not Found","status":404,"detail":"No such order"}404 404 404 200Order 26, Marta’s, gets the same 404 as an order that doesn’t exist. Going from 24 to 27, only hers answers. ; echo adds the final line break.
The delivery key: just enough
Section titled “The delivery key: just enough”9. All the orders, and an unpaid one
curl -s -w '\n' -H "Authorization: Bearer $KEY" 'localhost:3000/v2/orders?limit=3'curl -s -w '\n' -H "Authorization: Bearer $KEY" -X POST localhost:3000/v2/orders/26/shipmentWhat you will see:
[{"id":27,"productId":1,"quantity":2,"status":"pending","createdAt":"2026-10-14T04:47:30.260Z","customerId":5},{"id":26,"productId":2,"quantity":1,"status":"pending","createdAt":"2026-10-14T04:47:30.251Z","customerId":1},{"id":25,"productId":2,"quantity":2,"status":"pending","createdAt":"2026-10-08T09:00:00.000Z","customerId":null}]{"type":"https://shop.example/problems/order-status","title":"The order's status doesn't allow it","status":409,"detail":"The order is pending: only a paid one is shipped"}Delivery sees everyone’s orders, including 25, which has no owner. But Marta’s order can’t be shipped: it isn’t paid yet. If the first line is a 401, KEY is empty.
Have the gateway from the webhooks lesson pay for it, and try again:
10. Paid and shipped
npm run gateway -- 26curl -s -w '\n' -H "Authorization: Bearer $KEY" -X POST localhost:3000/v2/orders/26/shipmentWhat you will see:
> shop-api@1.0.0 gateway> node --env-file-if-exists=.env scripts/payment-gateway.ts 26
→ POST /v2/webhooks/payments {"id":"evt_04878fb2-09e2-4c01-940d-3c1c9da73441","type":"payment.completed","orderId":26}← 200 {"received":"evt_04878fb2-09e2-4c01-940d-3c1c9da73441","repeated":false}{"id":26,"productId":2,"quantity":1,"status":"shipped","createdAt":"2026-10-14T04:47:30.251Z","customerId":1}The signed webhook marks 26 as paid, and now the shipment works: shipped. Marta will see it like that in her list.
11. What isn't its job
curl -s -i -w '\n' -H "Authorization: Bearer $KEY" --json '{"name":"Sticker","priceCents":150}' localhost:3000/v2/productscurl -s -w '\n' -H "Authorization: Bearer $KEY" -X POST localhost:3000/v2/orders/27/cancellationWhat you will see:
HTTP/1.1 403 Forbiddencontent-type: application/problem+jsonvary: Originx-request-id: 0fd26f28-2412-46e1-b966-cdbf22034bedcontent-length: 113Date: Wed, 14 Oct 2026 04:47:30 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"about:blank","title":"Forbidden","status":403,"detail":"Your account does not have permission for this"}{"type":"about:blank","title":"Forbidden","status":403,"detail":"Your account does not have permission for this"}Creating a product and cancelling an order: 403 both times. Look at what’s missing from the headers: there’s no www-authenticate, because the shop knows who it is.
The same request, five identities
Section titled “The same request, five identities”12. Order 26, for each one
curl -s -o /dev/null -w 'nobody %{http_code}\n' localhost:3000/v2/orders/26curl -s -o /dev/null -w 'marta %{http_code}\n' -b marta.txt localhost:3000/v2/orders/26curl -s -o /dev/null -w 'carmen %{http_code}\n' -b carmen.txt localhost:3000/v2/orders/26curl -s -o /dev/null -w 'delivery %{http_code}\n' -H "Authorization: Bearer $KEY" localhost:3000/v2/orders/26curl -s -o /dev/null -w 'ana %{http_code}\n' -b ana.txt localhost:3000/v2/orders/26What you will see:
nobody 401marta 200carmen 404delivery 200ana 200Three different responses for the same URL: “identify yourself,” “here it is” and “it doesn’t exist.” The text in front of %{http_code} only labels each line.
Challenge: repeat the five lines with POST /v2/products and the introduction’s Sticker body. What code does each one get? If someone creates it, delete it with their session.Show answer
Only Ana creates it:
nobody 401marta 403carmen 403delivery 403ana 201Without -o /dev/null, Ana’s line shows the product, {"id":6,"name":"Sticker","priceCents":150,"stock":0,"categories":[]}: number 6, because 5 was the introduction’s Sticker. curl -s -w '%{http_code}\n' -X DELETE -b ana.txt localhost:3000/v2/products/6 deletes it with a 204. It’s what the ADMIN_TOKEN used to do, now with Ana’s account.
When you’re done, delete the files with rm marta.txt carmen.txt ana.txt: they’re open sessions.
You have already seen it
Section titled “You have already seen it”- A shared document. When you share a document in Google Drive you choose “Viewer”, “Commenter” or “Editor”: a role, not a list of permissions for each person.
- Linux groups. In the permissions lesson in Phase 1, a file gives permissions to a group, and adding someone to the group is enough: the same idea as a role.
- Your order number in the URL. Many shops show
/orders/12345. If changing that number showed another person’s order, it would be BOLA: don’t try it on other people’s sites.
Common mistakes
Section titled “Common mistakes”- Checking permissions only in the frontend, by hiding the button: anyone can call the API with
curl. - Checking that there’s a session and forgetting whose the data is. Every route that receives an id needs its check, including the events one and the
/v1one. - Taking the owner from the request body instead of from the session.
- Asking about roles in the code (
role === 'admin') instead of about permissions. - Answering
403to someone else’s order, which confirms it exists, or401to someone who is identified and isn’t allowed. - Sharing something stored by key between accounts. With the same
Idempotency-Key, Pablo would get Carmen’s order; that’s whyidempotency.tsstores each key with its account. - Relying on random ids instead of checking. An id that’s hard to guess helps, but it ends up in links, logs and screenshots.
- Giving a program more permissions “just in case.”
Summary
Section titled “Summary”- Authorization decides what someone who is already identified can do. With RBAC, each account has a role and each role, a list of permissions.
- The code asks about permissions (
requirePermission('products:manage')), never about role names: a new role is one more line in the table. - The role isn’t enough: every route that receives an id checks whose the data is. Forgetting it is BOLA, the first flaw in the OWASP API Security Top 10.
- With no identity,
401; identified and not allowed,403; someone else’s data,404, so as not to confirm it exists. - Each role and each key, with just what it needs. And a security hole is closed as soon as it’s seen, even if it breaks a client of the API.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- API1:2023 Broken Object Level Authorization (OWASP): BOLA, with examples of attacks and how to prevent it.
- OWASP API Security Top 10, 2023 (OWASP): the ten most serious flaws in APIs.
- Authorization Cheat Sheet (OWASP): least privilege, deny by default and check on every request.
- USPS Site Exposed Data on 60 Million Users (KrebsOnSecurity): a real case of BOLA.