JS-240 · Lesson 6 of 12 · 27 min

Authorization and roles

▶ Video coming soon A video version of this lesson is on the way.

On Thursday, June 22, 2028, the session starts from where the last three ended. The partner service can now tell who is calling: a Westview staff member with a password, an Elm Street or Northside staff member with a work account, Northside's import program with a client credentials token, and soon the kitchen board. Gareth writes a new question on the whiteboard. "Now that you know who they are, what may each of them do?" That is authorization, and the OWASP list puts three of its failures in the top five.

This lesson sets out the partner service's roles and permissions, shows how role-based access control checks what kind of thing a caller may do, how object-level checks make sure the thing belongs to them, and how attribute-based rules handle conditions such as cut-off times. It finishes with an authorization matrix, a table of every caller against every action, which becomes a test that runs on every change. By the end, Mira has replaced the scattered if statements in her handlers with one policy module.

Authentication and authorization

The two words are easy to confuse and are often shortened to authn and authz. Authentication answers who is calling: it turns a cookie, a token or a key into a known caller. Authorization answers whether that caller may perform this action on this object, now. The partner service authenticates once, at the start of each request, and authorizes at every decision point, because the answer depends on what is being asked.

The status codes follow the same split. A request without valid credentials is answered with 401: the service does not know who is calling. A known caller who is not allowed to do something gets 403, except when the object belongs to another agency, which gets 404 so that nothing is revealed, as lesson 1 decided.

Roles and permissions

Role-based access control (RBAC) gives each caller a role and each role a set of permissions, named actions such as orders:read. Code checks for a permission, never for a role name, so that a new role can be added by editing a table instead of hunting through handlers for every place that says if role is kitchen-lead.

Roles and permissions in the partner service
RoleWho has itPermissions
partner-staffAgency stafforders:read, orders:write
partner-adminOne or two people per agency who approve their colleaguesorders:read, orders:write, staff:manage
kitchen-staffRosa's cooks and driversorders:read, days:read, orders:deliver
kitchen-leadRosaall kitchen permissions, plus days:manage and orders:override
board-deviceThe kitchen board tabletdays:read

Two rows deserve comment. The board device can read the day's orders but cannot change anything, not even mark an order delivered, because it is a tablet on a wall that anyone in the kitchen can touch. And only Rosa has orders:override, which lets her change an order after the agency's cut-off, for example when a shelter phones at 8:00 on the delivery morning with a correction.

JavaScript Example · Checking permissions, not role names
const ROLE_PERMS = {
  'partner-staff': ['orders:read', 'orders:write'],
  'partner-admin': ['orders:read', 'orders:write', 'staff:manage'],
  'kitchen-staff': ['orders:read', 'days:read', 'orders:deliver'],
  'kitchen-lead': ['orders:read', 'days:read', 'orders:deliver', 'days:manage', 'orders:override'],
  'board-device': ['days:read'],
};

function hasPermission(caller, perm) {
  const perms = ROLE_PERMS[caller.role];
  if (!perms) return false; // unknown role: deny by default
  if (caller.scopes && !caller.scopes.includes(perm)) return false; // a token can only narrow the role
  return perms.includes(perm);
}

const callers = [
  { name: 'Priya (Westview)', role: 'partner-staff' },
  { name: 'Rosa', role: 'kitchen-lead' },
  { name: 'kitchen board', role: 'board-device' },
  { name: 'Northside import', role: 'partner-staff', scopes: ['orders:read'] },
  { name: 'typo in config', role: 'kitchen_lead' },
];
for (const c of callers) {
  const checks = ['orders:write', 'days:manage', 'days:read'].map((p) => `${p}=${hasPermission(c, p) ? 'yes' : 'no'}`);
  console.log(c.name.padEnd(17), checks.join('  '));
}
Output
Priya (Westview)  orders:write=yes  days:manage=no  days:read=no
Rosa              orders:write=no  days:manage=yes  days:read=yes
kitchen board     orders:write=no  days:manage=no  days:read=yes
Northside import  orders:write=no  days:manage=no  days:read=no
typo in config    orders:write=no  days:manage=no  days:read=no

What this code does

