Module 5 · Authorization before Cedar
5.5 Role explosion and the access matrix as a test
Turn the access matrix into one table-driven test, add a separation-of-duties rule, and measure where authorization logic now lives and what the next requirement would cost.
Starting point
Every route is authorized by can() in src/authz/rules.js, and every list by visibleBuildingCondition in src/models/scope.js. Tests for individual rows of the access matrix are spread over several files.
Outcome
test/access-matrix.test.jsstates the whole matrix from lesson 5.1 in one table. It is the contract that Cedar must satisfy in Module 6.- Nobody can approve an inspection they created.
- You can point to every place that encodes authorization, and explain why a policy engine helps.
The problem
We have tests for many cells of the matrix, but not in one place, and some cells are not tested at all. When we replace the engine underneath can() in the next module, we want one file that says: this is the behaviour, check it all. Let's write that file and see whether today's code passes it.
Build it
1. The matrix as data
Create test/access-matrix.test.js. Each row is one request and the expected status for each user. The order of users in a row is the order of the requests, so for actions that change data the users who should be refused go first, and the user who should succeed goes last.
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const USERS = ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi'];const agents = {}; before(async () => { await resetDatabase(); for (const name of USERS) agents[name] = await loginAs(name);});after(() => pool.end()); const reportAtBuilding20 = { title: 'Bins left by the back door', building_id: '20', priority: 'medium', occurred_at: '2026-11-22T09:00' }; // The access matrix from lesson 5.1, one row per request.export const MATRIX = [ { name: 'view issue 101 (building 10)', send: (a) => a.get('/issues/101'), expect: { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } }, { name: 'edit issue 101', send: (a) => a.get('/issues/101/edit'), expect: { alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } }, { name: 'view issue 103 (building 20)', send: (a) => a.get('/issues/103'), expect: { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } }, { name: 'edit issue 103 (reported by dave)', send: (a) => a.get('/issues/103/edit'), expect: { alice: 403, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } }, { name: 'report an issue at building 20', send: (a) => a.post('/issues').type('form').send(reportAtBuilding20), expect: { alice: 400, bob: 400, nora: 400, ravi: 400, carol: 303, dave: 303 } }, { name: 'view issue 105 (building 30)', send: (a) => a.get('/issues/105'), expect: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 } }, { name: 'view issue 106 (building 40, reported by bob)', send: (a) => a.get('/issues/106'), expect: { alice: 404, bob: 404, carol: 404, dave: 404, nora: 404, ravi: 404 } }, { name: 'approve inspection 201 (created by dave)', send: (a) => a.post('/inspections/201/approve'), expect: { bob: 404, dave: 403, nora: 404, ravi: 404, alice: 303 } }, { name: 'approve inspection 202 (created by alice)', send: (a) => a.post('/inspections/202/approve'), expect: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 } }, { name: 'update organisation 1', send: (a) => a.get('/organisations/1/edit'), expect: { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } },]; for (const row of MATRIX) { test(row.name, async () => { const actual = {}; for (const name of Object.keys(row.expect)) { actual[name] = (await row.send(agents[name])).status; } assert.deepEqual(actual, row.expect); });} test('issues in each user\'s list come only from the expected buildings', async () => { const expected = { alice: [10, 20], bob: [30], carol: [10, 20], dave: [10, 20], nora: [], ravi: [] }; for (const [name, buildings] of Object.entries(expected)) { const ids = []; for (let page = 1; page <= 4; page++) { const html = (await agents[name].get(`/issues?page=${page}`)).text; ids.push(...[...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]))); } const { rows } = await pool.query('SELECT DISTINCT building_id FROM issues WHERE id = ANY($1) ORDER BY building_id', [ids]); assert.deepEqual(rows.map((r) => r.building_id), buildings, name); }});MATRIXis data. Adding a cell is adding a line, and the failure message shows the whole row, expected against actual.test()is called in a loop, once per row, so each row is reported as its own test.MATRIXis exported. Nothing imports it yet; Module 8 does.
Run and inspect
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (468.230458ms)
✔ edit issue 101 (19.410083ms)
✔ view issue 103 (building 20) (15.573292ms)
✔ edit issue 103 (reported by dave) (24.582208ms)
✔ report an issue at building 20 (28.852458ms)
✔ view issue 105 (building 30) (16.841458ms)
✔ view issue 106 (building 40, reported by bob) (20.817041ms)
✔ approve inspection 201 (created by dave) (19.528125ms)
✖ approve inspection 202 (created by alice) (21.890625ms)
✔ update organisation 1 (19.753375ms)
✔ issues in each user's list come only from the expected buildings (99.92675ms)
✔ the scenario loads exactly as specified (204.717083ms)
✔ only one active assignment per user, building and role (0.9075ms)
✔ a revoked role can be granted again (1.231542ms)
✔ the My access page shows what the server loaded (74.19975ms)
✔ a correct login creates a session and shows the user (262.903334ms)
✔ a wrong password or unknown email gets the same 401 (53.757625ms)
✔ registration validates, creates a user, and logs them in (43.445417ms)
✔ registering an existing email is a field error (30.865708ms)
✔ logout destroys the session (49.765875ms)
✔ a building can be created inside an organisation (283.362834ms)
✔ a duplicate building name in the same organisation is a field error (4.854166ms)
✔ the same building name is allowed in another organisation (8.669875ms)
✔ a building with issues cannot be deleted (11.90225ms)
✔ an empty building can be deleted (9.2005ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.509834ms)
✔ a logged-in POST without a token is refused with 403 (298.437583ms)
✔ a token from another session is refused (39.830959ms)
✔ the right token in the form field works (10.327208ms)
✔ every POST form on every page carries the token (41.558291ms)
✔ the dashboard counts match the database (273.214125ms)
✔ only the buildings carol can see appear (5.233958ms)
✔ create a draft, edit it, submit it, approve it (295.559375ms)
✔ invalid transitions are refused with 409 and change nothing (12.869083ms)
✔ only drafts can be edited (5.198416ms)
✔ returning a submitted inspection makes it editable again (7.358875ms)
Show 90 more lines
✔ concurrent approvals: exactly one wins (24.058334ms)
✔ unknown actions are 404 (4.30175ms)
✔ the issues list contains only issues from visible buildings (563.554667ms)
✔ a filter for another tenant's building returns nothing (3.718042ms)
✔ the inspections list is scoped too (8.444292ms)
✔ organisations are listed for their members only (8.95475ms)
✔ the dashboard counts only visible data (6.912209ms)
✔ view issue 101 (building 10) (439.276042ms)
✔ open the edit form for issue 101 (19.681583ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.019ms)
✔ view issue 105 (building 30) and 106 (building 40) (33.775334ms)
✔ report an issue at building 20 (19.456167ms)
✔ a reporter cannot edit their own issue once it is closed (6.493542ms)
✔ only building admins may delete; refusals change nothing (13.310792ms)
✔ the edit form cannot move an issue to another building (4.027917ms)
✔ the list pages 10 at a time and reports the total (282.849542ms)
✔ pages do not overlap (18.023167ms)
✔ filters combine with AND (6.615875ms)
✔ sorting by priority puts critical first when descending (7.073625ms)
✔ unknown sort keys and SQL in the query string are ignored (29.297583ms)
✔ GET /issues lists issues from the database (274.342625ms)
✔ GET /issues/101 shows one issue with its building (4.487959ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.468542ms)
✔ POST /issues re-renders the form with errors (4.257625ms)
✔ POST /issues stores the issue and redirects to it (7.400875ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.001916ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.029125ms)
✔ an issue time in the future is rejected (3.990375ms)
✔ GET /issues/101/edit shows the current values (3.773041ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.708375ms)
✔ POST /issues/:id/delete removes the issue (8.360042ms)
✔ GET /organisations lists organisations with building counts (271.515709ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.1755ms)
✔ POST /organisations validates and creates (10.836625ms)
✔ POST /organisations/:id/edit renames the organisation (8.511333ms)
✔ unknown organisations are 404 (6.515375ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (345.741125ms)
✔ anonymous requests are redirected to the login page (209.21375ms)
✔ anonymous writes are refused and change nothing (10.960625ms)
✔ login and register pages stay public (6.086792ms)
✔ login issues a new session id (no session fixation) (32.798416ms)
✔ returnTo only follows local paths (28.255917ms)
✔ new issues and transitions record the logged-in user (75.317625ms)
✔ the session cookie has the attributes we chose (25.981875ms)
✔ organisation 1: view and update (478.727834ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (5.867042ms)
✔ building 10: view, update, delete (49.000792ms)
✔ creating buildings needs org_admin (13.7245ms)
✔ creating an organisation makes the creator its admin (8.245375ms)
✔ inspections: view 201, open the edit form for draft 203 (43.309416ms)
✔ approve inspection 201 (dave's): only building admins (14.008875ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (9.309084ms)
ℹ tests 88
ℹ suites 0
ℹ pass 87
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8446.512042
✖ failing tests:
test at test/access-matrix.test.js:42:3
✖ approve inspection 202 (created by alice) (21.890625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
+ alice: 303,
- alice: 403,
bob: 404,
+ carol: 409,
- carol: 303,
dave: 403,
nora: 404,
ravi: 404
}
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/access-matrix.test.js:47:12)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: { alice: 303, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 409 },
expected: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 },
operator: 'deepStrictEqual',
diff: 'simple'
}
Exactly one test fails: the matrix row "approve inspection 202 (created by alice)". The diff in the failure report shows exactly which cell: Alice, 303 instead of 403. Separation of duties is in the specification and not in the code.
2. Add the rule
In src/authz/rules.js, approving and returning share a case. Split them, and add the exception to approval:
case 'ApproveInspection': // Separation of duties: nobody approves an inspection they created, whatever their role. return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin') && resource.created_by !== user.id; case 'ReturnInspection': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
Show the whole src/authz/rules.js after this change
// Authorization rules in plain JavaScript (Module 5).// Every route asks can(user, action, resource). Module 6 keeps this question// and moves the answer into Cedar policies. const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin']; // The roles a user effectively holds at one building: the roles assigned there,// plus building_admin if they are org_admin of the organisation that owns the building.export function rolesAtBuilding(user, buildingId, organisationId) { const roles = new Set(); for (const assignment of user.access.assignments) { if (assignment.building_id === buildingId) { roles.add(assignment.role); } } if (isOrgAdmin(user, organisationId)) { roles.add('building_admin'); } return roles;} function isMember(user, organisationId) { return user.access.memberships.some((m) => m.organisation_id === organisationId);} function isOrgAdmin(user, organisationId) { return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');} function hasAny(roles, wanted) { return wanted.some((role) => roles.has(role));} export function can(user, action, resource) { switch (action) { // Organisations. resource: an organisation row { id, ... } case 'ViewOrganisation': return isMember(user, resource.id); case 'UpdateOrganisation': case 'DeleteOrganisation': case 'CreateBuilding': return isOrgAdmin(user, resource.id); // Buildings. resource: a building row { id, organisation_id, ... } case 'ViewBuilding': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateBuilding': return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin'); case 'DeleteBuilding': return isOrgAdmin(user, resource.organisation_id); case 'CreateIssue': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']); case 'CreateInspection': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']); // Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... } case 'ViewIssue': return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateIssue': { const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id); if (roles.has('building_admin')) { return true; } return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed'; } case 'DeleteIssue': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin'); // Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... } case 'ViewInspection': return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateInspection': case 'SubmitInspection': { const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id); if (roles.has('building_admin')) { return true; } return roles.has('inspector') && resource.created_by === user.id; } case 'ApproveInspection': // Separation of duties: nobody approves an inspection they created, whatever their role. return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin') && resource.created_by !== user.id; case 'ReturnInspection': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin'); default: // An action without a rule is a bug. Fail loudly rather than allow. throw new Error(`No authorization rule for action ${action}`); }}// Authorization rules in plain JavaScript (Module 5).
// Every route asks can(user, action, resource). Module 6 keeps this question
// and moves the answer into Cedar policies.
const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin'];
// The roles a user effectively holds at one building: the roles assigned there,
// plus building_admin if they are org_admin of the organisation that owns the building.
export function rolesAtBuilding(user, buildingId, organisationId) {
const roles = new Set();
for (const assignment of user.access.assignments) {
if (assignment.building_id === buildingId) {
roles.add(assignment.role);
}
}
if (isOrgAdmin(user, organisationId)) {
roles.add('building_admin');
}
return roles;
}
function isMember(user, organisationId) {
return user.access.memberships.some((m) => m.organisation_id === organisationId);
}
function isOrgAdmin(user, organisationId) {
return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');
}
function hasAny(roles, wanted) {
return wanted.some((role) => roles.has(role));
}
export function can(user, action, resource) {
switch (action) {
// Organisations. resource: an organisation row { id, ... }
case 'ViewOrganisation':
return isMember(user, resource.id);
case 'UpdateOrganisation':
case 'DeleteOrganisation':
case 'CreateBuilding':
return isOrgAdmin(user, resource.id);
// Buildings. resource: a building row { id, organisation_id, ... }
case 'ViewBuilding':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateBuilding':
return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin');
case 'DeleteBuilding':
return isOrgAdmin(user, resource.organisation_id);
case 'CreateIssue':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']);
case 'CreateInspection':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']);
// Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... }
case 'ViewIssue':
return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateIssue': {
const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);
if (roles.has('building_admin')) {
return true;
}
return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed';
}
case 'DeleteIssue':
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
// Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... }
case 'ViewInspection':
return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateInspection':
case 'SubmitInspection': {
const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);
if (roles.has('building_admin')) {
return true;
}
return roles.has('inspector') && resource.created_by === user.id;
}
case 'ApproveInspection':
// Separation of duties: nobody approves an inspection they created, whatever their role.
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin')
&& resource.created_by !== user.id;
case 'ReturnInspection':
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
default:
// An action without a rule is a bug. Fail loudly rather than allow.
throw new Error(`No authorization rule for action ${action}`);
}
}
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (469.705542ms)
✔ edit issue 101 (31.474583ms)
✔ view issue 103 (building 20) (34.446875ms)
✔ edit issue 103 (reported by dave) (25.616375ms)
✔ report an issue at building 20 (19.960292ms)
✔ view issue 105 (building 30) (16.893083ms)
✔ view issue 106 (building 40, reported by bob) (16.225875ms)
✔ approve inspection 201 (created by dave) (15.983042ms)
✔ approve inspection 202 (created by alice) (16.705084ms)
✔ update organisation 1 (16.923833ms)
✔ issues in each user's list come only from the expected buildings (90.123417ms)
✔ the scenario loads exactly as specified (200.831375ms)
✔ only one active assignment per user, building and role (0.948708ms)
✔ a revoked role can be granted again (1.36175ms)
✔ the My access page shows what the server loaded (83.855916ms)
✔ a correct login creates a session and shows the user (272.676625ms)
✔ a wrong password or unknown email gets the same 401 (64.173917ms)
✔ registration validates, creates a user, and logs them in (43.518541ms)
✔ registering an existing email is a field error (32.523375ms)
✔ logout destroys the session (53.843875ms)
✔ a building can be created inside an organisation (294.232667ms)
✔ a duplicate building name in the same organisation is a field error (4.802541ms)
✔ the same building name is allowed in another organisation (10.553458ms)
✔ a building with issues cannot be deleted (13.052917ms)
✔ an empty building can be deleted (9.65425ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.986167ms)
✔ a logged-in POST without a token is refused with 403 (275.731333ms)
✔ a token from another session is refused (37.465416ms)
✔ the right token in the form field works (10.881625ms)
✔ every POST form on every page carries the token (40.881833ms)
✔ the dashboard counts match the database (273.987ms)
✔ only the buildings carol can see appear (5.691542ms)
✖ create a draft, edit it, submit it, approve it (303.042958ms)
✖ invalid transitions are refused with 409 and change nothing (4.382125ms)
✔ only drafts can be edited (7.880834ms)
✔ returning a submitted inspection makes it editable again (9.105083ms)
Show 98 more lines
✔ concurrent approvals: exactly one wins (32.05025ms)
✔ unknown actions are 404 (3.778792ms)
✔ the issues list contains only issues from visible buildings (520.632209ms)
✔ a filter for another tenant's building returns nothing (3.911917ms)
✔ the inspections list is scoped too (9.8775ms)
✔ organisations are listed for their members only (8.220916ms)
✔ the dashboard counts only visible data (6.636583ms)
✔ view issue 101 (building 10) (458.795459ms)
✔ open the edit form for issue 101 (23.166083ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (19.752792ms)
✔ view issue 105 (building 30) and 106 (building 40) (33.556209ms)
✔ report an issue at building 20 (18.921458ms)
✔ a reporter cannot edit their own issue once it is closed (6.128333ms)
✔ only building admins may delete; refusals change nothing (13.084041ms)
✔ the edit form cannot move an issue to another building (3.361375ms)
✔ the list pages 10 at a time and reports the total (315.9065ms)
✔ pages do not overlap (19.556ms)
✔ filters combine with AND (7.445125ms)
✔ sorting by priority puts critical first when descending (5.645958ms)
✔ unknown sort keys and SQL in the query string are ignored (30.41ms)
✔ GET /issues lists issues from the database (289.2395ms)
✔ GET /issues/101 shows one issue with its building (5.231375ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (19.9945ms)
✔ POST /issues re-renders the form with errors (5.951666ms)
✔ POST /issues stores the issue and redirects to it (9.531875ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.439166ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.825458ms)
✔ an issue time in the future is rejected (4.542125ms)
✔ GET /issues/101/edit shows the current values (4.402708ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.437ms)
✔ POST /issues/:id/delete removes the issue (9.561875ms)
✔ GET /organisations lists organisations with building counts (284.781333ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.290042ms)
✔ POST /organisations validates and creates (13.43425ms)
✔ POST /organisations/:id/edit renames the organisation (9.583375ms)
✔ unknown organisations are 404 (7.336875ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (394.047083ms)
✔ anonymous requests are redirected to the login page (217.072125ms)
✔ anonymous writes are refused and change nothing (11.632791ms)
✔ login and register pages stay public (6.151584ms)
✔ login issues a new session id (no session fixation) (31.521084ms)
✔ returnTo only follows local paths (28.269417ms)
✔ new issues and transitions record the logged-in user (76.180792ms)
✔ the session cookie has the attributes we chose (26.332958ms)
✔ organisation 1: view and update (477.91625ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (6.924667ms)
✔ building 10: view, update, delete (55.269917ms)
✔ creating buildings needs org_admin (16.875334ms)
✔ creating an organisation makes the creator its admin (10.415792ms)
✔ inspections: view 201, open the edit form for draft 203 (39.820084ms)
✔ approve inspection 201 (dave's): only building admins (16.914542ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (12.386459ms)
ℹ tests 88
ℹ suites 0
ℹ pass 86
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8656.442
✖ failing tests:
test at test/inspections.test.js:20:1
✖ create a draft, edit it, submit it, approve it (303.042958ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
403 !== 303
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/inspections.test.js:27:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 403,
expected: 303,
operator: 'strictEqual',
diff: 'simple'
}
test at test/inspections.test.js:36:1
✖ invalid transitions are refused with 409 and change nothing (4.382125ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
403 !== 409
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/inspections.test.js:37:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 403,
expected: 409,
operator: 'strictEqual',
diff: 'simple'
}
The matrix passes now, but two older tests in test/inspections.test.js fail, and both failures are the new rule working:
- "create a draft, edit it, submit it, approve it" has Carol create and approve the same inspection. That is exactly what separation of duties forbids. Let Carol create and submit at building 10, and let Alice, the building admin there, approve.
- "invalid transitions are refused with 409" asks Carol to approve draft 203, which she created. The permission check now comes first and answers
403. The test is about workflow states, so use transitions Carol is allowed to attempt: returning a draft, and submitting an inspection that is already submitted.
const created = await agent.post('/inspections').type('form').send({ building_id: '20', title: 'Stairwell lighting check', findings: '' }); const created = await agent.post('/inspections').type('form').send({ building_id: '10', title: 'Stairwell lighting check', findings: '' });
assert.equal((await agent.post(`${url}/submit`)).status, 303); assert.equal((await agent.post(`${url}/approve`)).status, 303); assert.equal((await agent.post(`${url}/approve`)).status, 403, 'carol created it, so she may not approve it'); const alice = await loginAs('alice'); assert.equal((await alice.post(`${url}/approve`)).status, 303);
assert.equal((await agent.post('/inspections/203/approve')).status, 409); assert.equal((await agent.post('/inspections/203/return')).status, 409); assert.equal((await agent.post('/inspections/203/return')).status, 409, '203 is a draft'); assert.equal((await agent.post('/inspections/201/submit')).status, 409, '201 is already submitted');
Show the whole test/inspections.test.js after this change
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; let agent;before(async () => { await resetDatabase(); agent = await loginAs('carol');});after(() => pool.end()); async function history(inspectionId) { const { rows } = await pool.query('SELECT from_status, to_status FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY id', [inspectionId]); return rows.map((r) => `${r.from_status}->${r.to_status}`);} test('create a draft, edit it, submit it, approve it', async () => { const created = await agent.post('/inspections').type('form').send({ building_id: '10', title: 'Stairwell lighting check', findings: '' }); assert.equal(created.status, 303); const url = created.headers.location; assert.equal((await agent.post(`${url}/edit`).type('form').send({ title: 'Stairwell lighting check', findings: 'All bulbs working.' })).status, 303); assert.equal((await agent.post(`${url}/submit`)).status, 303); assert.equal((await agent.post(`${url}/approve`)).status, 403, 'carol created it, so she may not approve it'); const alice = await loginAs('alice'); assert.equal((await alice.post(`${url}/approve`)).status, 303); const id = Number(url.split('/').pop()); assert.deepEqual(await history(id), ['draft->submitted', 'submitted->approved']); const page = await agent.get(url); assert.match(page.text, /All bulbs working/); assert.match(page.text, /badge status-approved/);}); test('invalid transitions are refused with 409 and change nothing', async () => { assert.equal((await agent.post('/inspections/203/return')).status, 409, '203 is a draft'); assert.equal((await agent.post('/inspections/201/submit')).status, 409, '201 is already submitted'); assert.deepEqual(await history(203), []);}); test('only drafts can be edited', async () => { const res = await agent.post('/inspections/201/edit').type('form').send({ title: 'Changed after submission', findings: '' }); assert.equal(res.status, 409); const { rows } = await pool.query('SELECT title FROM inspections WHERE id = 201'); assert.equal(rows[0].title, 'Q4 lift maintenance inspection');}); test('returning a submitted inspection makes it editable again', async () => { assert.equal((await agent.post('/inspections/202/return')).status, 303); assert.equal((await agent.get('/inspections/202/edit')).status, 200);}); test('concurrent approvals: exactly one wins', async () => { const results = await Promise.all(Array.from({ length: 8 }, () => agent.post('/inspections/201/approve'))); assert.deepEqual(results.map((r) => r.status).sort(), [303, 409, 409, 409, 409, 409, 409, 409]); assert.deepEqual(await history(201), ['draft->submitted', 'submitted->approved']);}); test('unknown actions are 404', async () => { assert.equal((await agent.post('/inspections/201/delete')).status, 404);});import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
let agent;
before(async () => {
await resetDatabase();
agent = await loginAs('carol');
});
after(() => pool.end());
async function history(inspectionId) {
const { rows } = await pool.query('SELECT from_status, to_status FROM inspection_status_changes WHERE inspection_id = $1 ORDER BY id', [inspectionId]);
return rows.map((r) => `${r.from_status}->${r.to_status}`);
}
test('create a draft, edit it, submit it, approve it', async () => {
const created = await agent.post('/inspections').type('form').send({ building_id: '10', title: 'Stairwell lighting check', findings: '' });
assert.equal(created.status, 303);
const url = created.headers.location;
assert.equal((await agent.post(`${url}/edit`).type('form').send({ title: 'Stairwell lighting check', findings: 'All bulbs working.' })).status, 303);
assert.equal((await agent.post(`${url}/submit`)).status, 303);
assert.equal((await agent.post(`${url}/approve`)).status, 403, 'carol created it, so she may not approve it');
const alice = await loginAs('alice');
assert.equal((await alice.post(`${url}/approve`)).status, 303);
const id = Number(url.split('/').pop());
assert.deepEqual(await history(id), ['draft->submitted', 'submitted->approved']);
const page = await agent.get(url);
assert.match(page.text, /All bulbs working/);
assert.match(page.text, /badge status-approved/);
});
test('invalid transitions are refused with 409 and change nothing', async () => {
assert.equal((await agent.post('/inspections/203/return')).status, 409, '203 is a draft');
assert.equal((await agent.post('/inspections/201/submit')).status, 409, '201 is already submitted');
assert.deepEqual(await history(203), []);
});
test('only drafts can be edited', async () => {
const res = await agent.post('/inspections/201/edit').type('form').send({ title: 'Changed after submission', findings: '' });
assert.equal(res.status, 409);
const { rows } = await pool.query('SELECT title FROM inspections WHERE id = 201');
assert.equal(rows[0].title, 'Q4 lift maintenance inspection');
});
test('returning a submitted inspection makes it editable again', async () => {
assert.equal((await agent.post('/inspections/202/return')).status, 303);
assert.equal((await agent.get('/inspections/202/edit')).status, 200);
});
test('concurrent approvals: exactly one wins', async () => {
const results = await Promise.all(Array.from({ length: 8 }, () => agent.post('/inspections/201/approve')));
assert.deepEqual(results.map((r) => r.status).sort(), [303, 409, 409, 409, 409, 409, 409, 409]);
assert.deepEqual(await history(201), ['draft->submitted', 'submitted->approved']);
});
test('unknown actions are 404', async () => {
assert.equal((await agent.post('/inspections/201/delete')).status, 404);
});
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (474.97275ms)
✔ edit issue 101 (20.141458ms)
✔ view issue 103 (building 20) (18.723167ms)
✔ edit issue 103 (reported by dave) (20.170917ms)
✔ report an issue at building 20 (21.533958ms)
✔ view issue 105 (building 30) (19.627166ms)
✔ view issue 106 (building 40, reported by bob) (16.71375ms)
✔ approve inspection 201 (created by dave) (14.733334ms)
✔ approve inspection 202 (created by alice) (16.665292ms)
✔ update organisation 1 (20.8105ms)
✔ issues in each user's list come only from the expected buildings (97.121666ms)
✔ the scenario loads exactly as specified (206.740041ms)
✔ only one active assignment per user, building and role (0.900583ms)
✔ a revoked role can be granted again (1.289125ms)
✔ the My access page shows what the server loaded (76.080541ms)
✔ a correct login creates a session and shows the user (258.667833ms)
✔ a wrong password or unknown email gets the same 401 (53.123125ms)
✔ registration validates, creates a user, and logs them in (37.140334ms)
✔ registering an existing email is a field error (31.294334ms)
✔ logout destroys the session (48.236708ms)
✔ a building can be created inside an organisation (278.528625ms)
✔ a duplicate building name in the same organisation is a field error (4.66325ms)
✔ the same building name is allowed in another organisation (9.732917ms)
✔ a building with issues cannot be deleted (12.165375ms)
✔ an empty building can be deleted (10.782083ms)
✔ an organisation with buildings cannot be deleted, an empty one can (23.109958ms)
✔ a logged-in POST without a token is refused with 403 (269.354208ms)
✔ a token from another session is refused (37.753833ms)
✔ the right token in the form field works (10.5125ms)
✔ every POST form on every page carries the token (42.67225ms)
✔ the dashboard counts match the database (277.932375ms)
✔ only the buildings carol can see appear (6.728833ms)
✔ create a draft, edit it, submit it, approve it (326.504625ms)
✔ invalid transitions are refused with 409 and change nothing (9.431417ms)
✔ only drafts can be edited (4.369666ms)
✔ returning a submitted inspection makes it editable again (6.506791ms)
Show 60 more lines
✔ concurrent approvals: exactly one wins (21.086958ms)
✔ unknown actions are 404 (3.163ms)
✔ the issues list contains only issues from visible buildings (587.607292ms)
✔ a filter for another tenant's building returns nothing (4.647417ms)
✔ the inspections list is scoped too (11.491959ms)
✔ organisations are listed for their members only (11.524708ms)
✔ the dashboard counts only visible data (10.7915ms)
✔ view issue 101 (building 10) (459.381125ms)
✔ open the edit form for issue 101 (18.462625ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (15.895125ms)
✔ view issue 105 (building 30) and 106 (building 40) (31.698625ms)
✔ report an issue at building 20 (17.780833ms)
✔ a reporter cannot edit their own issue once it is closed (5.682167ms)
✔ only building admins may delete; refusals change nothing (12.669833ms)
✔ the edit form cannot move an issue to another building (3.25075ms)
✔ the list pages 10 at a time and reports the total (292.297666ms)
✔ pages do not overlap (16.555167ms)
✔ filters combine with AND (5.73725ms)
✔ sorting by priority puts critical first when descending (5.0675ms)
✔ unknown sort keys and SQL in the query string are ignored (28.08625ms)
✔ GET /issues lists issues from the database (295.172ms)
✔ GET /issues/101 shows one issue with its building (6.147208ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (16.813167ms)
✔ POST /issues re-renders the form with errors (5.314167ms)
✔ POST /issues stores the issue and redirects to it (8.885833ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.43925ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.489166ms)
✔ an issue time in the future is rejected (4.478166ms)
✔ GET /issues/101/edit shows the current values (4.533916ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.599625ms)
✔ POST /issues/:id/delete removes the issue (9.763541ms)
✔ GET /organisations lists organisations with building counts (273.477542ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.171875ms)
✔ POST /organisations validates and creates (11.079542ms)
✔ POST /organisations/:id/edit renames the organisation (10.090083ms)
✔ unknown organisations are 404 (6.329791ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (348.213959ms)
✔ anonymous requests are redirected to the login page (211.724709ms)
✔ anonymous writes are refused and change nothing (11.03125ms)
✔ login and register pages stay public (5.616708ms)
✔ login issues a new session id (no session fixation) (33.446792ms)
✔ returnTo only follows local paths (32.133167ms)
✔ new issues and transitions record the logged-in user (72.236917ms)
✔ the session cookie has the attributes we chose (26.759625ms)
✔ organisation 1: view and update (501.030875ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (6.518167ms)
✔ building 10: view, update, delete (60.671584ms)
✔ creating buildings needs org_admin (20.764667ms)
✔ creating an organisation makes the creator its admin (9.006458ms)
✔ inspections: view 201, open the edit form for draft 203 (38.98425ms)
✔ approve inspection 201 (dave's): only building admins (21.949667ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (10.808916ms)
ℹ tests 88
ℹ suites 0
ℹ pass 88
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8598.019
The Approve button on inspection 202 disappears for Alice without touching the template, because the template asks can('ApproveInspection', inspection).
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

3. Where does authorization live now?
That rule was cheap, because we had one can() function. Now count where the idea "who may see what" is encoded:
grep -rn "org_admin\|building_admin\|revoked_at IS NULL" src --include=*.js | grep -v "^src/seed.js"
src/models/access.js:18: WHERE a.user_id = $1 AND a.revoked_at IS NULL
src/models/organisations.js:24:// Creates the organisation and makes its creator org_admin, in one transaction.
src/models/organisations.js:28: await client.query("INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, 'org_admin')", [creatorId, rows[0].id]);
src/models/scope.js:5:// holds any active role there, or is org_admin of the organisation that owns it.
src/models/scope.js:9: SELECT building_id FROM building_role_assignments WHERE user_id = ${userParam} AND revoked_at IS NULL
src/models/scope.js:12: SELECT organisation_id FROM memberships WHERE user_id = ${userParam} AND role = 'org_admin'
src/authz/rules.js:5:const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin'];
src/authz/rules.js:8:// plus building_admin if they are org_admin of the organisation that owns the building.
src/authz/rules.js:17: roles.add('building_admin');
src/authz/rules.js:27: return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');
src/authz/rules.js:48: return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin');
src/authz/rules.js:52: return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']);
src/authz/rules.js:54: return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']);
src/authz/rules.js:61: if (roles.has('building_admin')) {
src/authz/rules.js:67: return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
src/authz/rules.js:75: if (roles.has('building_admin')) {
src/authz/rules.js:82: return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin')
src/authz/rules.js:85: return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
Read the list: the role logic lives in rules.js (JavaScript) and in scope.js (SQL), and the loading of roles in access.js (SQL again). The separation-of-duties rule had to be written inside the approve rule; the next exception (say, "no edits to issues at a building that is under investigation") has to be woven into every case it affects. And rules.js now has 17 actions in one switch, each of which mixes three questions: which role, which scope, which exception.
4. Role explosion
Our design kept one thing manageable: roles are per building in data (building_role_assignments), not per building in code. The common alternative, a fixed list of roles such as dublin_admin or cork_viewer, grows with every building. Count it with our own data:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT (SELECT count(*) FROM buildings) AS buildings, 4 AS roles_per_building, (SELECT count(*) FROM buildings) * 4 AS static_roles_needed, (SELECT count(*) FROM building_role_assignments WHERE revoked_at IS NULL) AS assignments_in_use;
buildings | roles_per_building | static_roles_needed | assignments_in_use
-----------+--------------------+---------------------+--------------------
4 | 4 | 16 | 5
(1 row)Sixteen static roles for four buildings. A company with 300 buildings needs 1,200, before any organisation-level role, before "inspector who may also report", and before exceptions such as separation of duties. Every new combination is a new role, and every route has to know which roles imply which rights. That growth is called role explosion.
Try it with different numbers. This explorer is a counting model, not the Cedar engine:
Our per-building assignments avoid the explosion in the data. What we have not avoided is the growth in the logic: each new rule lands in a switch statement, is mirrored by hand in SQL, and can only be reviewed by reading JavaScript. Those are the problems a policy language addresses:
| Problem in Module 5 | What a policy engine offers |
|---|---|
Rules are code inside a switch |
Rules are separate, declarative policies, one per statement of the matrix |
| Exceptions are woven into every permit | A forbid policy overrides every permit, stated once |
| No way to check a rule refers to real attributes | A schema validates every policy before it runs |
| The decision gives no reason | The engine returns the IDs of the policies that decided |
| Reviewers must read JavaScript | Reviewers read policies |
It does not solve everything: the engine evaluates the data our code gives it, and lists still need SQL. Module 8 is about exactly that.
Experiment
The product owner asks for a new organisation-level role: facilities_manager, who may view every building of their organisation but change nothing.
Reveal One honest count
At least: (1) a migration to allow facilities_manager in the memberships.role check; (2) rolesAtBuilding in rules.js, to add viewer when the user is a facilities manager of the building's organisation; (3) visibleBuildingCondition in scope.js, the same idea in SQL; (4) any rule that tests isMember or isOrgAdmin directly; (5) the matrix test and the role table. Two languages, and nothing but the tests to tell you that steps 2 and 3 agree. In Module 7 we make the same change with Cedar and compare.
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (453.525042ms)
✔ edit issue 101 (23.565208ms)
✔ view issue 103 (building 20) (19.276833ms)
✔ edit issue 103 (reported by dave) (21.952542ms)
✔ report an issue at building 20 (27.131208ms)
✔ view issue 105 (building 30) (19.02025ms)
✔ view issue 106 (building 40, reported by bob) (18.126625ms)
✔ approve inspection 201 (created by dave) (18.981875ms)
✔ approve inspection 202 (created by alice) (19.901333ms)
✔ update organisation 1 (20.829875ms)
✔ issues in each user's list come only from the expected buildings (96.147209ms)
✔ the scenario loads exactly as specified (202.885458ms)
✔ only one active assignment per user, building and role (0.847ms)
✔ a revoked role can be granted again (1.53275ms)
✔ the My access page shows what the server loaded (73.423541ms)
✔ a correct login creates a session and shows the user (267.383875ms)
✔ a wrong password or unknown email gets the same 401 (54.728833ms)
✔ registration validates, creates a user, and logs them in (40.313125ms)
✔ registering an existing email is a field error (33.102625ms)
✔ logout destroys the session (52.58875ms)
✔ a building can be created inside an organisation (267.885541ms)
✔ a duplicate building name in the same organisation is a field error (4.789875ms)
✔ the same building name is allowed in another organisation (10.67425ms)
✔ a building with issues cannot be deleted (13.168875ms)
✔ an empty building can be deleted (11.070875ms)
✔ an organisation with buildings cannot be deleted, an empty one can (26.659167ms)
✔ a logged-in POST without a token is refused with 403 (276.35675ms)
✔ a token from another session is refused (35.116791ms)
✔ the right token in the form field works (12.839625ms)
✔ every POST form on every page carries the token (53.254708ms)
✔ the dashboard counts match the database (278.086917ms)
✔ only the buildings carol can see appear (5.422125ms)
✔ create a draft, edit it, submit it, approve it (322.026583ms)
✔ invalid transitions are refused with 409 and change nothing (9.293916ms)
✔ only drafts can be edited (4.489917ms)
✔ returning a submitted inspection makes it editable again (6.796125ms)
Show 60 more lines
✔ concurrent approvals: exactly one wins (21.367667ms)
✔ unknown actions are 404 (2.945083ms)
✔ the issues list contains only issues from visible buildings (552.673625ms)
✔ a filter for another tenant's building returns nothing (4.83375ms)
✔ the inspections list is scoped too (14.070666ms)
✔ organisations are listed for their members only (13.224458ms)
✔ the dashboard counts only visible data (11.509667ms)
✔ view issue 101 (building 10) (465.417792ms)
✔ open the edit form for issue 101 (22.378459ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (20.779333ms)
✔ view issue 105 (building 30) and 106 (building 40) (44.808583ms)
✔ report an issue at building 20 (26.921666ms)
✔ a reporter cannot edit their own issue once it is closed (8.122625ms)
✔ only building admins may delete; refusals change nothing (20.284333ms)
✔ the edit form cannot move an issue to another building (4.234666ms)
✔ the list pages 10 at a time and reports the total (278.735834ms)
✔ pages do not overlap (21.025666ms)
✔ filters combine with AND (6.430625ms)
✔ sorting by priority puts critical first when descending (5.505125ms)
✔ unknown sort keys and SQL in the query string are ignored (58.02625ms)
✔ GET /issues lists issues from the database (276.922667ms)
✔ GET /issues/101 shows one issue with its building (6.148333ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (13.629292ms)
✔ POST /issues re-renders the form with errors (4.638958ms)
✔ POST /issues stores the issue and redirects to it (8.016625ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (5.000791ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.956125ms)
✔ an issue time in the future is rejected (4.407334ms)
✔ GET /issues/101/edit shows the current values (4.812708ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.310916ms)
✔ POST /issues/:id/delete removes the issue (8.78ms)
✔ GET /organisations lists organisations with building counts (267.035333ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.690583ms)
✔ POST /organisations validates and creates (13.62025ms)
✔ POST /organisations/:id/edit renames the organisation (10.173958ms)
✔ unknown organisations are 404 (6.963625ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (344.675792ms)
✔ anonymous requests are redirected to the login page (212.830875ms)
✔ anonymous writes are refused and change nothing (11.007458ms)
✔ login and register pages stay public (5.938833ms)
✔ login issues a new session id (no session fixation) (32.386416ms)
✔ returnTo only follows local paths (28.28775ms)
✔ new issues and transitions record the logged-in user (69.061875ms)
✔ the session cookie has the attributes we chose (25.752167ms)
✔ organisation 1: view and update (483.792166ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (6.73175ms)
✔ building 10: view, update, delete (50.390833ms)
✔ creating buildings needs org_admin (15.975792ms)
✔ creating an organisation makes the creator its admin (8.955458ms)
✔ inspections: view 201, open the edit form for draft 203 (34.907875ms)
✔ approve inspection 201 (dave's): only building admins (16.1345ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (10.816708ms)
ℹ tests 88
ℹ suites 0
ℹ pass 88
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8636.919625
git add -A
git commit -m "Access matrix test and separation of duties"
[main a595c3a] Access matrix test and separation of duties
3 files changed, 71 insertions(+), 4 deletions(-)
create mode 100644 test/access-matrix.test.js
Symptom A matrix row fails only when the whole suite runs
Rows that change data (approvals, new issues) must list the refused users first. Check the order of keys in that row's expect.
Recap and next step
The access matrix is now executable: one table, one row per request, every user. It caught the missing separation-of-duties rule, which became one more condition inside can(). Role explosion is avoided in our data by per-building assignments, but our logic is spread across a JavaScript switch, a SQL fragment, and hand-written exceptions.
Module 6 keeps every route and every test exactly as they are, and replaces what is inside can() with Cedar: first the smallest possible check, then one route, then all of them.
Open the checkpoint files for lesson 5.5 (separate page; only files from this lesson and earlier)