Caretaker Express · PostgreSQL · Cedar

Module 5 · Authorization before Cedar

5.4 Buildings, organisations and inspections

Extend can() to every remaining action, enforce it in the organisations, buildings and inspections routers, make the creator of an organisation its admin in one transaction, and close the last local-only gaps.

≈ 70 min 26 steps 246 lines of code Replay verified

Starting point

Issues and every list are protected. The organisation, building and inspection pages are not: Alice can rename Harbour Lets, and Dave can approve inspections.

Outcome

  • can() answers 17 actions across organisations, buildings, issues and inspections.
  • Every route loads, authorizes, then acts; 404 for what you cannot see, 403 for what you see but cannot do.
  • Creating an organisation makes you its org_admin, atomically.
  • Buttons on organisation, building and inspection pages follow the rules.
  • At the end of this lesson the application has no known authorization gaps, and the local-only warning is lifted.

The problem

Server terminal (leave it running)caretaker/
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000
Run and comparecaretaker/
rm -f /tmp/dave.txt
TOKEN=$(curl -s -c /tmp/dave.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/dave.txt -c /tmp/dave.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=dave@example.test -d password=password123
TOKEN=$(curl -s -b /tmp/dave.txt http://localhost:3000/account | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -si -b /tmp/dave.txt -X POST http://localhost:3000/inspections/202/approve -d _csrf=$TOKEN | head -1
HTTP/1.1 303 See Other

Dave, an inspector, just approved Alice's inspection. Only building admins may approve. The same gap exists for every organisation, building and inspection route.

Ctrl+C Stop the server in the server terminal.
Run and comparecaretaker/
npm run db:seed

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario

Build it

1. All the rules

Replace src/authz/rules.js. The issue rules are unchanged; the new actions follow the role table from lesson 5.1:

Replace whole filesrc/authz/rules.jsJavaScript
Highlighted lines are new or changed (44).
// 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':    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}`);  }}

Two judgement calls are worth noticing:

  • Membership without a building role lets a user see the organisation page (ViewOrganisation) but no building (ViewBuilding). Ravi, whose building role was revoked, is exactly that case.
  • Permission versus workflow. ApproveInspection says who may approve. Whether the inspection is in a state that can be approved (submitted) is a workflow rule, already enforced by transitionInspection. We keep them separate: a building admin approving a draft gets 409 Conflict (wrong state), Dave approving anything gets 403 Forbidden (wrong person).

2. Creating an organisation makes you its admin

Without this, a user who creates an organisation could not see it. The insert and the membership must succeed or fail together. Update src/models/organisations.js:

Editsrc/models/organisations.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 2
import { query } from '../db.js';import { query, withTransaction } from '../db.js';
Change 2 of 2
export async function createOrganisation({ name }) {  const { rows } = await query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);  return rows[0];// Creates the organisation and makes its creator org_admin, in one transaction.export async function createOrganisation({ name }, creatorId) {  return withTransaction(async (client) => {    const { rows } = await client.query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);    await client.query("INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, 'org_admin')", [creatorId, rows[0].id]);    return rows[0];  });}
Show the whole src/models/organisations.js after this change
import { query, withTransaction } from '../db.js'; export async function listOrganisations(userId) {  if (!userId) {    throw new Error('listOrganisations requires the id of the user the list is for');  }  const { rows } = await query(    `SELECT o.id, o.name, count(s.id)::int AS building_count     FROM organisations o     LEFT JOIN buildings s ON s.organisation_id = o.id     WHERE o.id IN (SELECT organisation_id FROM memberships WHERE user_id = $1)     GROUP BY o.id     ORDER BY o.name`,    [userId],  );  return rows;} export async function findOrganisation(id) {  const { rows } = await query('SELECT id, name, created_at, updated_at FROM organisations WHERE id = $1', [id]);  return rows[0] ?? null;} // Creates the organisation and makes its creator org_admin, in one transaction.export async function createOrganisation({ name }, creatorId) {  return withTransaction(async (client) => {    const { rows } = await client.query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);    await client.query("INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, 'org_admin')", [creatorId, rows[0].id]);    return rows[0];  });} export async function deleteOrganisation(id) {  const { rowCount } = await query('DELETE FROM organisations WHERE id = $1', [id]);  return rowCount === 1;} export async function updateOrganisation(id, { name }) {  const { rows } = await query(    'UPDATE organisations SET name = $2, updated_at = now() WHERE id = $1 RETURNING id',    [id, name],  );  return rows[0] ?? null;}

3. The organisations router

Four changes in src/routes/organisations.js: imports, loadOrganisation checks ViewOrganisation, each action checks its own permission, and creation passes the creator.

Editsrc/routes/organisations.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 8
import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';
Change 2 of 8
  const organisation = id === null ? null : await findOrganisation(id);  if (!organisation) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });  if (!organisation || !can(req.user, 'ViewOrganisation', organisation)) {    notFound(req, res);    return null;  }  return organisation;
Change 3 of 8
  const created = await createOrganisation(values);  const created = await createOrganisation(values, req.user.id);
Change 4 of 8
organisationsRouter.get('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
Change 5 of 8
organisationsRouter.post('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
Change 6 of 8
organisationsRouter.post('/:id/delete', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res);
Change 7 of 8
organisationsRouter.get('/:id/buildings/new', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
Change 8 of 8
organisationsRouter.post('/:id/buildings', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
Show the whole src/routes/organisations.js after this change
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js'; export const organisationsRouter = express.Router(); const validateOrganisation = validateName; function renderForm(res, status, { organisation = null, values = {}, errors = {} }) {  res.status(status).render('organisations/form', {    title: organisation ? `Edit ${organisation.name}` : 'New organisation',    action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations',    organisation,    values,    errors,  });} // Loads the organisation named by :id, or answers 404. Returns null when it answered.async function loadOrganisation(req, res) {  const id = parseId(req.params.id);  const organisation = id === null ? null : await findOrganisation(id);  if (!organisation || !can(req.user, 'ViewOrganisation', organisation)) {    notFound(req, res);    return null;  }  return organisation;} organisationsRouter.get('/', async (req, res) => {  res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });}); organisationsRouter.get('/new', (req, res) => {  renderForm(res, 200, {});}); organisationsRouter.post('/', async (req, res) => {  const { errors, values } = validateOrganisation(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderForm(res, 400, { values, errors });  }  const created = await createOrganisation(values, req.user.id);  res.redirect(303, `/organisations/${created.id}`);}); organisationsRouter.get('/:id', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  const buildings = await listBuildingsForOrganisation(organisation.id);  res.render('organisations/show', { title: organisation.name, organisation, buildings });}); organisationsRouter.get('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);  renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);  const { errors, values } = validateOrganisation(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderForm(res, 400, { organisation, values, errors });  }  await updateOrganisation(organisation.id, values);  res.redirect(303, `/organisations/${organisation.id}`);}); organisationsRouter.post('/:id/delete', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res);  try {    await deleteOrganisation(organisation.id);  } catch (err) {    if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {      const buildings = await listBuildingsForOrganisation(organisation.id);      return res.status(409).render('organisations/show', {        title: organisation.name,        organisation,        buildings,        error: 'This organisation still has buildings. Delete its buildings first.',      });    }    throw err;  }  res.redirect(303, '/organisations');}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) {  res.status(status).render('buildings/form', {    title: `New building in ${organisation.name}`,    action: `/organisations/${organisation.id}/buildings`,    cancelUrl: `/organisations/${organisation.id}`,    building: null,    values,    errors,  });} organisationsRouter.get('/:id/buildings/new', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);  renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);  const { errors, values } = validateName(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderBuildingForm(res, 400, { organisation, values, errors });  }  try {    const building = await createBuilding({ organisation_id: organisation.id, name: values.name });    res.redirect(303, `/buildings/${building.id}`);  } catch (err) {    if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {      return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } });    }    throw err;  }});

4. The buildings router

Editsrc/routes/buildings.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 5
import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';
Change 2 of 5
  const building = id === null ? null : await findBuilding(id);  if (!building) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });  if (!building || !can(req.user, 'ViewBuilding', building)) {    notFound(req, res);    return null;  }  return building;