Each role maps to a list of permissions, and hasPermission answers a question about one permission rather than about a role name. A token's scopes can only remove permissions, never add them, so Northside's import, whose token has only orders:read, cannot write even though its role could. A role the table does not know, such as one misspelt with an underscore, gets no permissions at all, which is the safe way to fail.

The last caller shows the principle of deny by default. A typing mistake in a configuration file must lock someone out, which is annoying and quickly noticed, rather than let them in, which may never be noticed. Every check in the policy module ends with deny if nothing has said allow.

Function level: protecting every route

OWASP's fifth risk, broken function level authorization, is about endpoints that check nothing, or check less than they should. It usually happens when an administrative endpoint is added for one person's convenience, such as a route that lets Rosa reset an agency's capacity, and the handler assumes that only the kitchen page links to it. Anyone who guesses the URL can call it. The partner service guards against this by declaring the required permission next to every route and refusing to start if any route has none.

JavaScript Example · Refusing to start with an unprotected route
const routes = [
  { method: 'GET', path: '/v1/menu', public: true },
  { method: 'GET', path: '/v1/orders', perm: 'orders:read' },
  { method: 'POST', path: '/v1/orders', perm: 'orders:write' },
  { method: 'PATCH', path: '/v1/orders/:id', perm: 'orders:write' },
  { method: 'GET', path: '/v1/kitchen/days/:date', perm: 'days:read' },
  { method: 'PUT', path: '/v1/kitchen/days/:date/capacity' },
  { method: 'GET', path: '/v1/staff', perm: 'staff:manage' },
];

function audit(routes) {
  const problems = routes.filter((r) => !r.public && !r.perm);
  for (const r of problems) console.log(`MISSING PERMISSION: ${r.method} ${r.path}`);
  return problems.length === 0;
}

const ok = audit(routes);
console.log(ok ? 'all routes protected' : 'refusing to start');
routes[5].perm = 'days:manage';
console.log(audit(routes) ? 'all routes protected' : 'refusing to start');
Output
MISSING PERMISSION: PUT /v1/kitchen/days/:date/capacity
refusing to start
all routes protected

What this code does

Every route either says it is public or names the permission it needs, and the audit lists any route that does neither. The capacity route was added without a permission, so the first audit refuses to start the server, which turns a quiet security hole into a loud start-up error. Once days:manage is added, the audit passes.

Object level: is this order theirs?

Permission checks answer what kind of action is allowed. They do not answer whether this particular order belongs to the caller. OWASP's first risk, broken object level authorization (BOLA), is a handler that checks orders:read and then loads whatever order id is in the URL. Westview's staff have orders:read, so without an object check, any of them could read Northside's orders by trying ids one after another.

The reliable fix is to make the check impossible to forget, by building it into the data access. The repository methods that partner callers use always take the caller and add the agency to the query, so there is no method that loads an order by id alone. A missing order and another agency's order look exactly the same: nothing comes back, and the handler answers 404.

JavaScript Example · Scoping every lookup to the caller
const orders = [
  { id: 41, agency: 'northside', deliveryDate: '2028-06-26', trays: 6 },
  { id: 42, agency: 'westview', deliveryDate: '2028-06-26', trays: 3 },
  { id: 43, agency: 'elm-seniors', deliveryDate: '2028-06-28', trays: 5 },
];

// The only ways to load orders for a partner caller: both are scoped to the caller's agency.
const repo = {
  findForCaller(caller, id) {
    return orders.find((o) => o.id === id && o.agency === caller.agency) ?? null;
  },
  listForCaller(caller) {
    return orders.filter((o) => o.agency === caller.agency);
  },
};

function getOrder(caller, id) {
  const order = repo.findForCaller(caller, id);
  return order ? `200 ${JSON.stringify(order)}` : '404 Not found';
}

const priya = { role: 'partner-staff', agency: 'westview' };
console.log(getOrder(priya, 42));
console.log(getOrder(priya, 41));
console.log(getOrder(priya, 99));
console.log('list:', repo.listForCaller(priya).map((o) => o.id));
Output
200 {"id":42,"agency":"westview","deliveryDate":"2028-06-26","trays":3}
404 Not found
404 Not found
list: [ 42 ]

What this code does

