Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 5.5

Role explosion and the access matrix as a test: checkpoint files

Git tag in the reference repository
lesson/m05-l05 (commit c51c4d8)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 88, pass 88, fail 0)

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m05-l05 -- src.

Files changed in this lesson

src/authz/rules.js changed

src/authz/rules.js
// 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}`);  }}

test/access-matrix.test.js added

test/access-matrix.test.js
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);  }});

test/inspections.test.js changed

test/inspections.test.js
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);});

Project tree at this checkpoint

.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
migrations/005_create_memberships_and_building_roles.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/migrate.js
scripts/seed.js
src/app.js
src/authz/rules.js
src/config.js
src/db.js
src/lib/http.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/migrate.js
src/models/access.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/organisations.js
src/models/scope.js
src/models/users.js
src/routes/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access-matrix.test.js
test/access.test.js
test/auth.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/isolation.test.js
test/issue-authz.test.js
test/issue-list.test.js
test/issues.test.js
test/organisations.test.js
test/rate-limit.test.js
test/require-login.test.js
test/resource-authz.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/forbidden.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 5.5