Change 3 of 5
buildingsRouter.get('/:id/edit', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);
Change 4 of 5
buildingsRouter.post('/:id/edit', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);
Change 5 of 5
buildingsRouter.post('/:id/delete', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  if (!can(req.user, 'DeleteBuilding', building)) return forbidden(res);
Show the whole src/routes/buildings.js after this change
import express from 'express';import { findBuilding, updateBuilding, deleteBuilding } from '../models/buildings.js';import { listRecentIssuesForBuilding } from '../models/issues.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js'; export const buildingsRouter = express.Router(); async function loadBuilding(req, res) {  const id = parseId(req.params.id);  const building = id === null ? null : await findBuilding(id);  if (!building || !can(req.user, 'ViewBuilding', building)) {    notFound(req, res);    return null;  }  return building;} async function renderBuildingPage(res, status, building, error = null) {  const issues = await listRecentIssuesForBuilding(building.id);  res.status(status).render('buildings/show', { title: building.name, building, issues, error });} function renderEditForm(res, status, { building, values, errors = {} }) {  res.status(status).render('buildings/form', {    title: `Edit ${building.name}`,    action: `/buildings/${building.id}/edit`,    cancelUrl: `/buildings/${building.id}`,    building,    values,    errors,  });} buildingsRouter.get('/:id', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  await renderBuildingPage(res, 200, building);}); buildingsRouter.get('/:id/edit', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);  renderEditForm(res, 200, { building, values: building });}); buildingsRouter.post('/:id/edit', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);  const { errors, values } = validateName(req.body ?? {});  if (Object.keys(errors).length > 0) {    return renderEditForm(res, 400, { building, values, errors });  }  try {    await updateBuilding(building.id, values);  } catch (err) {    if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {      return renderEditForm(res, 400, { building, values, errors: { name: 'This organisation already has a building with that name.' } });    }    throw err;  }  res.redirect(303, `/buildings/${building.id}`);}); buildingsRouter.post('/:id/delete', async (req, res) => {  const building = await loadBuilding(req, res);  if (!building) return;  if (!can(req.user, 'DeleteBuilding', building)) return forbidden(res);  try {    await deleteBuilding(building.id);  } catch (err) {    if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {      return renderBuildingPage(res, 409, building, 'This building still has maintenance issues, so it cannot be deleted.');    }    throw err;  }  res.redirect(303, `/organisations/${building.organisation_id}`);});

5. The inspections router

The form offers only buildings where the user may create inspections, creation checks the chosen building, and every transition maps to its action:

Editsrc/routes/inspections.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 9
import { listBuildings } from '../models/buildings.js';import { listBuildings, findBuilding } from '../models/buildings.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';
Change 2 of 9
const INSPECTION_STATUSES = ['draft', 'submitted', 'approved'];const TRANSITION_ACTIONS = { submit: 'SubmitInspection', approve: 'ApproveInspection', return: 'ReturnInspection' };
Change 3 of 9
async function renderInspectionForm(res, status, { inspection = null, values = {}, errors = {} } = {}) {async function renderInspectionForm(req, res, status, { inspection = null, values = {}, errors = {} } = {}) {
Change 4 of 9
    buildings: inspection ? [] : await listBuildings(),    buildings: inspection ? [] : (await listBuildings()).filter((building) => can(req.user, 'CreateInspection', building)),
Change 5 of 9
  const inspection = id === null ? null : await findInspection(id);  if (!inspection) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });  if (!inspection || !can(req.user, 'ViewInspection', inspection)) {    notFound(req, res);    return null;  }  return inspection;
Change 6 of 9
inspectionsRouter.get('/new', async (req, res) => {  await renderInspectionForm(res, 200);  await renderInspectionForm(req, res, 200);}); inspectionsRouter.post('/', async (req, res) => {  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(res, 400, { values, errors });    return renderInspectionForm(req, res, 400, { values, errors });  }  const building = await findBuilding(values.building_id);  if (!building || !can(req.user, 'CreateInspection', building)) {    return renderInspectionForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can create inspections.' } });  }  try {    const created = await createInspection(values, req.user.id);    res.redirect(303, `/inspections/${created.id}`);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderInspectionForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });      return renderInspectionForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }});
Change 7 of 9
  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res);  if (inspection.status !== 'draft') {    return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');  }  await renderInspectionForm(res, 200, { inspection, values: inspection });  await renderInspectionForm(req, res, 200, { inspection, values: inspection });
Change 8 of 9
  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res);  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(res, 400, { inspection, values, errors });    return renderInspectionForm(req, res, 400, { inspection, values, errors });  }
Change 9 of 9
  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (!can(req.user, TRANSITION_ACTIONS[req.params.action], inspection)) return forbidden(res);  const changed = await transitionInspection(inspection.id, req.params.action, req.user.id);