The repository has no function that finds an order by id alone, so a handler for partner callers cannot load another agency's order even by mistake. Asking for Northside's order 41 and for an order 99 that does not exist give the same 404, so trying ids reveals nothing. In the real service, the same condition is part of the SQL query, which matches on both the order id and the partner id, each passed as a parameter.

Three stacked checks for a request PATCH /v1/orders/41 from Priya at Westview. Function level: does the role have orders:write? Yes. Object level: does order 41 belong to Westview? No, it belongs to Northside, so the answer is 404. Attribute level, not reached: is the order still before its cut-off and in status received?
Authorization happens at three levels: the function, the object and its attributes.

Attributes: rules that depend on the situation

Some decisions depend on more than the role and the owner. An agency may change an order only while its status is received and only before the cut-off at noon two days before delivery. Rosa may change it after the cut-off. The board may never change it. Rules like these, which combine attributes of the caller, the object and the moment, are called attribute-based access control (ABAC). The partner service keeps them in one function, can(caller, action, order, now), so that every handler asks the same question in the same way.

JavaScript Example · policy.mjs
// policy.mjs: who may do what to which order
export const ROLE_PERMS = {
  'partner-staff': ['orders:read', 'orders:write'],
  'partner-admin': ['orders:read', 'orders:write', 'staff:manage'],
  'kitchen-staff': ['orders:read', 'days:read', 'orders:deliver'],
  'kitchen-lead': ['orders:read', 'days:read', 'orders:deliver', 'days:manage', 'orders:override'],
  'board-device': ['days:read'],
};

export function can(caller, action, order, now) {
  const perms = new Set(ROLE_PERMS[caller.role] ?? []);
  if (caller.scopes) for (const p of perms) if (!caller.scopes.includes(p)) perms.delete(p);
  const isKitchen = caller.role.startsWith('kitchen') || caller.role === 'board-device';
  if (order && !isKitchen && order.agency !== caller.agency) return 'not-found';
  switch (action) {
    case 'read': return perms.has('orders:read') ? 'allow' : 'deny';
    case 'change':
      if (!perms.has('orders:write') && !perms.has('orders:override')) return 'deny';
      if (order.status !== 'received') return 'deny';
      if (now >= order.cutoff && !perms.has('orders:override')) return 'deny';
      return 'allow';
    case 'deliver': return perms.has('orders:deliver') && order.status === 'received' ? 'allow' : 'deny';
    default: return 'deny';
  }
}

// a quick check from the command line
const order = { agency: 'northside', status: 'received', cutoff: 100 };
console.log(can({ role: 'partner-staff', agency: 'northside' }, 'change', order, 50));
console.log(can({ role: 'partner-staff', agency: 'northside' }, 'change', order, 150));
console.log(can({ role: 'kitchen-lead' }, 'change', order, 150));
console.log(can({ role: 'partner-staff', agency: 'westview' }, 'change', order, 50));

What this code does

The function first works out the caller's permissions, narrowed by any token scopes, and answers not-found straight away if a partner caller asks about another agency's order. A change needs a write or override permission, an order that is still received, and either a time before the cut-off or the override permission, which only Rosa has. Every branch that does not explicitly allow ends in deny, including actions the function has never heard of.

Running it
$ node policy.mjs
allow
deny
allow
not-found

Keeping the rules in one function has a practical benefit beyond tidiness. When the agencies asked in May whether they could change orders until 15:00 instead of noon, the whole discussion was about one comparison in one file, and the tests in the next section showed exactly which decisions the change would affect.

The authorization matrix

An authorization matrix lists every kind of caller against every action and writes down the expected answer. It is the clearest way to review a policy with people who do not read code, such as Rosa, and it turns directly into tests. Each row of the matrix becomes one test, so that a change to the policy that alters any decision fails a test and has to be explained.

JavaScript Example · policy.test.mjs
// policy.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { can } from './policy.mjs';

const order = { id: 41, agency: 'northside', status: 'received', cutoff: 100 };
const callers = {
  northsideStaff: { role: 'partner-staff', agency: 'northside' },
  westviewStaff: { role: 'partner-staff', agency: 'westview' },
  rosa: { role: 'kitchen-lead' },
  board: { role: 'board-device' },
  importer: { role: 'partner-staff', agency: 'northside', scopes: ['orders:read'] },
};
// [caller, action, time, expected]
const matrix = [
  ['northsideStaff', 'read', 50, 'allow'], ['northsideStaff', 'change', 50, 'allow'],
  ['northsideStaff', 'change', 150, 'deny'], ['northsideStaff', 'deliver', 50, 'deny'],
  ['westviewStaff', 'read', 50, 'not-found'], ['westviewStaff', 'change', 50, 'not-found'],
  ['rosa', 'change', 150, 'allow'], ['rosa', 'deliver', 150, 'allow'],
  ['board', 'read', 50, 'deny'], ['board', 'deliver', 50, 'deny'],
  ['importer', 'read', 50, 'allow'], ['importer', 'change', 50, 'deny'],
];

for (const [who, action, now, expected] of matrix) {
  test(`${who} ${action} at t=${now} -> ${expected}`, () => {
    assert.equal(can(callers[who], action, order, now), expected);
  });
}

What this code does

The matrix lists each caller, action and time with the answer the policy should give, and a loop turns each row into a named test with node:test. assert.equal from node:assert/strict compares the actual decision with the expected one. The run shows every case passing; a change to the policy that turned any deny into an allow would show up here as a named failure.