Show the whole src/routes/inspections.js after this change
import express from 'express';import { listInspections, findInspection, listInspectionHistory, createInspection, updateDraftInspection, transitionInspection, INSPECTION_TRANSITIONS } from '../models/inspections.js';import { listBuildings, findBuilding } from '../models/buildings.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const inspectionsRouter = express.Router(); const INSPECTION_STATUSES = ['draft', 'submitted', 'approved'];const TRANSITION_ACTIONS = { submit: 'SubmitInspection', approve: 'ApproveInspection', return: 'ReturnInspection' }; function validateInspection(input, { requireBuilding }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const findings = cleanText(input.findings, { max: 5000 });  const buildingId = parseId(input.building_id);  if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.';  if (!findings.ok) errors.findings = 'Findings must be at most 5000 characters.';  if (requireBuilding && buildingId === null) errors.building_id = 'Choose a building.';  return { errors, values: { title: title.text, findings: findings.text, building_id: buildingId } };} async function renderInspectionForm(req, res, status, { inspection = null, values = {}, errors = {} } = {}) {  res.status(status).render('inspections/form', {    title: inspection ? `Edit inspection #${inspection.id}` : 'New inspection',    action: inspection ? `/inspections/${inspection.id}/edit` : '/inspections',    inspection,    values,    errors,    buildings: inspection ? [] : (await listBuildings()).filter((building) => can(req.user, 'CreateInspection', building)),  });} async function renderInspectionPage(res, status, inspection, error = null) {  const history = await listInspectionHistory(inspection.id);  res.status(status).render('inspections/show', { title: inspection.title, inspection, history, error });} async function loadInspection(req, res) {  const id = parseId(req.params.id);  const inspection = id === null ? null : await findInspection(id);  if (!inspection || !can(req.user, 'ViewInspection', inspection)) {    notFound(req, res);    return null;  }  return inspection;} inspectionsRouter.get('/', async (req, res) => {  const status = INSPECTION_STATUSES.includes(req.query.status) ? req.query.status : null;  res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status, userId: req.user.id }), status, statuses: INSPECTION_STATUSES });}); inspectionsRouter.get('/new', async (req, res) => {  await renderInspectionForm(req, res, 200);}); inspectionsRouter.post('/', async (req, res) => {  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: true });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(req, res, 400, { values, errors });  }  const building = await findBuilding(values.building_id);  if (!building || !can(req.user, 'CreateInspection', building)) {    return renderInspectionForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can create inspections.' } });  }  try {    const created = await createInspection(values, req.user.id);    res.redirect(303, `/inspections/${created.id}`);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderInspectionForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }}); inspectionsRouter.get('/:id', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  await renderInspectionPage(res, 200, inspection);}); inspectionsRouter.get('/:id/edit', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res);  if (inspection.status !== 'draft') {    return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');  }  await renderInspectionForm(req, res, 200, { inspection, values: inspection });}); inspectionsRouter.post('/:id/edit', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (!can(req.user, 'UpdateInspection', inspection)) return forbidden(res);  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(req, res, 400, { inspection, values, errors });  }  const updated = await updateDraftInspection(inspection.id, values);  if (!updated) {    return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');  }  res.redirect(303, `/inspections/${inspection.id}`);}); // POST /inspections/:id/submit, /approve and /return share one handler.inspectionsRouter.post('/:id/:action', async (req, res, next) => {  if (!Object.hasOwn(INSPECTION_TRANSITIONS, req.params.action)) {    return next();  }  const inspection = await loadInspection(req, res);  if (!inspection) return;  if (!can(req.user, TRANSITION_ACTIONS[req.params.action], inspection)) return forbidden(res);  const changed = await transitionInspection(inspection.id, req.params.action, req.user.id);  if (!changed) {    const fresh = await findInspection(inspection.id);    return renderInspectionPage(res, 409, fresh, `This inspection is ${fresh.status}; it cannot be ${req.params.action === 'return' ? 'returned' : `${req.params.action}d`} now.`);  }  res.redirect(303, `/inspections/${inspection.id}`);});

The order inside the transition route is authorize, then attempt the transition. A user who may not approve gets 403 whatever the inspection's state, so the response does not reveal the state to someone without the right.

6. Buttons that follow the rules

Editviews/organisations/show.ejsEJS
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 2
  <div class="actions">    <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>    <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>    <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">      <button type="submit" class="btn btn-danger">Delete</button>    </form>    <% if (can('UpdateOrganisation', organisation)) { %>      <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>    <% } %>    <% if (can('CreateBuilding', organisation)) { %>      <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>    <% } %>    <% if (can('DeleteOrganisation', organisation)) { %>      <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">        <button type="submit" class="btn btn-danger">Delete</button>      </form>    <% } %>  </div>
Change 2 of 2
        <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>        <% const buildingRef = { id: building.id, organisation_id: organisation.id }; %>        <% if (can('ViewBuilding', buildingRef)) { %>          <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>        <% } else { %>          <tr><td><%= building.name %></td><td class="muted">no access</td></tr>        <% } %>
Show the whole views/organisations/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p><div class="page-header">  <h1><%= organisation.name %></h1>  <div class="actions">    <% if (can('UpdateOrganisation', organisation)) { %>      <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>    <% } %>    <% if (can('CreateBuilding', organisation)) { %>      <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>    <% } %>    <% if (can('DeleteOrganisation', organisation)) { %>      <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">        <button type="submit" class="btn btn-danger">Delete</button>      </form>    <% } %>  </div></div><% if (typeof error !== 'undefined' && error) { %>  <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Buildings</h2><% if (buildings.length === 0) { %>  <p class="empty">This organisation has no buildings yet.</p><% } else { %>  <table class="data">    <thead><tr><th>Building</th><th>Issues</th></tr></thead>    <tbody>      <% for (const building of buildings) { %>        <% const buildingRef = { id: building.id, organisation_id: organisation.id }; %>        <% if (can('ViewBuilding', buildingRef)) { %>          <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>        <% } else { %>          <tr><td><%= building.name %></td><td class="muted">no access</td></tr>        <% } %>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

Members see every building name of their organisation, but the link and the issue count only where they may view the building.

Editviews/buildings/show.ejsEJS
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  <div class="actions">    <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a>    <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">      <button type="submit" class="btn btn-danger">Delete</button>    </form>    <% if (can('UpdateBuilding', building)) { %>      <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a>    <% } %>    <% if (can('DeleteBuilding', building)) { %>      <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">        <button type="submit" class="btn btn-danger">Delete</button>      </form>    <% } %>  </div>
Show the whole views/buildings/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p><div class="page-header">  <h1><%= building.name %></h1>  <div class="actions">    <% if (can('UpdateBuilding', building)) { %>      <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a>    <% } %>    <% if (can('DeleteBuilding', building)) { %>      <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">        <button type="submit" class="btn btn-danger">Delete</button>      </form>    <% } %>  </div></div><% if (error) { %>  <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Latest issues</h2><% if (issues.length === 0) { %>  <p class="empty">No issues at this building.</p><% } else { %>  <table class="data">    <thead><tr><th>Title</th><th>Priority</th><th>Status</th><th>Occurred</th></tr></thead>    <tbody>      <% for (const issue of issues) { %>        <tr>          <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>          <td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td>          <td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td>          <td><%= formatDate(issue.occurred_at) %></td>        </tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>
Editviews/inspections/show.ejsEJS
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
    <% if (inspection.status === 'draft') { %>    <% if (inspection.status === 'draft' && can('UpdateInspection', inspection)) { %>      <a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a>    <% } %>    <% if (inspection.status === 'draft' && can('SubmitInspection', inspection)) { %>      <form method="post" action="/inspections/<%= inspection.id %>/submit"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Submit for approval</button></form>    <% } %>    <% if (inspection.status === 'submitted') { %>    <% if (inspection.status === 'submitted' && can('ReturnInspection', inspection)) { %>      <form method="post" action="/inspections/<%= inspection.id %>/return"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn">Return to draft</button></form>    <% } %>    <% if (inspection.status === 'submitted' && can('ApproveInspection', inspection)) { %>      <form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Approve</button></form>    <% } %>
Show the whole views/inspections/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/inspections">Inspections</a> / #<%= inspection.id %></p><div class="page-header">  <h1><%= inspection.title %></h1>  <div class="actions">    <% if (inspection.status === 'draft' && can('UpdateInspection', inspection)) { %>      <a class="btn" href="/inspections/<%= inspection.id %>/edit">Edit</a>    <% } %>    <% if (inspection.status === 'draft' && can('SubmitInspection', inspection)) { %>      <form method="post" action="/inspections/<%= inspection.id %>/submit"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Submit for approval</button></form>    <% } %>    <% if (inspection.status === 'submitted' && can('ReturnInspection', inspection)) { %>      <form method="post" action="/inspections/<%= inspection.id %>/return"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn">Return to draft</button></form>    <% } %>    <% if (inspection.status === 'submitted' && can('ApproveInspection', inspection)) { %>      <form method="post" action="/inspections/<%= inspection.id %>/approve" data-confirm="Approve this inspection? Approved inspections cannot be changed."><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-primary">Approve</button></form>    <% } %>  </div></div><% if (error) { %>  <div class="flash flash-error" role="alert"><%= error %></div><% } %><dl class="details">  <dt>Building</dt><dd><a href="/buildings/<%= inspection.building_id %>"><%= inspection.building_name %></a></dd>  <dt>Status</dt><dd><span class="badge status-<%= inspection.status %>"><%= inspection.status %></span></dd>  <dt>Created by</dt><dd><%= inspection.created_by_name ?? 'unknown' %></dd>  <% if (inspection.submitted_at) { %><dt>Submitted</dt><dd><%= formatDate(inspection.submitted_at) %> UTC</dd><% } %>  <% if (inspection.approved_at) { %><dt>Approved</dt><dd><%= formatDate(inspection.approved_at) %> UTC</dd><% } %></dl><h2>Findings</h2><% if (inspection.findings) { %><p class="prose"><%= inspection.findings %></p><% } else { %><p class="empty">No findings recorded yet.</p><% } %><h2>History</h2><% if (history.length === 0) { %>  <p class="muted">No status changes yet.</p><% } else { %>  <table class="data">    <thead><tr><th>When (UTC)</th><th>Change</th><th>By</th></tr></thead>    <tbody>      <% for (const h of history) { %>        <tr><td><%= formatDate(h.changed_at) %></td><td><%= h.from_status %> → <%= h.to_status %></td><td><%= h.changed_by_name ?? 'unknown' %></td></tr>      <% } %>    </tbody>  </table><% } %><%- include('../partials/foot') %>

Each button now needs two conditions: the workflow state and the permission. Remember that pattern; Module 6 replaces only the second half.

Run and inspect

Run and comparecaretaker/exit code 1 (expected)
npm test

> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"

✔ the scenario loads exactly as specified (203.912916ms)
✔ only one active assignment per user, building and role (0.803125ms)
✔ a revoked role can be granted again (1.404291ms)
✔ the My access page shows what the server loaded (77.905541ms)
✔ a correct login creates a session and shows the user (270.390959ms)
✔ a wrong password or unknown email gets the same 401 (52.716166ms)
✔ registration validates, creates a user, and logs them in (38.033041ms)
✔ registering an existing email is a field error (28.526417ms)
✔ logout destroys the session (44.4805ms)
✔ a building can be created inside an organisation (269.241834ms)
✔ a duplicate building name in the same organisation is a field error (4.802208ms)
✖ the same building name is allowed in another organisation (5.164833ms)
✔ a building with issues cannot be deleted (12.06175ms)
✖ an empty building can be deleted (3.56025ms)
✔ an organisation with buildings cannot be deleted, an empty one can (22.083042ms)
✔ a logged-in POST without a token is refused with 403 (254.551958ms)
✔ a token from another session is refused (35.575834ms)
✔ the right token in the form field works (8.76475ms)
✔ every POST form on every page carries the token (40.104041ms)
✔ the dashboard counts match the database (279.891625ms)
✔ only the buildings carol can see appear (6.324041ms)
✔ create a draft, edit it, submit it, approve it (288.398292ms)
✔ invalid transitions are refused with 409 and change nothing (11.03725ms)
✔ only drafts can be edited (4.686916ms)
✔ returning a submitted inspection makes it editable again (6.280542ms)
✔ concurrent approvals: exactly one wins (21.516417ms)
✔ unknown actions are 404 (3.175ms)
✔ the issues list contains only issues from visible buildings (548.766584ms)
✔ a filter for another tenant's building returns nothing (4.098375ms)
✔ the inspections list is scoped too (9.1455ms)
✔ organisations are listed for their members only (8.524ms)
✔ the dashboard counts only visible data (9.075875ms)
✔ view issue 101 (building 10) (435.032375ms)
✔ open the edit form for issue 101 (20.799416ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (16.541292ms)
✔ view issue 105 (building 30) and 106 (building 40) (36.104541ms)
Show 105 more lines✔ report an issue at building 20 (17.602417ms) ✔ a reporter cannot edit their own issue once it is closed (5.799792ms) ✔ only building admins may delete; refusals change nothing (13.254666ms) ✔ the edit form cannot move an issue to another building (3.4755ms) ✔ the list pages 10 at a time and reports the total (279.6575ms) ✔ pages do not overlap (17.173417ms) ✔ filters combine with AND (5.292625ms) ✔ sorting by priority puts critical first when descending (4.92475ms) ✔ unknown sort keys and SQL in the query string are ignored (27.152834ms) ✔ GET /issues lists issues from the database (269.999ms) ✔ GET /issues/101 shows one issue with its building (6.602917ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (13.624292ms) ✔ POST /issues re-renders the form with errors (4.238417ms) ✔ POST /issues stores the issue and redirects to it (7.077292ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (3.609875ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.141542ms) ✔ an issue time in the future is rejected (3.672084ms) ✔ GET /issues/101/edit shows the current values (3.797625ms) ✔ POST /issues/:id/edit changes the status and updated_at (4.052333ms) ✔ POST /issues/:id/delete removes the issue (9.406083ms) ✔ GET /organisations lists organisations with building counts (265.872375ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.303917ms) ✔ POST /organisations validates and creates (12.479542ms) ✖ POST /organisations/:id/edit renames the organisation (5.128208ms) ✔ unknown organisations are 404 (9.331083ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (336.658209ms) ✔ anonymous requests are redirected to the login page (212.658334ms) ✔ anonymous writes are refused and change nothing (10.884375ms) ✔ login and register pages stay public (5.58675ms) ✔ login issues a new session id (no session fixation) (33.14775ms) ✔ returnTo only follows local paths (31.623ms) ✖ new issues and transitions record the logged-in user (72.688458ms) ✔ the session cookie has the attributes we chose (26.782083ms) ℹ tests 69 ℹ suites 0 ℹ pass 65 ℹ fail 4 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 6684.761041 ✖ failing tests: test at test/buildings.test.js:29:1 ✖ the same building name is allowed in another organisation (5.164833ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 404 !== 303 at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/buildings.test.js:31: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: 404, expected: 303, operator: 'strictEqual', diff: 'simple' } test at test/buildings.test.js:41:1 ✖ an empty building can be deleted (3.56025ms) TypeError: Invalid URL at new URL (node:internal/url:818:25) at Request.request (/Users/you/code/caretaker/node_modules/superagent/lib/node/index.js:870:15) at Request.end (/Users/you/code/caretaker/node_modules/superagent/lib/node/index.js:1168:10) at /Users/you/code/caretaker/node_modules/supertest/lib/test.js:390:15 at /Users/you/code/caretaker/node_modules/supertest/lib/test.js:211:9 at Array.forEach (<anonymous>) at /Users/you/code/caretaker/node_modules/supertest/lib/test.js:210:17 at /Users/you/code/caretaker/node_modules/supertest/lib/test.js:132:5 at /Users/you/code/caretaker/node_modules/supertest/lib/test.js:52:7 at Array.forEach (<anonymous>) { code: 'ERR_INVALID_URL', input: 'http://127.0.0.1:59864undefined/delete', response: undefined } test at test/organisations.test.js:41:1 ✖ POST /organisations/:id/edit renames the organisation (5.128208ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 404 !== 303 at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/organisations.test.js:43: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: 404, expected: 303, operator: 'strictEqual', diff: 'simple' } test at test/require-login.test.js:61:1 ✖ new issues and transitions record the logged-in user (72.688458ms) TypeError: Cannot read properties of undefined (reading 'changed_by') at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/require-login.test.js:70:32) 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)

Again, the failures are old tests that relied on Carol reaching Harbour Lets. Fix them so they use data Carol is allowed to touch:

Edittest/organisations.test.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
test('POST /organisations/:id/edit renames the organisation', async () => {  const res = await agent.post('/organisations/2/edit').type('form').send({ name: 'Harbour Lets Ltd' });  const res = await agent.post('/organisations/1/edit').type('form').send({ name: 'Liffey Estates Ltd' });  assert.equal(res.status, 303);  const page = await agent.get('/organisations/2');  assert.match(page.text, /<h1>Harbour Lets Ltd<\/h1>/);  const page = await agent.get('/organisations/1');  assert.match(page.text, /<h1>Liffey Estates Ltd<\/h1>/);});
Show the whole test/organisations.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()); test('GET /organisations lists organisations with building counts', async () => {  const res = await agent.get('/organisations');  assert.equal(res.status, 200);  assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/);  assert.doesNotMatch(res.text, /Harbour Lets/, 'carol is not a member of Harbour Lets');}); test('GET /organisations/1 shows its buildings, not other organisations\' buildings', async () => {  const res = await agent.get('/organisations/1');  assert.equal(res.status, 200);  assert.match(res.text, /Dublin Offices/);  assert.match(res.text, /Cork Apartments/);  assert.doesNotMatch(res.text, /Galway Studios/);}); test('POST /organisations validates and creates', async () => {  const bad = await agent.post('/organisations').type('form').send({ name: ' ' });  assert.equal(bad.status, 400);  assert.match(bad.text, /Name must be between 2 and 100 characters/);   const good = await agent.post('/organisations').type('form').send({ name: 'Riverside Lettings' });  assert.equal(good.status, 303);  const page = await agent.get(good.headers.location);  assert.match(page.text, /<h1>Riverside Lettings<\/h1>/);}); test('POST /organisations/:id/edit renames the organisation', async () => {  const res = await agent.post('/organisations/1/edit').type('form').send({ name: 'Liffey Estates Ltd' });  assert.equal(res.status, 303);  const page = await agent.get('/organisations/1');  assert.match(page.text, /<h1>Liffey Estates Ltd<\/h1>/);}); test('unknown organisations are 404', async () => {  assert.equal((await agent.get('/organisations/999')).status, 404);  assert.equal((await agent.post('/organisations/999/edit').type('form').send({ name: 'Nope' })).status, 404);});
Edittest/buildings.test.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 2
test('the same building name is allowed in another organisation', async () => {  const res = await agent.post('/organisations/2/buildings').type('form').send({ name: 'Cork Apartments' });  const created = await agent.post('/organisations').type('form').send({ name: 'Carol Consulting' });  const res = await agent.post(`${created.headers.location}/buildings`).type('form').send({ name: 'Cork Apartments' });  assert.equal(res.status, 303);});
Change 2 of 2
  const created = await agent.post('/organisations/2/buildings').type('form').send({ name: 'Temporary Annex' });  const created = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Temporary Annex' });  const res = await agent.post(`${created.headers.location}/delete`);  assert.equal(res.status, 303);  assert.equal(res.headers.location, '/organisations/2');  assert.equal(res.headers.location, '/organisations/1');
Show the whole test/buildings.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()); test('a building can be created inside an organisation', async () => {  const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Galway Townhouse' });  assert.equal(res.status, 303);  const page = await agent.get(res.headers.location);  assert.match(page.text, /<h1>Galway Townhouse<\/h1>/);  assert.match(page.text, /Liffey Estates/);}); test('a duplicate building name in the same organisation is a field error', async () => {  const res = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Cork Apartments' });  assert.equal(res.status, 400);  assert.match(res.text, /already has a building with that name/);}); test('the same building name is allowed in another organisation', async () => {  const created = await agent.post('/organisations').type('form').send({ name: 'Carol Consulting' });  const res = await agent.post(`${created.headers.location}/buildings`).type('form').send({ name: 'Cork Apartments' });  assert.equal(res.status, 303);}); test('a building with issues cannot be deleted', async () => {  const res = await agent.post('/buildings/10/delete');  assert.equal(res.status, 409);  assert.match(res.text, /still has maintenance issues/);  assert.equal((await agent.get('/buildings/10')).status, 200);}); test('an empty building can be deleted', async () => {  const created = await agent.post('/organisations/1/buildings').type('form').send({ name: 'Temporary Annex' });  const res = await agent.post(`${created.headers.location}/delete`);  assert.equal(res.status, 303);  assert.equal(res.headers.location, '/organisations/1');  assert.equal((await agent.get(created.headers.location)).status, 404);}); test('an organisation with buildings cannot be deleted, an empty one can', async () => {  const blocked = await agent.post('/organisations/1/delete');  assert.equal(blocked.status, 409);  assert.match(blocked.text, /still has buildings/);   const created = await agent.post('/organisations').type('form').send({ name: 'Short-lived Ltd' });  const res = await agent.post(`${created.headers.location}/delete`);  assert.equal(res.status, 303);  assert.equal((await agent.get(created.headers.location)).status, 404);});

One more: in test/require-login.test.js, Dave submitted inspection 203. That is Carol's draft at a building where Dave is only a reporter, so it is now 403, correctly. The test is about recording changed_by, so let Dave create and submit his own inspection at building 10, where he is an inspector:

Edittest/require-login.test.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  await dave.post('/inspections/203/submit');  const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = 203 AND to_status = 'submitted'");  const inspection = await dave.post('/inspections').type('form').send({ building_id: '10', title: 'Lift alarm check', findings: '' });  const inspectionId = Number(inspection.headers.location.split('/').pop());  await dave.post(`/inspections/${inspectionId}/submit`);  const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = $1 AND to_status = 'submitted'", [inspectionId]);  assert.equal(history.rows[0].changed_by, 4);
Show the whole test/require-login.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, anonymousAgent, csrfTokenFrom } from './helpers.js'; before(resetDatabase);after(() => pool.end()); function sessionId(res) {  const cookie = (res.headers['set-cookie'] ?? []).find((c) => c.startsWith('caretaker.sid='));  return cookie ? cookie.split(';')[0] : null;} test('anonymous requests are redirected to the login page', async () => {  for (const path of ['/', '/issues', '/issues/101', '/organisations', '/inspections/201', '/buildings/10']) {    const res = await request(app).get(path);    assert.equal(res.status, 303, path);    assert.equal(res.headers.location, '/login', path);  }}); test('anonymous writes are refused and change nothing', async () => {  const withoutToken = await request(app).post('/issues/101/delete');  assert.equal(withoutToken.status, 403);  const agent = await anonymousAgent();  const withToken = await agent.post('/issues/101/delete');  assert.equal(withToken.status, 303);  assert.equal(withToken.headers.location, '/login');  const { rowCount } = await pool.query('SELECT 1 FROM issues WHERE id = 101');  assert.equal(rowCount, 1);}); test('login and register pages stay public', async () => {  assert.equal((await request(app).get('/login')).status, 200);  assert.equal((await request(app).get('/register')).status, 200);  assert.equal((await request(app).get('/css/style.css')).status, 200);}); test('login issues a new session id (no session fixation)', async () => {  const agent = request.agent(app);  await agent.get('/issues');  const page = await agent.get('/login');  const before = sessionId(page) ?? 'cookie set by the first request';  const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) });  const afterLogin = sessionId(login);  assert.ok(afterLogin);  assert.notEqual(afterLogin, before);  assert.equal(login.headers.location, '/issues', 'returns to the page the user wanted');}); test('returnTo only follows local paths', async () => {  const agent = request.agent(app);  await agent.get('//evil.test/phish');  const page = await agent.get('/login');  const login = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123', _csrf: csrfTokenFrom(page.text) });  assert.equal(login.headers.location, '/');}); test('new issues and transitions record the logged-in user', async () => {  const dave = await loginAs('dave');  const res = await dave.post('/issues').type('form').send({ title: 'Loose handrail on stairs', building_id: '20', priority: 'medium', occurred_at: '2026-11-21T08:00', reported_by: '1' });  const id = Number(res.headers.location.split('/').pop());  const { rows } = await pool.query('SELECT reported_by FROM issues WHERE id = $1', [id]);  assert.equal(rows[0].reported_by, 4, 'reported_by comes from the session, not the form');   const inspection = await dave.post('/inspections').type('form').send({ building_id: '10', title: 'Lift alarm check', findings: '' });  const inspectionId = Number(inspection.headers.location.split('/').pop());  await dave.post(`/inspections/${inspectionId}/submit`);  const history = await pool.query("SELECT changed_by FROM inspection_status_changes WHERE inspection_id = $1 AND to_status = 'submitted'", [inspectionId]);  assert.equal(history.rows[0].changed_by, 4);}); test('the session cookie has the attributes we chose', async () => {  const agent = await anonymousAgent();  const res = await agent.post('/login').type('form').send({ email: 'alice@example.test', password: 'password123' });  const cookie = res.headers['set-cookie'].find((c) => c.startsWith('caretaker.sid='));  assert.match(cookie, /HttpOnly/);  assert.match(cookie, /SameSite=Lax/);  assert.match(cookie, /Expires=/);  assert.doesNotMatch(cookie, /Secure/, 'not Secure in tests: they use plain HTTP');});

And add the remaining matrix rows. As before, each row lists every user's status:

Create filetest/resource-authz.test.jsJavaScript
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()); async function statusesFor(request, users = USERS) {  const result = {};  for (const name of users) result[name] = (await request(agents[name])).status;  return result;} test('organisation 1: view and update', async () => {  assert.deepEqual(await statusesFor((a) => a.get('/organisations/1')),    { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });  assert.deepEqual(await statusesFor((a) => a.get('/organisations/1/edit')),    { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });}); test('ravi is still a member of organisation 2 but can see none of its buildings', async () => {  assert.equal((await agents.ravi.get('/organisations/2')).status, 200);  assert.equal((await agents.ravi.get('/buildings/30')).status, 404);}); test('building 10: view, update, delete', async () => {  assert.deepEqual(await statusesFor((a) => a.get('/buildings/10')),    { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });  assert.deepEqual(await statusesFor((a) => a.get('/buildings/10/edit')),    { alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });  assert.deepEqual(await statusesFor((a) => a.post('/buildings/10/delete'), ['alice', 'bob', 'dave', 'nora']),    { alice: 403, bob: 404, dave: 403, nora: 404 }, 'only org_admin may delete a building');}); test('creating buildings needs org_admin', async () => {  assert.deepEqual(await statusesFor((a) => a.get('/organisations/1/buildings/new')),    { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 });}); test('creating an organisation makes the creator its admin', async () => {  const res = await agents.nora.post('/organisations').type('form').send({ name: 'Nora Property Services' });  assert.equal(res.status, 303);  assert.equal((await agents.nora.get(`${res.headers.location}/edit`)).status, 200);  assert.equal((await agents.alice.get(res.headers.location)).status, 404);}); test('inspections: view 201, open the edit form for draft 203', async () => {  assert.deepEqual(await statusesFor((a) => a.get('/inspections/201')),    { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 });  assert.deepEqual(await statusesFor((a) => a.get('/inspections/203/edit')),    { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 }, '203 is carol\'s draft at building 20');}); test('approve inspection 201 (dave\'s): only building admins', async () => {  assert.deepEqual(await statusesFor((a) => a.post('/inspections/201/approve'), ['bob', 'dave', 'nora', 'ravi']),    { bob: 404, dave: 403, nora: 404, ravi: 404 });  assert.equal((await agents.alice.post('/inspections/201/approve')).status, 303);}); test('creating an inspection needs inspector or building_admin at the chosen building', async () => {  const form = (building) => ({ building_id: String(building), title: 'Spot check', findings: '' });  assert.equal((await agents.dave.post('/inspections').type('form').send(form(10))).status, 303, 'dave is inspector at 10');  assert.equal((await agents.dave.post('/inspections').type('form').send(form(20))).status, 400, 'dave is only reporter at 20');  assert.equal((await agents.alice.post('/inspections').type('form').send(form(30))).status, 400, 'building 30 is another tenant');});
Run and comparecaretaker/
npm test

> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"

✔ the scenario loads exactly as specified (204.26725ms)
✔ only one active assignment per user, building and role (1.028166ms)
✔ a revoked role can be granted again (1.075333ms)
✔ the My access page shows what the server loaded (73.669084ms)
✔ a correct login creates a session and shows the user (247.46325ms)
✔ a wrong password or unknown email gets the same 401 (53.21725ms)
✔ registration validates, creates a user, and logs them in (39.065083ms)
✔ registering an existing email is a field error (26.662542ms)
✔ logout destroys the session (41.624375ms)
✔ a building can be created inside an organisation (276.549125ms)
✔ a duplicate building name in the same organisation is a field error (4.582291ms)
✔ the same building name is allowed in another organisation (8.89025ms)
✔ a building with issues cannot be deleted (11.911125ms)
✔ an empty building can be deleted (9.50075ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.261167ms)
✔ a logged-in POST without a token is refused with 403 (274.668916ms)
✔ a token from another session is refused (37.512458ms)
✔ the right token in the form field works (8.975625ms)
✔ every POST form on every page carries the token (37.916125ms)
✔ the dashboard counts match the database (266.588334ms)
✔ only the buildings carol can see appear (4.770917ms)
✔ create a draft, edit it, submit it, approve it (296.03475ms)
✔ invalid transitions are refused with 409 and change nothing (11.9695ms)
✔ only drafts can be edited (4.851125ms)
✔ returning a submitted inspection makes it editable again (7.003584ms)
✔ concurrent approvals: exactly one wins (24.009ms)
✔ unknown actions are 404 (3.485625ms)
✔ the issues list contains only issues from visible buildings (545.131042ms)
✔ a filter for another tenant's building returns nothing (4.034792ms)
✔ the inspections list is scoped too (10.9385ms)
✔ organisations are listed for their members only (8.4185ms)
✔ the dashboard counts only visible data (6.195542ms)
✔ view issue 101 (building 10) (474.839834ms)
✔ open the edit form for issue 101 (25.94425ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.548ms)
✔ view issue 105 (building 30) and 106 (building 40) (35.706125ms)
Show 49 more lines✔ report an issue at building 20 (19.382834ms) ✔ a reporter cannot edit their own issue once it is closed (6.292167ms) ✔ only building admins may delete; refusals change nothing (13.822667ms) ✔ the edit form cannot move an issue to another building (3.319167ms) ✔ the list pages 10 at a time and reports the total (292.114958ms) ✔ pages do not overlap (20.744417ms) ✔ filters combine with AND (5.348292ms) ✔ sorting by priority puts critical first when descending (4.974708ms) ✔ unknown sort keys and SQL in the query string are ignored (27.851166ms) ✔ GET /issues lists issues from the database (253.828458ms) ✔ GET /issues/101 shows one issue with its building (5.72975ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (13.5035ms) ✔ POST /issues re-renders the form with errors (4.741042ms) ✔ POST /issues stores the issue and redirects to it (7.570584ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (3.625292ms) ✔ the stored row has the cleaned values and ignores a client-sent status (3.650625ms) ✔ an issue time in the future is rejected (3.817708ms) ✔ GET /issues/101/edit shows the current values (8.467333ms) ✔ POST /issues/:id/edit changes the status and updated_at (4.695291ms) ✔ POST /issues/:id/delete removes the issue (9.934042ms) ✔ GET /organisations lists organisations with building counts (266.54175ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.834125ms) ✔ POST /organisations validates and creates (12.088042ms) ✔ POST /organisations/:id/edit renames the organisation (8.724333ms) ✔ unknown organisations are 404 (5.931209ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (344.962208ms) ✔ anonymous requests are redirected to the login page (213.302584ms) ✔ anonymous writes are refused and change nothing (11.339167ms) ✔ login and register pages stay public (5.782333ms) ✔ login issues a new session id (no session fixation) (32.507875ms) ✔ returnTo only follows local paths (30.997417ms) ✔ new issues and transitions record the logged-in user (76.22ms) ✔ the session cookie has the attributes we chose (28.132417ms) ✔ organisation 1: view and update (455.244583ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (5.854916ms) ✔ building 10: view, update, delete (45.879583ms) ✔ creating buildings needs org_admin (16.059834ms) ✔ creating an organisation makes the creator its admin (8.169042ms) ✔ inspections: view 201, open the edit form for draft 203 (34.126083ms) ✔ approve inspection 201 (dave's): only building admins (14.062917ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (10.477084ms) ℹ tests 77 ℹ suites 0 ℹ pass 77 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 7456.309917
Server terminal (leave it running)caretaker/
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000
localhost:3000/organisations/2signed in as ravi
Ravi is still a member of Harbour Lets: he sees the organisation and its building names, but no access to any building.
Ravi is still a member of Harbour Lets: he sees the organisation and its building names, but no access to any building.
localhost:3000/inspections/201signed in as dave
Dave views his own submitted inspection 201. Approve and Return are not offered: he is not a building admin.
Dave views his own submitted inspection 201. Approve and Return are not offered: he is not a building admin.

Experiment

Predict Alice is building_admin at building 10 and created inspection 202 herself. Can she approve it now?
Run and comparecaretaker/
rm -f /tmp/alice.txt
TOKEN=$(curl -s -c /tmp/alice.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/alice.txt -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=password123
TOKEN=$(curl -s -b /tmp/alice.txt http://localhost:3000/account | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -si -b /tmp/alice.txt -X POST http://localhost:3000/inspections/202/approve -d _csrf=$TOKEN | head -1
HTTP/1.1 303 See Other
Reveal Answer

Yes: our rules say building admins may approve, and Alice is one. But the access matrix in lesson 5.1 says no: nobody may approve an inspection they created. That is a separation-of-duties rule, and we have not implemented it. The next lesson adds it, and on the way we will count how many places a single new rule has to touch.

Ctrl+C Stop the server in the server terminal.
Run and comparecaretaker/
npm run db:seed

> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js

seeded the Caretaker scenario

Checkpoint

Run and comparecaretaker/
npm test

> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"

✔ the scenario loads exactly as specified (216.931375ms)
✔ only one active assignment per user, building and role (1.245ms)
✔ a revoked role can be granted again (1.283334ms)
✔ the My access page shows what the server loaded (74.801292ms)
✔ a correct login creates a session and shows the user (273.406459ms)
✔ a wrong password or unknown email gets the same 401 (54.228959ms)
✔ registration validates, creates a user, and logs them in (39.379833ms)
✔ registering an existing email is a field error (30.72075ms)
✔ logout destroys the session (45.71675ms)
✔ a building can be created inside an organisation (332.188167ms)
✔ a duplicate building name in the same organisation is a field error (4.649334ms)
✔ the same building name is allowed in another organisation (9.62975ms)
✔ a building with issues cannot be deleted (12.54525ms)
✔ an empty building can be deleted (9.918375ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.951542ms)
✔ a logged-in POST without a token is refused with 403 (270.449458ms)
✔ a token from another session is refused (36.759209ms)
✔ the right token in the form field works (9.648167ms)
✔ every POST form on every page carries the token (41.054916ms)
✔ the dashboard counts match the database (272.697667ms)
✔ only the buildings carol can see appear (4.851375ms)
✔ create a draft, edit it, submit it, approve it (300.814084ms)
✔ invalid transitions are refused with 409 and change nothing (13.075666ms)
✔ only drafts can be edited (5.063291ms)
✔ returning a submitted inspection makes it editable again (8.451458ms)
✔ concurrent approvals: exactly one wins (24.804834ms)
✔ unknown actions are 404 (4.068084ms)
✔ the issues list contains only issues from visible buildings (549.56875ms)
✔ a filter for another tenant's building returns nothing (4.627375ms)
✔ the inspections list is scoped too (10.08725ms)
✔ organisations are listed for their members only (9.761542ms)
✔ the dashboard counts only visible data (7.777208ms)
✔ view issue 101 (building 10) (461.205958ms)
✔ open the edit form for issue 101 (21.041125ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.155ms)
✔ view issue 105 (building 30) and 106 (building 40) (38.030958ms)
Show 49 more lines✔ report an issue at building 20 (20.712333ms) ✔ a reporter cannot edit their own issue once it is closed (6.4965ms) ✔ only building admins may delete; refusals change nothing (14.603166ms) ✔ the edit form cannot move an issue to another building (3.4325ms) ✔ the list pages 10 at a time and reports the total (281.002417ms) ✔ pages do not overlap (16.533916ms) ✔ filters combine with AND (5.497416ms) ✔ sorting by priority puts critical first when descending (5.06975ms) ✔ unknown sort keys and SQL in the query string are ignored (28.026083ms) ✔ GET /issues lists issues from the database (277.109083ms) ✔ GET /issues/101 shows one issue with its building (6.091708ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.451125ms) ✔ POST /issues re-renders the form with errors (5.184833ms) ✔ POST /issues stores the issue and redirects to it (7.884167ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (3.659541ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.020959ms) ✔ an issue time in the future is rejected (3.510583ms) ✔ GET /issues/101/edit shows the current values (4.101833ms) ✔ POST /issues/:id/edit changes the status and updated_at (3.96025ms) ✔ POST /issues/:id/delete removes the issue (8.9425ms) ✔ GET /organisations lists organisations with building counts (273.019917ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.768292ms) ✔ POST /organisations validates and creates (11.368167ms) ✔ POST /organisations/:id/edit renames the organisation (8.546833ms) ✔ unknown organisations are 404 (5.905125ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (338.823708ms) ✔ anonymous requests are redirected to the login page (222.813958ms) ✔ anonymous writes are refused and change nothing (11.345583ms) ✔ login and register pages stay public (6.544917ms) ✔ login issues a new session id (no session fixation) (32.621917ms) ✔ returnTo only follows local paths (31.666ms) ✔ new issues and transitions record the logged-in user (79.051708ms) ✔ the session cookie has the attributes we chose (27.524416ms) ✔ organisation 1: view and update (477.212125ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (6.412875ms) ✔ building 10: view, update, delete (47.307042ms) ✔ creating buildings needs org_admin (12.716209ms) ✔ creating an organisation makes the creator its admin (7.647417ms) ✔ inspections: view 201, open the edit form for draft 203 (36.172708ms) ✔ approve inspection 201 (dave's): only building admins (14.25575ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (9.786542ms) ℹ tests 77 ℹ suites 0 ℹ pass 77 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 7653.580583
Run and comparecaretaker/
git add -A
git commit -m "Authorize organisations, buildings and inspections"
[main 089e050] Authorize organisations, buildings and inspections
 12 files changed, 202 insertions(+), 47 deletions(-)
 create mode 100644 test/resource-authz.test.js
Symptom A page you expected to see is 404

Print what the server loaded: open My access as that user. Then find the action in can() and check which role it requires and whether the resource row has the organisation_id the rule uses.

Symptom TypeError: Cannot read properties of undefined (reading 'assignments')

can() was called with a user that has no access, for example in a test that builds a user object by hand. Users must come from loadUser.

Recap and next step

Seventeen actions now have rules. Every route loads, authorizes, then acts; templates ask the same can(); creating an organisation grants its admin role in the same transaction. Permission checks run before workflow checks.

Our rules work. But look at what one missing requirement (no self-approval) would cost to add, and what the switch statement will look like when the product asks for the next role. That is the next lesson.