Running it
$ node --test --test-reporter=spec policy.test.mjs
✔ northsideStaff read at t=50 -> allow (0.2ms)
✔ northsideStaff change at t=50 -> allow (0.2ms)
✔ northsideStaff change at t=150 -> deny (0.2ms)
✔ northsideStaff deliver at t=50 -> deny (0.2ms)
✔ westviewStaff read at t=50 -> not-found (0.2ms)
✔ westviewStaff change at t=50 -> not-found (0.2ms)
✔ rosa change at t=150 -> allow (0.2ms)
✔ rosa deliver at t=150 -> allow (0.2ms)
✔ board read at t=50 -> deny (0.2ms)
✔ board deliver at t=50 -> deny (0.2ms)
✔ importer read at t=50 -> allow (0.2ms)
✔ importer change at t=50 -> deny (0.2ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 31.4

The matrix includes the cases people forget. Westview's staff get not-found for Northside's order whatever they try. The board is denied even reading an order through the order endpoint, because its only permission is days:read for the day view. And Northside's import program, whose token carries only orders:read, is denied changes even though its role would allow them. Mira also writes one test per role that calls every route without the right permission and checks for 403, so that function-level gaps are caught by the same suite.

Practical rules

  • Enforce on the server, every time. Hiding a button on the partner page is good design, but it is not a security control; the API must refuse the request anyway.
  • Check as close to the data as possible. Scoped repository methods and SQL conditions are harder to bypass than a check at the top of a handler.
  • Log denials. A burst of 404s for other agencies' order ids, or 403s from one account, is worth an alert.
  • Review the matrix when people change. When a partner admin leaves an agency, the agency's other admin removes them, and Theo's monthly review of the staff list catches anyone who was missed.

Worked problem

Reading a request against the policy

At 13:10 on Monday, June 26, Northside's staff member Dev tries to change order 41, for delivery on Wednesday, June 28, from 6 trays to 8. The cut-off for a Wednesday delivery is noon on Monday. Then Rosa, signed in as kitchen-lead, makes the same change after Dev phones her. What does the policy decide each time, and why?

Show solution
  1. Dev has the partner-staff role, which has orders:write, so the function-level check passes.
  2. Order 41 belongs to Northside, Dev's agency, so the object-level check passes.
  3. The order's status is received, but the time, 13:10 on Monday, is after the cut-off, noon on Monday, and Dev has no orders:override: deny, answered as 409 with a problem type for the cut-off.
  4. Rosa is kitchen-lead, so the agency check does not apply, and she has orders:override, so the cut-off does not stop her: allow. The change is logged with her name in updatedBy.

Answer: Dev's change is refused because the cut-off has passed; Rosa's identical change is allowed because she holds the override permission. Both decisions come from the same function, and both are rows in the matrix.

Common mistakes

  • MistakeChecking the role name in each handler.

    InsteadCheck permissions, and keep the role-to-permission table in one place.

  • MistakeLoading an order by id and then checking orders:read.

    InsteadScope every lookup to the caller's agency, so other agencies' orders are never loaded.

  • MistakeHiding the kitchen buttons on the partner page.

    InsteadHiding is not protection. The API must refuse the request.

  • MistakeAllowing anything the policy does not mention.

    InsteadDeny by default; allow only what a rule allows.

  • MistakeAnswering 403 for another agency's order.

    InsteadAnswer 404, so that the order's existence is not confirmed.

Summary and key terms

  • Authentication finds out who is calling; authorization decides whether that caller may do this action to this object now.
  • The partner service uses role-based access control with permissions such as orders:read, checks permissions rather than role names, narrows them by token scopes and denies by default.
  • Every route declares the permission it needs, and the service refuses to start if one does not, which prevents broken function level authorization.
  • Repository methods for partner callers always include the caller's agency, so other agencies' objects are never loaded and are answered with 404, which prevents broken object level authorization.
  • Attribute-based rules such as the cut-off and order status live in one policy function.
  • An authorization matrix of callers, actions and expected answers documents the policy and runs as tests on every change.
Authentication
Finding out who is calling.
Authorization
Deciding whether a known caller may perform an action on an object.
RBAC
Role-based access control: permissions granted through roles.
Permission
A named action that a role allows, such as orders:write.
Deny by default
Refusing anything that no rule explicitly allows.
BFLA
Broken function level authorization: an endpoint that does not check whether the caller may use it.
ABAC
Attribute-based access control: rules that combine attributes of the caller, the object and the situation.
Authorization matrix
A table of callers, actions and expected decisions, used for review and tests.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. What is the difference between a 401 and a 403?

    Show answer

    401: the caller is not known; 403: the caller is known but not allowed.

  2. Why does code check orders:write rather than role === 'partner-staff'?

    Show answer

    So roles can be added or changed in one table without editing handlers.

  3. How does the partner service make BOLA hard to introduce?

    Show answer

    Partner repository methods always include the caller's agency in the lookup.

  4. What can a token's scopes do to a role's permissions?

    Show answer

    Only remove them, never add.

  5. What does each row of the authorization matrix become?

    Show answer

    A test that checks the policy's decision.

Try it yourself

Deny by default

Complete decide(rules, caller, action) so that it returns allow only if some rule in rules matches both the caller's role and the action, and deny otherwise.

A rule is an object like { role: 'kitchen-staff', action: 'deliver' }. A rule whose role is * matches every role, but only for its action. An unknown action must be denied.

function decide(rules, caller, action) {
  for (const r of rules) {
    if (r.role === caller.role) return 'allow';
  }
  return 'allow';
}

const rules = [
  { role: 'kitchen-staff', action: 'deliver' },
  { role: 'partner-staff', action: 'change' },
  { role: '*', action: 'read-menu' },
];
console.log(decide(rules, { role: 'kitchen-staff' }, 'deliver'));
console.log(decide(rules, { role: 'kitchen-staff' }, 'change'));
console.log(decide(rules, { role: 'board-device' }, 'read-menu'));
console.log(decide(rules, { role: 'board-device' }, 'deliver'));
console.log(decide(rules, { role: 'partner-staff' }, 'delete-everything'));

Try it yourself

Scope the list to the caller

Complete ordersFor(caller, orders) so that partner callers (roles starting with partner-) get only their own agency's orders, and kitchen callers (roles starting with kitchen-) get every order.

Any other role, such as board-device, gets an empty list. Print the ids only.

function ordersFor(caller, orders) {
  return orders;
}

const orders = [
  { id: 41, agency: 'northside' }, { id: 42, agency: 'westview' },
  { id: 43, agency: 'elm-seniors' }, { id: 44, agency: 'westview' },
];
for (const caller of [
  { role: 'partner-staff', agency: 'westview' },
  { role: 'partner-admin', agency: 'northside' },
  { role: 'kitchen-lead' },
  { role: 'board-device' },
]) console.log(caller.role.padEnd(14), ordersFor(caller, orders).map((o) => o.id).join(',') || '(none)');

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz