Caretaker Express · PostgreSQL · Cedar

Module 5 · Authorization before Cedar

5.3 Lists and tenant isolation

Scope every list, count and dropdown to the buildings the user can see, in SQL, with one shared condition that must agree with the JavaScript rules.

≈ 65 min 29 steps 177 lines of code Replay verified

Starting point

Single issues are protected: /issues/105 is 404 for Alice. But lists, counts and dropdowns still read every row in the database.

Outcome

Text
src/models/scope.js        (new: visibleBuildingCondition)test/isolation.test.js     (new)

The issues list, the inspections list, the dashboard, the organisations list and the building filter show only data from buildings the user can see. Each list function requires a user ID, so a forgotten argument fails loudly instead of returning everything.

The problem

Log in as Alice and open the issues list:

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/issues?priority=criticalsigned in as alice
Before: Alice's list, filtered to critical issues, includes Harbour Lets' boiler issue at Galway Studios.
Before: Alice's list, filtered to critical issues, includes Harbour Lets' boiler issue at Galway Studios.

She cannot open issue 105, but she can read its title, building and priority in the list. The dashboard counts both companies' issues, the building filter lists Harbour Lets' buildings, and the organisations page lists every organisation. Each one is a cross-tenant leak.

Ctrl+C Stop the server in the server terminal.

Why not reuse can() on each row? We could load all issues and keep the ones where can(user, 'ViewIssue', issue) is true. That works for ten rows and fails at scale: the database would return every tenant's issues on every page view, and LIMIT 10 OFFSET 20 would be applied before our filter, so pages would have random numbers of rows and the total would be wrong. A list must be filtered in the query, so that paging and counting happen on the right set.

Build it

1. One SQL condition for "buildings this user can see"

Create src/models/scope.js:

Create filesrc/models/scope.jsJavaScript
// SQL condition that is true when the building aliased `buildingAlias` is visible to the user// whose id is the SQL parameter `userParam` (for example '$3').//// It MUST agree with rolesAtBuilding() in src/authz/rules.js: a building is visible if the user// holds any active role there, or is org_admin of the organisation that owns it.export function visibleBuildingCondition(buildingAlias, userParam) {  return `(    ${buildingAlias}.id IN (      SELECT building_id FROM building_role_assignments WHERE user_id = ${userParam} AND revoked_at IS NULL    )    OR ${buildingAlias}.organisation_id IN (      SELECT organisation_id FROM memberships WHERE user_id = ${userParam} AND role = 'org_admin'    )  )`;}

This is authorization logic in SQL. The same rule now exists twice: once in rolesAtBuilding (JavaScript, for single resources) and once here (SQL, for lists). If one changes and the other does not, a user could see a row in the list that they cannot open, or, worse, open a row they should not see listed. Keep this pair in mind; Module 8 builds a test that checks they agree for every user and every issue.

Notice that the function only ever inserts our own SQL and a placeholder name such as $3. The user ID still travels as a parameter.

2. Scope the issues list

Editsrc/models/issues.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 { visibleBuildingCondition } from './scope.js';
Change 2 of 2
export async function listIssues({ page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null } = {}) {  const where = [];  const params = [];export async function listIssues({ userId, page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null }) {  if (!userId) {    throw new Error('listIssues requires the id of the user the list is for');  }  const params = [userId];  const where = [visibleBuildingCondition('s', '$1')];
Show the whole src/models/issues.js after this change
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; const ISSUE_COLUMNS = `  e.id, e.building_id, s.name AS building_name, s.organisation_id,  e.title, e.description, e.priority, e.status, e.reported_by,  (SELECT u.name FROM users u WHERE u.id = e.reported_by) AS reported_by_name,  e.occurred_at, e.created_at, e.updated_at`; // Sort keys a client may ask for. Keys come from the URL; the SQL is ours.export const ISSUE_SORTS = {  occurred_at: 'e.occurred_at',  title: 'e.title',  building: 's.name',  priority: "array_position(ARRAY['low', 'medium', 'high', 'critical'], e.priority)",  status: "array_position(ARRAY['open', 'investigating', 'closed'], e.status)",}; export async function listIssues({ userId, page = 1, perPage = 10, sort = 'occurred_at', dir = 'desc', status = null, priority = null, buildingId = null }) {  if (!userId) {    throw new Error('listIssues requires the id of the user the list is for');  }  const params = [userId];  const where = [visibleBuildingCondition('s', '$1')];  if (status) {    params.push(status);    where.push(`e.status = $${params.length}`);  }  if (priority) {    params.push(priority);    where.push(`e.priority = $${params.length}`);  }  if (buildingId) {    params.push(buildingId);    where.push(`e.building_id = $${params.length}`);  }  const whereSql = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';  const direction = dir === 'asc' ? 'ASC' : 'DESC';  const orderSql = `${ISSUE_SORTS[sort] ?? ISSUE_SORTS.occurred_at} ${direction}, e.id ${direction}`;   const countResult = await query(    `SELECT count(*)::int AS total FROM issues e JOIN buildings s ON s.id = e.building_id ${whereSql}`,    params,  );  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     ${whereSql}     ORDER BY ${orderSql}     LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,    [...params, perPage, (page - 1) * perPage],  );  return { issues: rows, total: countResult.rows[0].total };} export async function listRecentIssuesForBuilding(buildingId, limit = 10) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.building_id = $1     ORDER BY e.occurred_at DESC, e.id DESC     LIMIT $2`,    [buildingId, limit],  );  return rows;} export async function findIssue(id) {  const { rows } = await query(    `SELECT ${ISSUE_COLUMNS}     FROM issues e     JOIN buildings s ON s.id = e.building_id     WHERE e.id = $1`,    [id],  );  return rows[0] ?? null;} export async function createIssue({ building_id, title, description, priority, occurred_at }, reportedBy) {  const { rows } = await query(    `INSERT INTO issues (building_id, title, description, priority, occurred_at, reported_by)     VALUES ($1, $2, $3, $4, $5, $6)     RETURNING id`,    [building_id, title, description, priority, occurred_at, reportedBy],  );  return rows[0];} export async function updateIssue(id, { building_id, title, description, priority, status, occurred_at }) {  const { rows } = await query(    `UPDATE issues     SET building_id = $2, title = $3, description = $4, priority = $5, status = $6, occurred_at = $7, updated_at = now()     WHERE id = $1     RETURNING id`,    [id, building_id, title, description, priority, status, occurred_at],  );  return rows[0] ?? null;} export async function deleteIssue(id) {  const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);  return rowCount === 1;}

The user's condition is always the first WHERE clause and $1. The filters that follow are added with AND, so they can only narrow the visible set, never widen it. A ?building=30 filter from Alice produces visible AND e.building_id = 30, which is empty.

3. Scope inspections, organisations and the dashboard

Editsrc/models/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 2
import { query, withTransaction } from '../db.js';import { visibleBuildingCondition } from './scope.js';
Change 2 of 2
export async function listInspections({ status = null } = {}) {  const params = [];  let whereSql = '';export async function listInspections({ userId, status = null }) {  if (!userId) {    throw new Error('listInspections requires the id of the user the list is for');  }  const params = [userId];  let whereSql = `WHERE ${visibleBuildingCondition('s', '$1')}`;  if (status) {    params.push(status);    whereSql = 'WHERE a.status = $1';    whereSql += ' AND a.status = $2';  }
Show the whole src/models/inspections.js after this change
import { query, withTransaction } from '../db.js';import { visibleBuildingCondition } from './scope.js'; // The workflow. Each action moves an inspection from exactly one status to another.export const INSPECTION_TRANSITIONS = {  submit: { from: 'draft', to: 'submitted' },  approve: { from: 'submitted', to: 'approved' },  return: { from: 'submitted', to: 'draft' },}; const INSPECTION_COLUMNS = `  a.id, a.building_id, s.name AS building_name, s.organisation_id, a.title, a.findings, a.status, a.created_by,  (SELECT u.name FROM users u WHERE u.id = a.created_by) AS created_by_name,  a.submitted_at, a.approved_at, a.created_at, a.updated_at`; export async function listInspections({ userId, status = null }) {  if (!userId) {    throw new Error('listInspections requires the id of the user the list is for');  }  const params = [userId];  let whereSql = `WHERE ${visibleBuildingCondition('s', '$1')}`;  if (status) {    params.push(status);    whereSql += ' AND a.status = $2';  }  const { rows } = await query(    `SELECT ${INSPECTION_COLUMNS}     FROM inspections a     JOIN buildings s ON s.id = a.building_id     ${whereSql}     ORDER BY a.updated_at DESC, a.id DESC`,    params,  );  return rows;} export async function findInspection(id) {  const { rows } = await query(`SELECT ${INSPECTION_COLUMNS} FROM inspections a JOIN buildings s ON s.id = a.building_id WHERE a.id = $1`, [id]);  return rows[0] ?? null;} export async function listInspectionHistory(inspectionId) {  const { rows } = await query(    `SELECT h.from_status, h.to_status, h.changed_at, u.name AS changed_by_name     FROM inspection_status_changes h LEFT JOIN users u ON u.id = h.changed_by     WHERE h.inspection_id = $1 ORDER BY h.changed_at, h.id`,    [inspectionId],  );  return rows;} export async function createInspection({ building_id, title, findings }, createdBy) {  const { rows } = await query(    'INSERT INTO inspections (building_id, title, findings, created_by) VALUES ($1, $2, $3, $4) RETURNING id',    [building_id, title, findings, createdBy],  );  return rows[0];} // Only drafts can be edited. Returns false if the inspection is not (or no longer) a draft.export async function updateDraftInspection(id, { title, findings }) {  const { rowCount } = await query(    "UPDATE inspections SET title = $2, findings = $3, updated_at = now() WHERE id = $1 AND status = 'draft'",    [id, title, findings],  );  return rowCount === 1;} // Applies a transition atomically. Returns false if the inspection was not in the expected status.export async function transitionInspection(id, action, changedBy) {  const transition = INSPECTION_TRANSITIONS[action];  if (!transition) {    throw new Error(`Unknown inspection action ${action}`);  }  return withTransaction(async (client) => {    const { rowCount } = await client.query(      `UPDATE inspections       SET status = $3,           updated_at = now(),           submitted_at = CASE WHEN $3 = 'submitted' THEN now() ELSE submitted_at END,           approved_at = CASE WHEN $3 = 'approved' THEN now() ELSE approved_at END       WHERE id = $1 AND status = $2`,      [id, transition.from, transition.to],    );    if (rowCount === 0) {      return false;    }    await client.query(      'INSERT INTO inspection_status_changes (inspection_id, from_status, to_status, changed_by) VALUES ($1, $2, $3, $4)',      [id, transition.from, transition.to, changedBy],    );    return true;  });}

Organisations are visible to their members, whatever their role:

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.
export async function listOrganisations() {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;}
Show the whole src/models/organisations.js after this change
import { query } 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;} export async function createOrganisation({ name }) {  const { rows } = await query('INSERT INTO organisations (name) VALUES ($1) RETURNING id', [name]);  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;}

The building filter on the issues list needs the visible buildings. Add a function to src/models/buildings.js:

Editsrc/models/buildings.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; export async function listVisibleBuildings(userId) {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     WHERE ${visibleBuildingCondition('s', '$1')}     ORDER BY o.name, s.name`,    [userId],  );  return rows;}
Show the whole src/models/buildings.js after this change
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; export async function listVisibleBuildings(userId) {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     WHERE ${visibleBuildingCondition('s', '$1')}     ORDER BY o.name, s.name`,    [userId],  );  return rows;} export async function listBuildings() {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     ORDER BY o.name, s.name`,  );  return rows;} export async function findBuilding(id) {  const { rows } = await query(    `SELECT s.id, s.name, s.organisation_id, o.name AS organisation_name, s.created_at, s.updated_at     FROM buildings s     JOIN organisations o ON o.id = s.organisation_id     WHERE s.id = $1`,    [id],  );  return rows[0] ?? null;} export async function createBuilding({ organisation_id, name }) {  const { rows } = await query(    'INSERT INTO buildings (organisation_id, name) VALUES ($1, $2) RETURNING id',    [organisation_id, name],  );  return rows[0];} export async function updateBuilding(id, { name }) {  const { rows } = await query('UPDATE buildings SET name = $2, updated_at = now() WHERE id = $1 RETURNING id', [id, name]);  return rows[0] ?? null;} export async function deleteBuilding(id) {  const { rowCount } = await query('DELETE FROM buildings WHERE id = $1', [id]);  return rowCount === 1;} export async function listBuildingsForOrganisation(organisationId) {  const { rows } = await query(    `SELECT s.id, s.name, count(e.id)::int AS issue_count     FROM buildings s     LEFT JOIN issues e ON e.building_id = s.id     WHERE s.organisation_id = $1     GROUP BY s.id     ORDER BY s.name`,    [organisationId],  );  return rows;}

The dashboard runs four queries; each needs the condition. Replace src/models/dashboard.js:

Replace whole filesrc/models/dashboard.jsJavaScript
Highlighted lines are new or changed (19).
import { query } from '../db.js';import { listIssues } from './issues.js';import { visibleBuildingCondition } from './scope.js'; export async function getDashboard(userId) {  const visible = visibleBuildingCondition('s', '$1');  const [issueCounts, inspectionCounts, buildings, recent] = await Promise.all([    query(      `SELECT count(*) FILTER (WHERE e.status <> 'closed')::int AS open_issues,              count(*) FILTER (WHERE e.status <> 'closed' AND e.priority IN ('high', 'critical'))::int AS serious_open_issues       FROM issues e       JOIN buildings s ON s.id = e.building_id       WHERE ${visible}`,      [userId],    ),    query(      `SELECT count(*)::int AS awaiting_approval       FROM inspections a       JOIN buildings s ON s.id = a.building_id       WHERE a.status = 'submitted' AND ${visible}`,      [userId],    ),    query(      `SELECT s.id, s.name, o.name AS organisation_name,              count(e.id) FILTER (WHERE e.status <> 'closed')::int AS open_issues,              count(e.id)::int AS total_issues       FROM buildings s       JOIN organisations o ON o.id = s.organisation_id       LEFT JOIN issues e ON e.building_id = s.id       WHERE ${visible}       GROUP BY s.id, o.name       ORDER BY o.name, s.name`,      [userId],    ),    listIssues({ userId, perPage: 5 }),  ]);  return {    ...issueCounts.rows[0],    ...inspectionCounts.rows[0],    buildings: buildings.rows,    recentIssues: recent.issues,  };}

The first two queries gained a JOIN buildings s: the condition is about buildings, so every query that needs it must reach the buildings table.

4. Pass the user from every route

Editsrc/routes/issues.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 { listBuildings, findBuilding } from '../models/buildings.js';import { listBuildings, findBuilding, listVisibleBuildings } from '../models/buildings.js';
Change 2 of 2
  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE });  const buildings = await listBuildings();  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });  const buildings = await listVisibleBuildings(req.user.id);
Show the whole src/routes/issues.js after this change
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';import { listBuildings, findBuilding, listVisibleBuildings } 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 issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) {  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {    return null;  }  const date = new Date(`${value}:00Z`);  return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) {  return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const description = cleanText(input.description, { max: 2000 });  const buildingId = parseId(input.building_id);  const occurredAt = parseDateTimeLocal(input.occurred_at);  const status = editing ? input.status : 'open';  if (!title.ok) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!description.ok) {    errors.description = 'Description must be at most 2000 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (!editing && buildingId === null) {    errors.building_id = 'Choose a building.';  }  if (!occurredAt) {    errors.occurred_at = 'Enter the date and time it happened (UTC).';  } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {    errors.occurred_at = 'That time is in the future.';  }  if (!STATUSES.includes(status)) {    errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;  }  // values: what the form shows again. record: what we store.  const values = {    title: title.text,    description: description.text,    priority: input.priority,    building_id: buildingId,    status,    occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',  };  const record = { ...values, occurred_at: occurredAt };  return { errors, values, record };} async function renderIssueForm(req, res, status, { issue = null, values = {}, errors = {} } = {}) {  const buildings = (await listBuildings()).filter((building) => can(req.user, 'CreateIssue', building));  res.status(status).render('issues/form', {    title: issue ? `Edit issue #${issue.id}` : 'Report an issue',    action: issue ? `/issues/${issue.id}/edit` : '/issues',    issue,    values,    errors,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,  });} const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) {  const page = parseId(query.page) ?? 1;  return {    page,    sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',    dir: query.dir === 'asc' ? 'asc' : 'desc',    status: STATUSES.includes(query.status) ? query.status : null,    priority: PRIORITIES.includes(query.priority) ? query.priority : null,    building: parseId(query.building),  };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) {  const merged = { ...options, ...overrides };  const params = new URLSearchParams();  for (const [key, value] of Object.entries(merged)) {    const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');    if (!isDefault) params.set(key, String(value));  }  const qs = params.toString();  return qs ? `/issues?${qs}` : '/issues';} async function loadIssue(req, res) {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue || !can(req.user, 'ViewIssue', issue)) {    notFound(req, res);    return null;  }  return issue;} issuesRouter.get('/', async (req, res) => {  const options = parseListQuery(req.query);  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });  const buildings = await listVisibleBuildings(req.user.id);  res.render('issues/index', {    title: 'Maintenance issues',    issues,    total,    options,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,    totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),    listUrl: (overrides) => listUrl(options, overrides),  });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(req, res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => {  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });  if (Object.keys(errors).length > 0) {    return renderIssueForm(req, res, 400, { values, errors });  }  // The building id came from the form. Load the real building and check the user may report there.  const building = await findBuilding(record.building_id);  if (!building || !can(req.user, 'CreateIssue', building)) {    return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can report issues.' } });  }  let created;  try {    created = await createIssue(record, req.user.id);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);  await renderIssueForm(req, res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });  if (Object.keys(errors).length > 0) {    return renderIssueForm(req, res, 400, { issue, values, errors });  }  // The edit form cannot move an issue: the building stays the one we loaded.  await updateIssue(issue.id, { ...record, building_id: issue.building_id });  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'DeleteIssue', issue)) return forbidden(res);  await deleteIssue(issue.id);  res.redirect(303, '/issues');});
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.
  res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status }), status, statuses: INSPECTION_STATUSES });  res.render('inspections/index', { title: 'Inspections', inspections: await listInspections({ status, userId: req.user.id }), status, statuses: INSPECTION_STATUSES });
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 } from '../models/buildings.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']; 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(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(),  });} 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) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    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(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 });  }  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.' } });    }    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 (inspection.status !== 'draft') {    return renderInspectionPage(res, 409, inspection, 'Only draft inspections can be edited.');  }  await renderInspectionForm(res, 200, { inspection, values: inspection });}); inspectionsRouter.post('/:id/edit', async (req, res) => {  const inspection = await loadInspection(req, res);  if (!inspection) return;  const { errors, values } = validateInspection(req.body ?? {}, { requireBuilding: false });  if (Object.keys(errors).length > 0) {    return renderInspectionForm(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;  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}`);});
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.
  res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations() });  res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });
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'; 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) {    res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });    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);  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;  renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  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;  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;  renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => {  const organisation = await loadOrganisation(req, res);  if (!organisation) return;  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;  }});
Editsrc/app.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard() });  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard(req.user.id) });
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { can } from './authz/rules.js';import { csrf } from './middleware/csrf.js';import { authRouter } from './routes/auth.js';import { accountRouter } from './routes/account.js';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.js'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });app.locals.currentUser = null;app.locals.flash = null;app.locals.csrfToken = ''; const PgSession = connectPgSimple(session); app.use((req, res, next) => {  if (process.env.NODE_ENV === 'test') {    return next();  }  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false }));app.use(session({  store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }),  name: 'caretaker.sid',  secret: config.sessionSecret,  resave: false,  saveUninitialized: false,  cookie: {    httpOnly: true,    sameSite: 'lax',    secure: config.cookieSecure,    maxAge: 8 * 60 * 60 * 1000,  },}));app.use(loadUser);app.use(flash);app.use(csrf); app.use(authRouter);app.use(requireLogin);app.use((req, res, next) => {  res.locals.can = (action, resource) => can(req.user, action, resource);  next();}); app.get('/', async (req, res) => {  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard(req.user.id) });}); app.use('/account', accountRouter);app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => {  res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);  }  const message = err.expose ? err.message : 'Something went wrong';  res.status(status).render('error', { title: 'Error', status, message });});

Run and inspect

Check the condition directly in SQL, for every user at once. A CROSS JOIN pairs every user with every building; the condition keeps the visible pairs:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT u.email, array_agg(s.id ORDER BY s.id) AS visible_buildingsFROM users uCROSS JOIN buildings sWHERE s.id IN (SELECT building_id FROM building_role_assignments WHERE user_id = u.id AND revoked_at IS NULL)   OR s.organisation_id IN (SELECT organisation_id FROM memberships WHERE user_id = u.id AND role = 'org_admin')GROUP BY u.emailORDER BY u.email;
       email        | visible_buildings 
--------------------+-------------------
 alice@example.test | {10,20}
 bob@example.test   | {30}
 carol@example.test | {10,20}
 dave@example.test  | {10,20}
(4 rows)

Compare with the last row of the access matrix in lesson 5.1: Alice, Carol and Dave see 10 and 20; Bob sees 30; Nora and Ravi do not appear at all, because no building is visible to them.

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/issues?priority=criticalsigned in as alice
After: the same filter for Alice. Only buildings 10 and 20, and the building filter lists only those.
After: the same filter for Alice. Only buildings 10 and 20, and the building filter lists only those.
localhost:3000/signed in as bob
Bob's dashboard counts only Galway Studios, the one building he can see.
Bob's dashboard counts only Galway Studios, the one building he can see.

Now run the tests:

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 (204.024542ms)
✔ only one active assignment per user, building and role (1.156917ms)
✔ a revoked role can be granted again (1.123625ms)
✔ the My access page shows what the server loaded (84.835292ms)
✔ a correct login creates a session and shows the user (281.606292ms)
✔ a wrong password or unknown email gets the same 401 (53.326541ms)
✔ registration validates, creates a user, and logs them in (48.278208ms)
✔ registering an existing email is a field error (32.732041ms)
✔ logout destroys the session (53.5545ms)
✔ a building can be created inside an organisation (269.328791ms)
✔ a duplicate building name in the same organisation is a field error (4.248375ms)
✔ the same building name is allowed in another organisation (4.947541ms)
✔ a building with issues cannot be deleted (12.964ms)
✔ an empty building can be deleted (9.572541ms)
✔ an organisation with buildings cannot be deleted, an empty one can (20.848875ms)
✔ a logged-in POST without a token is refused with 403 (268.99675ms)
✔ a token from another session is refused (34.66725ms)
✔ the right token in the form field works (8.545083ms)
✔ every POST form on every page carries the token (41.940208ms)
✖ the dashboard counts match the database (261.884667ms)
✖ every building appears with its organisation (6.741042ms)
✔ create a draft, edit it, submit it, approve it (290.768334ms)
✔ invalid transitions are refused with 409 and change nothing (11.303708ms)
✔ only drafts can be edited (5.032208ms)
✔ returning a submitted inspection makes it editable again (6.896875ms)
✔ concurrent approvals: exactly one wins (22.508833ms)
✔ unknown actions are 404 (3.215709ms)
✔ view issue 101 (building 10) (450.288291ms)
✔ open the edit form for issue 101 (20.214625ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (18.139166ms)
✔ view issue 105 (building 30) and 106 (building 40) (38.088583ms)
✔ report an issue at building 20 (21.261459ms)
✔ a reporter cannot edit their own issue once it is closed (6.361708ms)
✔ only building admins may delete; refusals change nothing (12.981917ms)
✔ the edit form cannot move an issue to another building (3.650459ms)
✖ the list pages 10 at a time and reports the total (275.126917ms)
Show 451 more lines✖ pages do not overlap (18.660458ms) ✔ filters combine with AND (6.167583ms) ✔ sorting by priority puts critical first when descending (6.170958ms) ✔ unknown sort keys and SQL in the query string are ignored (28.477875ms) ✔ GET /issues lists issues from the database (271.763167ms) ✔ GET /issues/101 shows one issue with its building (4.458917ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.959291ms) ✔ POST /issues re-renders the form with errors (4.51375ms) ✔ POST /issues stores the issue and redirects to it (6.832958ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (3.37575ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.379625ms) ✔ an issue time in the future is rejected (3.728583ms) ✔ GET /issues/101/edit shows the current values (3.663375ms) ✔ POST /issues/:id/edit changes the status and updated_at (3.83225ms) ✔ POST /issues/:id/delete removes the issue (7.788083ms) ✖ GET /organisations lists organisations with building counts (269.660375ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.376166ms) ✔ POST /organisations validates and creates (10.505958ms) ✔ POST /organisations/:id/edit renames the organisation (9.317125ms) ✔ unknown organisations are 404 (6.220667ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (349.08675ms) ✔ anonymous requests are redirected to the login page (216.414667ms) ✔ anonymous writes are refused and change nothing (11.166916ms) ✔ login and register pages stay public (6.074042ms) ✔ login issues a new session id (no session fixation) (34.0345ms) ✔ returnTo only follows local paths (31.238666ms) ✔ new issues and transitions record the logged-in user (77.472166ms) ✔ the session cookie has the attributes we chose (26.668292ms) ℹ tests 64 ℹ suites 0 ℹ pass 59 ℹ fail 5 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 6052.744834 ✖ failing tests: test at test/dashboard.test.js:15:1 ✖ the dashboard counts match the database (261.884667ms) AssertionError [ERR_ASSERTION]: The input did not match the regular expression /<h3>Open issues<\/h3><div class="stat">21<\/div>/. Input: '<!doctype html>\n' + '<html lang="en">\n' + '<head>\n' + ' <meta charset="utf-8">\n' + ' <meta name="viewport" content="width=device-width, initial-scale=1">\n' + ' <meta name="csrf-token" content="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU">\n' + ' <title>Dashboard · Caretaker</title>\n' + ' <link rel="stylesheet" href="/css/style.css">\n' + ' <script src="/js/app.js" defer></script>\n' + '</head>\n' + '<body>\n' + '<header class="site-header">\n' + ' <div class="container header-inner">\n' + ' <a class="brand" href="/">Caretaker</a>\n' + ' <nav class="main-nav" aria-label="Main">\n' + ' <a href="/issues">Issues</a>\n' + ' <a href="/inspections">Inspections</a>\n' + ' <a href="/organisations">Organisations</a>\n' + ' </nav>\n' + ' <div class="user-nav">\n' + ' \n' + ' <a class="link-button" href="/account">My access</a>\n' + ' <span>Signed in as <strong>Carol Duffy</strong></span>\n' + ' <form method="post" action="/logout"><input type="hidden" name="_csrf" value="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU"><button type="submit" class="link-button">Log out</button></form>\n' + ' \n' + ' </div>\n' + ' </div>\n' + '</header>\n' + '\n' + '<main class="container">\n' + '\n' + '\n' + '<h1>Dashboard</h1>\n' + '<div class="cards">\n' + ' <div class="card"><h3>Open issues</h3><div class="stat">19</div><p class="muted">open or under investigation</p></div>\n' + ' <div class="card"><h3>Serious and open</h3><div class="stat">10</div><p class="muted">high or critical priority</p></div>\n' + ' <div class="card"><h3>Inspections awaiting approval</h3><div class="stat">2</div><p class="muted"><a href="/inspections?status=submitted">review them</a></p></div>\n' + '</div>\n' + '\n' + '<h2>Buildings</h2>\n' + '<table class="data">\n' + ' <thead><tr><th>Building</th><th>Organisation</th><th>Open issues</th><th>All issues</th></tr></thead>\n' + ' <tbody>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/buildings/20">Cork Apartments</a></td>\n' + ' <td>Liffey Estates</td>\n' + ' <td><a href="/issues?building=20&status=open">10</a></td>\n' + ' <td>14</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/buildings/10">Dublin Offices</a></td>\n' + ' <td>Liffey Estates</td>\n' + ' <td><a href="/issues?building=10&status=open">9</a></td>\n' + ' <td>14</td>\n' + ' </tr>\n' + ' \n' + ' </tbody>\n' + '</table>\n' + '\n' + '<h2>Recent issues</h2>\n' + '<table class="data">\n' + ' <thead><tr><th>Title</th><th>Building</th><th>Priority</th><th>Occurred</th></tr></thead>\n' + ' <tbody>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/104">Water stain on the ceiling of flat 7</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td>10 Nov 2026, 11:30</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/103">Front door lock sticks at entrance 4</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-medium">medium</span></td>\n' + ' <td>8 Nov 2026, 07:05</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/102">Dripping tap in the second-floor kitchen</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-low">low</span></td>\n' + ' <td>5 Nov 2026, 14:40</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/101">Lift stuck between floors 2 and 3</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td>2 Nov 2026, 09:15</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/130">Blocked sink in kitchen (#130)</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-critical">critical</span></td>\n' + ' <td>24 Oct 2026, 13:00</td>\n' + ' </tr>\n' + ' \n' + ' </tbody>\n' + '</table>\n' + '</main>\n' + '<footer class="site-footer">\n' + ' <div class="container">Caretaker · a learning application with synthetic data</div>\n' + '</footer>\n' + '</body>\n' + '</html>\n' + '\n' at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/dashboard.test.js:19: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: '<!doctype html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <meta name="csrf-token" content="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU">\n <title>Dashboard · Caretaker</title>\n <link rel="stylesheet" href="/css/style.css">\n <script src="/js/app.js" defer></script>\n</head>\n<body>\n<header class="site-header">\n <div class="container header-inner">\n <a class="brand" href="/">Caretaker</a>\n <nav class="main-nav" aria-label="Main">\n <a href="/issues">Issues</a>\n <a href="/inspections">Inspections</a>\n <a href="/organisations">Organisations</a>\n </nav>\n <div class="user-nav">\n \n <a class="link-button" href="/account">My access</a>\n <span>Signed in as <strong>Carol Duffy</strong></span>\n <form method="post" action="/logout"><input type="hidden" name="_csrf" value="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU"><button type="submit" class="link-button">Log out</button></form>\n \n </div>\n </div>\n</header>\n\n<main class="container">\n\n\n<h1>Dashboard</h1>\n<div class="cards">\n <div class="card"><h3>Open issues</h3><div class="stat">19</div><p class="muted">open or under investigation</p></div>\n <div class="card"><h3>Serious and open</h3><div class="stat">10</div><p class="muted">high or critical priority</p></div>\n <div class="card"><h3>Inspections awaiting approval</h3><div class="stat">2</div><p class="muted"><a href="/inspections?status=submitted">review them</a></p></div>\n</div>\n\n<h2>Buildings</h2>\n<table class="data">\n <thead><tr><th>Building</th><th>Organisation</th><th>Open issues</th><th>All issues</th></tr></thead>\n <tbody>\n \n <tr>\n <td><a href="/buildings/20">Cork Apartments</a></td>\n <td>Liffey Estates</td>\n <td><a href="/issues?building=20&status=open">10</a></td>\n <td>14</td>\n </tr>\n \n <tr>\n <td><a href="/buildings/10">Dublin Offices</a></td>\n <td>Liffey Estates</td>\n <td><a href="/issues?building=10&status=open">9</a></td>\n <td>14</td>\n </tr>\n \n </tbody>\n</table>\n\n<h2>Recent issues</h2>\n<table class="data">\n <thead><tr><th>Title</th><th>Building</th><th>Priority</th><th>Occurred</th></tr></thead>\n <tbody>\n \n <tr>\n <td><a href="/issues/104">Water stain on the ceiling of flat 7</a></td>\n <td>Cork Apartments</td>\n <td><span class="badge sev-high">high</span></td>\n <td>10 Nov 2026, 11:30</td>\n </tr>\n \n <tr>\n <td><a href="/issues/103">Front door lock sticks at entrance 4</a></td>\n <td>Cork Apartments</td>\n <td><span class="badge sev-medium">medium</span></td>\n <td>8 Nov 2026, 07:05</td>\n </tr>\n \n <tr>\n <td><a href="/issues/102">Dripping tap in the second-floor kitchen</a></td>\n <td>Dublin Offices</td>\n <td><span class="badge sev-low">low</span></td>\n <td>5 Nov 2026, 14:40</td>\n </tr>\n \n <tr>\n <td><a href="/issues/101">Lift stuck between floors 2 and 3</a></td>\n <td>Dublin Offices</td>\n <td><span class="badge sev-high">high</span></td>\n <td>2 Nov 2026, 09:15</td>\n </tr>\n \n <tr>\n <td><a href="/issues/130">Blocked sink in kitchen (#130)</a></td>\n <td>Cork Apartments</td>\n <td><span class="badge sev-critical">critical</span></td>\n <td>24 Oct 2026, 13:00</td>\n </tr>\n \n </tbody>\n</table>\n</main>\n<footer class="site-footer">\n <div class="container">Caretaker · a learning application with synthetic data</div>\n</footer>\n</body>\n</html>\n\n', expected: /<h3>Open issues<\/h3><div class="stat">21<\/div>/, operator: 'match', diff: 'simple' } test at test/dashboard.test.js:23:1 ✖ every building appears with its organisation (6.741042ms) AssertionError [ERR_ASSERTION]: The input did not match the regular expression /Galway Studios/. Input: '<!doctype html>\n' + '<html lang="en">\n' + '<head>\n' + ' <meta charset="utf-8">\n' + ' <meta name="viewport" content="width=device-width, initial-scale=1">\n' + ' <meta name="csrf-token" content="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU">\n' + ' <title>Dashboard · Caretaker</title>\n' + ' <link rel="stylesheet" href="/css/style.css">\n' + ' <script src="/js/app.js" defer></script>\n' + '</head>\n' + '<body>\n' + '<header class="site-header">\n' + ' <div class="container header-inner">\n' + ' <a class="brand" href="/">Caretaker</a>\n' + ' <nav class="main-nav" aria-label="Main">\n' + ' <a href="/issues">Issues</a>\n' + ' <a href="/inspections">Inspections</a>\n' + ' <a href="/organisations">Organisations</a>\n' + ' </nav>\n' + ' <div class="user-nav">\n' + ' \n' + ' <a class="link-button" href="/account">My access</a>\n' + ' <span>Signed in as <strong>Carol Duffy</strong></span>\n' + ' <form method="post" action="/logout"><input type="hidden" name="_csrf" value="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU"><button type="submit" class="link-button">Log out</button></form>\n' + ' \n' + ' </div>\n' + ' </div>\n' + '</header>\n' + '\n' + '<main class="container">\n' + '\n' + '\n' + '<h1>Dashboard</h1>\n' + '<div class="cards">\n' + ' <div class="card"><h3>Open issues</h3><div class="stat">19</div><p class="muted">open or under investigation</p></div>\n' + ' <div class="card"><h3>Serious and open</h3><div class="stat">10</div><p class="muted">high or critical priority</p></div>\n' + ' <div class="card"><h3>Inspections awaiting approval</h3><div class="stat">2</div><p class="muted"><a href="/inspections?status=submitted">review them</a></p></div>\n' + '</div>\n' + '\n' + '<h2>Buildings</h2>\n' + '<table class="data">\n' + ' <thead><tr><th>Building</th><th>Organisation</th><th>Open issues</th><th>All issues</th></tr></thead>\n' + ' <tbody>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/buildings/20">Cork Apartments</a></td>\n' + ' <td>Liffey Estates</td>\n' + ' <td><a href="/issues?building=20&status=open">10</a></td>\n' + ' <td>14</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/buildings/10">Dublin Offices</a></td>\n' + ' <td>Liffey Estates</td>\n' + ' <td><a href="/issues?building=10&status=open">9</a></td>\n' + ' <td>14</td>\n' + ' </tr>\n' + ' \n' + ' </tbody>\n' + '</table>\n' + '\n' + '<h2>Recent issues</h2>\n' + '<table class="data">\n' + ' <thead><tr><th>Title</th><th>Building</th><th>Priority</th><th>Occurred</th></tr></thead>\n' + ' <tbody>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/104">Water stain on the ceiling of flat 7</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td>10 Nov 2026, 11:30</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/103">Front door lock sticks at entrance 4</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-medium">medium</span></td>\n' + ' <td>8 Nov 2026, 07:05</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/102">Dripping tap in the second-floor kitchen</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-low">low</span></td>\n' + ' <td>5 Nov 2026, 14:40</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/101">Lift stuck between floors 2 and 3</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td>2 Nov 2026, 09:15</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/130">Blocked sink in kitchen (#130)</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-critical">critical</span></td>\n' + ' <td>24 Oct 2026, 13:00</td>\n' + ' </tr>\n' + ' \n' + ' </tbody>\n' + '</table>\n' + '</main>\n' + '<footer class="site-footer">\n' + ' <div class="container">Caretaker · a learning application with synthetic data</div>\n' + '</footer>\n' + '</body>\n' + '</html>\n' + '\n' at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/dashboard.test.js:26: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: '<!doctype html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <meta name="csrf-token" content="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU">\n <title>Dashboard · Caretaker</title>\n <link rel="stylesheet" href="/css/style.css">\n <script src="/js/app.js" defer></script>\n</head>\n<body>\n<header class="site-header">\n <div class="container header-inner">\n <a class="brand" href="/">Caretaker</a>\n <nav class="main-nav" aria-label="Main">\n <a href="/issues">Issues</a>\n <a href="/inspections">Inspections</a>\n <a href="/organisations">Organisations</a>\n </nav>\n <div class="user-nav">\n \n <a class="link-button" href="/account">My access</a>\n <span>Signed in as <strong>Carol Duffy</strong></span>\n <form method="post" action="/logout"><input type="hidden" name="_csrf" value="N1PJjtxehaSc6JlFk4A8hYwAWs5uoWNRCcWhV3HfhAU"><button type="submit" class="link-button">Log out</button></form>\n \n </div>\n </div>\n</header>\n\n<main class="container">\n\n\n<h1>Dashboard</h1>\n<div class="cards">\n <div class="card"><h3>Open issues</h3><div class="stat">19</div><p class="muted">open or under investigation</p></div>\n <div class="card"><h3>Serious and open</h3><div class="stat">10</div><p class="muted">high or critical priority</p></div>\n <div class="card"><h3>Inspections awaiting approval</h3><div class="stat">2</div><p class="muted"><a href="/inspections?status=submitted">review them</a></p></div>\n</div>\n\n<h2>Buildings</h2>\n<table class="data">\n <thead><tr><th>Building</th><th>Organisation</th><th>Open issues</th><th>All issues</th></tr></thead>\n <tbody>\n \n <tr>\n <td><a href="/buildings/20">Cork Apartments</a></td>\n <td>Liffey Estates</td>\n <td><a href="/issues?building=20&status=open">10</a></td>\n <td>14</td>\n </tr>\n \n <tr>\n <td><a href="/buildings/10">Dublin Offices</a></td>\n <td>Liffey Estates</td>\n <td><a href="/issues?building=10&status=open">9</a></td>\n <td>14</td>\n </tr>\n \n </tbody>\n</table>\n\n<h2>Recent issues</h2>\n<table class="data">\n <thead><tr><th>Title</th><th>Building</th><th>Priority</th><th>Occurred</th></tr></thead>\n <tbody>\n \n <tr>\n <td><a href="/issues/104">Water stain on the ceiling of flat 7</a></td>\n <td>Cork Apartments</td>\n <td><span class="badge sev-high">high</span></td>\n <td>10 Nov 2026, 11:30</td>\n </tr>\n \n <tr>\n <td><a href="/issues/103">Front door lock sticks at entrance 4</a></td>\n <td>Cork Apartments</td>\n <td><span class="badge sev-medium">medium</span></td>\n <td>8 Nov 2026, 07:05</td>\n </tr>\n \n <tr>\n <td><a href="/issues/102">Dripping tap in the second-floor kitchen</a></td>\n <td>Dublin Offices</td>\n <td><span class="badge sev-low">low</span></td>\n <td>5 Nov 2026, 14:40</td>\n </tr>\n \n <tr>\n <td><a href="/issues/101">Lift stuck between floors 2 and 3</a></td>\n <td>Dublin Offices</td>\n <td><span class="badge sev-high">high</span></td>\n <td>2 Nov 2026, 09:15</td>\n </tr>\n \n <tr>\n <td><a href="/issues/130">Blocked sink in kitchen (#130)</a></td>\n <td>Cork Apartments</td>\n <td><span class="badge sev-critical">critical</span></td>\n <td>24 Oct 2026, 13:00</td>\n </tr>\n \n </tbody>\n</table>\n</main>\n<footer class="site-footer">\n <div class="container">Caretaker · a learning application with synthetic data</div>\n</footer>\n</body>\n</html>\n\n', expected: /Galway Studios/, operator: 'match', diff: 'simple' } test at test/issue-list.test.js:20:1 ✖ the list pages 10 at a time and reports the total (275.126917ms) AssertionError [ERR_ASSERTION]: The input did not match the regular expression /30 issues/. Input: '<!doctype html>\n' + '<html lang="en">\n' + '<head>\n' + ' <meta charset="utf-8">\n' + ' <meta name="viewport" content="width=device-width, initial-scale=1">\n' + ' <meta name="csrf-token" content="1h4qnC_ZuZO-JGhwsnWIDxWX-aQmpdNnRwgiO7CMKd0">\n' + ' <title>Maintenance issues · Caretaker</title>\n' + ' <link rel="stylesheet" href="/css/style.css">\n' + ' <script src="/js/app.js" defer></script>\n' + '</head>\n' + '<body>\n' + '<header class="site-header">\n' + ' <div class="container header-inner">\n' + ' <a class="brand" href="/">Caretaker</a>\n' + ' <nav class="main-nav" aria-label="Main">\n' + ' <a href="/issues">Issues</a>\n' + ' <a href="/inspections">Inspections</a>\n' + ' <a href="/organisations">Organisations</a>\n' + ' </nav>\n' + ' <div class="user-nav">\n' + ' \n' + ' <a class="link-button" href="/account">My access</a>\n' + ' <span>Signed in as <strong>Carol Duffy</strong></span>\n' + ' <form method="post" action="/logout"><input type="hidden" name="_csrf" value="1h4qnC_ZuZO-JGhwsnWIDxWX-aQmpdNnRwgiO7CMKd0"><button type="submit" class="link-button">Log out</button></form>\n' + ' \n' + ' </div>\n' + ' </div>\n' + '</header>\n' + '\n' + '<main class="container">\n' + '\n' + '\n' + '<div class="page-header">\n' + ' <h1>Maintenance issues</h1>\n' + ' <a class="btn btn-primary" href="/issues/new">Report an issue</a>\n' + '</div>\n' + '\n' + '<form method="get" action="/issues" class="filters">\n' + ' <label>Status\n' + ' <select name="status">\n' + ' <option value="">Any</option>\n' + ' <option value="open">open</option><option value="investigating">investigating</option><option value="closed">closed</option>\n' + ' </select>\n' + ' </label>\n' + ' <label>Priority\n' + ' <select name="priority">\n' + ' <option value="">Any</option>\n' + ' <option value="low">low</option><option value="medium">medium</option><option value="high">high</option><option value="critical">critical</option>\n' + ' </select>\n' + ' </label>\n' + ' <label>Building\n' + ' <select name="building">\n' + ' <option value="">Any</option>\n' + ' <option value="20">Liffey Estates · Cork Apartments</option><option value="10">Liffey Estates · Dublin Offices</option>\n' + ' </select>\n' + ' </label>\n' + ' <input type="hidden" name="sort" value="occurred_at">\n' + ' <input type="hidden" name="dir" value="desc">\n' + ' <button type="submit" class="btn btn-small">Apply</button>\n' + ' <a class="btn btn-small" href="/issues">Reset</a>\n' + '</form>\n' + '\n' + '\n' + '<p class="muted">28 issues</p>\n' + '\n' + ' <table class="data">\n' + ' <thead>\n' + ' <tr>\n' + ' \n' + ' <th><a href="/issues?sort=title">Title</a></th>\n' + ' \n' + ' <th><a href="/issues?sort=building">Building</a></th>\n' + ' \n' + ' <th><a href="/issues?sort=priority">Priority</a></th>\n' + ' \n' + ' <th><a href="/issues?sort=status">Status</a></th>\n' + ' \n' + ' <th><a href="/issues?dir=asc">Occurred ▼</a></th>\n' + ' \n' + ' </tr>\n' + ' </thead>\n' + ' <tbody>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/104">Water stain on the ceiling of flat 7</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td><span class="badge status-investigating">investigating</span></td>\n' + ' <td>10 Nov 2026, 11:30</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/103">Front door lock sticks at entrance 4</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-medium">medium</span></td>\n' + ' <td><span class="badge status-open">open</span></td>\n' + ' <td>8 Nov 2026, 07:05</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/102">Dripping tap in the second-floor kitchen</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-low">low</span></td>\n' + ' <td><span class="badge status-closed">closed</span></td>\n' + ' <td>5 Nov 2026, 14:40</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/101">Lift stuck between floors 2 and 3</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td><span class="badge status-open">open</span></td>\n' + ' <td>2 Nov 2026, 09:15</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/130">Blocked sink in kitchen (#130)</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-critical">critical</span></td>\n' + ' <td><span class="badge status-closed">closed</span></td>\n' + ' <td>24 Oct 2026, 13:00</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/129">Toilet cistern keeps running (#129)</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-high">high</span></td>\n' + ' <td><span class="badge status-investigating">investigating</span></td>\n' + ' <td>23 Oct 2026, 12:00</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/128">Loose floor tile at entrance (#128)</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-medium">medium</span></td>\n' + ' <td><span class="badge status-open">open</span></td>\n' + ' <td>22 Oct 2026, 11:00</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/127">Window does not close fully (#127)</a></td>\n' + ' <td>Dublin Offices</td>\n' + ' <td><span class="badge sev-low">low</span></td>\n' + ' <td><span class="badge status-closed">closed</span></td>\n' + ' <td>21 Oct 2026, 10:00</td>\n' + ' </tr>\n' + ' \n' + ' <tr>\n' + ' <td><a href="/issues/126">Radiator cold in room 2 (#126)</a></td>\n' + ' <td>Cork Apartments</td>\n' + ' <td><span class="badge sev-critical">critical</span></td>\n' + ' <td><span class="badge status-investigating">investigating</span></td>\n' + ' <td>20 Oct 2026, 09:00</td>\n' + ' </tr>\n' +

Several old tests fail. Read the messages before changing anything; each is a test that assumed Carol sees both organisations:

  • test/issue-list.test.js expects 30 issues. Carol sees the 28 issues at buildings 10 and 20.
  • test/dashboard.test.js compares with a count over all issues and expects every building to appear.
  • test/organisations.test.js expects Harbour Lets in Carol's list.

Those expectations were about the list mechanics, and they now meet isolation. Update them to the new truth:

Edittest/issue-list.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
  assert.match(first.text, /30 issues/);  assert.match(first.text, /28 issues/, 'carol sees the 28 issues at buildings 10 and 20');  const third = await agent.get('/issues?page=3');  assert.equal(issueIds(third.text).length, 10);  assert.equal(issueIds(third.text).length, 8);
Change 2 of 2
  assert.equal(new Set(ids).size, 30);  assert.equal(new Set(ids).size, 28);
Show the whole test/issue-list.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()); // The issue ids linked from the table rows, in order.function issueIds(html) {  return [...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]));} test('the list pages 10 at a time and reports the total', async () => {  const first = await agent.get('/issues');  assert.equal(issueIds(first.text).length, 10);  assert.match(first.text, /28 issues/, 'carol sees the 28 issues at buildings 10 and 20');  const third = await agent.get('/issues?page=3');  assert.equal(issueIds(third.text).length, 8);  const fourth = await agent.get('/issues?page=4');  assert.equal(issueIds(fourth.text).length, 0);}); test('pages do not overlap', async () => {  const ids = [];  for (const page of [1, 2, 3]) ids.push(...issueIds((await agent.get(`/issues?page=${page}`)).text));  assert.equal(new Set(ids).size, 28);}); test('filters combine with AND', async () => {  const res = await agent.get('/issues?status=open&building=20');  const ids = issueIds(res.text);  assert.ok(ids.length > 0);  const { rows } = await pool.query('SELECT id FROM issues WHERE status = $1 AND building_id = $2', ['open', 20]);  assert.deepEqual(new Set(ids), new Set(rows.map((r) => r.id)));}); test('sorting by priority puts critical first when descending', async () => {  const res = await agent.get('/issues?sort=priority&dir=desc');  assert.match(res.text, /<span class="badge sev-critical">/);  const firstBadge = res.text.match(/class="badge sev-(\w+)"/)[1];  assert.equal(firstBadge, 'critical');}); test('unknown sort keys and SQL in the query string are ignored', async () => {  for (const qs of ['sort=(SELECT%201/0)', 'sort=toString', 'dir=sideways', 'page=-1', 'status=%27%3B--', 'building=abc']) {    const res = await agent.get(`/issues?${qs}`);    assert.equal(res.status, 200, qs);    assert.equal(issueIds(res.text).length, 10, qs);  }});
Edittest/dashboard.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
  const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed'");  const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed' AND building_id IN (10, 20)");
Change 2 of 2
test('every building appears with its organisation', async () => {test('only the buildings carol can see appear', async () => {  const res = await agent.get('/');  for (const name of ['Dublin Offices', 'Cork Apartments', 'Galway Studios', 'Limerick House']) {  for (const name of ['Dublin Offices', 'Cork Apartments']) {    assert.match(res.text, new RegExp(name));  }  for (const name of ['Galway Studios', 'Limerick House']) {    assert.doesNotMatch(res.text, new RegExp(name));  }});
Show the whole test/dashboard.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('the dashboard counts match the database', async () => {  const res = await agent.get('/');  assert.equal(res.status, 200);  const { rows } = await pool.query("SELECT count(*)::int AS n FROM issues WHERE status <> 'closed' AND building_id IN (10, 20)");  assert.match(res.text, new RegExp(`<h3>Open issues</h3><div class="stat">${rows[0].n}</div>`));  assert.match(res.text, /<h3>Inspections awaiting approval<\/h3><div class="stat">2<\/div>/);}); test('only the buildings carol can see appear', async () => {  const res = await agent.get('/');  for (const name of ['Dublin Offices', 'Cork Apartments']) {    assert.match(res.text, new RegExp(name));  }  for (const name of ['Galway Studios', 'Limerick House']) {    assert.doesNotMatch(res.text, new RegExp(name));  }});
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.
  assert.match(res.text, /Liffey Estates<\/a><\/td>\s*<td>2<\/td>/);  assert.match(res.text, /Harbour Lets/);  assert.doesNotMatch(res.text, /Harbour Lets/, 'carol is not a member of Harbour Lets');
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/2/edit').type('form').send({ name: 'Harbour Lets Ltd' });  assert.equal(res.status, 303);  const page = await agent.get('/organisations/2');  assert.match(page.text, /<h1>Harbour Lets 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);});

Then add a test file that states isolation for every user:

Create filetest/isolation.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 agents = {};before(async () => {  await resetDatabase();  for (const name of ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi']) agents[name] = await loginAs(name);});after(() => pool.end()); function linkedIds(html, kind) {  return [...html.matchAll(new RegExp(`<td><a href="/${kind}/(\\d+)">`, 'g'))].map((m) => Number(m[1]));} async function allIssueIds(agent) {  const ids = [];  for (let page = 1; page <= 4; page++) ids.push(...linkedIds((await agent.get(`/issues?page=${page}`)).text, 'issues'));  return ids;} async function buildingsOf(issueIds) {  if (issueIds.length === 0) return [];  const { rows } = await pool.query('SELECT DISTINCT building_id FROM issues WHERE id = ANY($1) ORDER BY building_id', [issueIds]);  return rows.map((r) => r.building_id);} test('the issues list contains only issues from visible 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)) {    assert.deepEqual(await buildingsOf(await allIssueIds(agents[name])), buildings, name);  }}); test('a filter for another tenant\'s building returns nothing', async () => {  const res = await agents.alice.get('/issues?building=30');  assert.deepEqual(linkedIds(res.text, 'issues'), []);  assert.match(res.text, /0 issues/);}); test('the inspections list is scoped too', async () => {  assert.deepEqual(linkedIds((await agents.alice.get('/inspections')).text, 'inspections').sort(), [201, 202, 203]);  assert.deepEqual(linkedIds((await agents.bob.get('/inspections')).text, 'inspections'), [204]);  assert.deepEqual(linkedIds((await agents.nora.get('/inspections')).text, 'inspections'), []);}); test('organisations are listed for their members only', async () => {  assert.match((await agents.ravi.get('/organisations')).text, /Harbour Lets/, 'ravi is still a member');  assert.doesNotMatch((await agents.ravi.get('/organisations')).text, /Liffey/);  assert.doesNotMatch((await agents.nora.get('/organisations')).text, /<td><a href/);}); test('the dashboard counts only visible data', async () => {  const bob = (await agents.bob.get('/')).text;  assert.match(bob, /<h3>Open issues<\/h3><div class="stat">1<\/div>/);  assert.doesNotMatch(bob, /Dublin Offices/);  const nora = (await agents.nora.get('/')).text;  assert.match(nora, /<h3>Open issues<\/h3><div class="stat">0<\/div>/);});
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 (187.541ms)
✔ only one active assignment per user, building and role (1.036625ms)
✔ a revoked role can be granted again (1.245583ms)
✔ the My access page shows what the server loaded (72.373125ms)
✔ a correct login creates a session and shows the user (270.263291ms)
✔ a wrong password or unknown email gets the same 401 (52.79275ms)
✔ registration validates, creates a user, and logs them in (43.299375ms)
✔ registering an existing email is a field error (30.917875ms)
✔ logout destroys the session (53.475375ms)
✔ a building can be created inside an organisation (276.722833ms)
✔ a duplicate building name in the same organisation is a field error (5.976916ms)
✔ the same building name is allowed in another organisation (4.701125ms)
✔ a building with issues cannot be deleted (12.487917ms)
✔ an empty building can be deleted (11.557ms)
✔ an organisation with buildings cannot be deleted, an empty one can (20.462209ms)
✔ a logged-in POST without a token is refused with 403 (275.100375ms)
✔ a token from another session is refused (38.90075ms)
✔ the right token in the form field works (11.605292ms)
✔ every POST form on every page carries the token (50.096ms)
✔ the dashboard counts match the database (300.896708ms)
✔ only the buildings carol can see appear (6.07475ms)
✔ create a draft, edit it, submit it, approve it (317.832125ms)
✔ invalid transitions are refused with 409 and change nothing (13.181292ms)
✔ only drafts can be edited (7.605166ms)
✔ returning a submitted inspection makes it editable again (9.39825ms)
✔ concurrent approvals: exactly one wins (25.1255ms)
✔ unknown actions are 404 (3.300708ms)
✔ the issues list contains only issues from visible buildings (539.492416ms)
✔ a filter for another tenant's building returns nothing (3.990083ms)
✔ the inspections list is scoped too (9.686583ms)
✔ organisations are listed for their members only (8.838375ms)
✔ the dashboard counts only visible data (7.162375ms)
✔ view issue 101 (building 10) (466.247584ms)
✔ open the edit form for issue 101 (18.883334ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.354583ms)
✔ view issue 105 (building 30) and 106 (building 40) (47.0325ms)
Show 41 more lines✔ report an issue at building 20 (24.251417ms) ✔ a reporter cannot edit their own issue once it is closed (6.946625ms) ✔ only building admins may delete; refusals change nothing (16.485208ms) ✔ the edit form cannot move an issue to another building (3.654958ms) ✔ the list pages 10 at a time and reports the total (293.896083ms) ✔ pages do not overlap (21.730167ms) ✔ filters combine with AND (6.223125ms) ✔ sorting by priority puts critical first when descending (5.634291ms) ✔ unknown sort keys and SQL in the query string are ignored (29.680792ms) ✔ GET /issues lists issues from the database (267.63325ms) ✔ GET /issues/101 shows one issue with its building (4.224708ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.646917ms) ✔ POST /issues re-renders the form with errors (4.746666ms) ✔ POST /issues stores the issue and redirects to it (7.164708ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (3.401708ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.044459ms) ✔ an issue time in the future is rejected (3.672333ms) ✔ GET /issues/101/edit shows the current values (3.702041ms) ✔ POST /issues/:id/edit changes the status and updated_at (3.797625ms) ✔ POST /issues/:id/delete removes the issue (8.516667ms) ✔ GET /organisations lists organisations with building counts (276.25775ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.9265ms) ✔ POST /organisations validates and creates (11.328666ms) ✔ POST /organisations/:id/edit renames the organisation (8.944542ms) ✔ unknown organisations are 404 (6.675875ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (336.471ms) ✔ anonymous requests are redirected to the login page (214.865084ms) ✔ anonymous writes are refused and change nothing (11.3255ms) ✔ login and register pages stay public (6.013958ms) ✔ login issues a new session id (no session fixation) (32.314667ms) ✔ returnTo only follows local paths (29.57375ms) ✔ new issues and transitions record the logged-in user (5111.395666ms) ✔ the session cookie has the attributes we chose (43.103542ms) ℹ tests 69 ℹ suites 0 ℹ pass 69 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 12050.535666

Experiment

Carol's access to buildings 10 and 20 comes from her organisation role, not from assignments. What happens when Liffey opens a new building?

Predict A new building 50 is added to organisation 1, and an issue is reported there. Without any new assignment, who sees that issue in their list: Alice, Carol, Dave?
In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
INSERT INTO buildings (id, organisation_id, name) VALUES (50, 1, 'Waterford Annex');INSERT INTO issues (building_id, title, priority, occurred_at) VALUES (50, 'Broken hinge near the gate', 'medium', now()) RETURNING id;
INSERT 0 1
 id  
-----
 131
(1 row)

INSERT 0 1
Run and comparecaretaker/
for user in carol alice dave; do
  rm -f /tmp/$user.txt
  TOKEN=$(curl -s -c /tmp/$user.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
  curl -s -b /tmp/$user.txt -c /tmp/$user.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=$user@example.test -d password=password123
  printf "%s: %s " $user $(curl -s -b /tmp/$user.txt "http://localhost:3000/issues?building=50" | grep -c "Broken hinge")
done; echo
carol: 1 alice: 0 dave: 0
Reveal Answer

Only Carol. Her rights follow the relationship "building 50 belongs to organisation 1", so a new building is covered the moment it exists. Alice and Dave hold assignments at specific buildings; nobody assigned them to building 50. Both behaviours are what the role table promised. In Module 7, Cedar expresses this relationship directly, as a parent link from building to organisation.

Remove the experiment rows:

Run and comparecaretaker/
npm run db:seed

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

seeded the Caretaker scenario
Ctrl+C Stop the server in the server terminal.

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 (203.396292ms)
✔ only one active assignment per user, building and role (0.839875ms)
✔ a revoked role can be granted again (1.363458ms)
✔ the My access page shows what the server loaded (81.819084ms)
✔ a correct login creates a session and shows the user (259.487125ms)
✔ a wrong password or unknown email gets the same 401 (52.283375ms)
✔ registration validates, creates a user, and logs them in (41.998875ms)
✔ registering an existing email is a field error (32.614125ms)
✔ logout destroys the session (51.637ms)
✔ a building can be created inside an organisation (268.569084ms)
✔ a duplicate building name in the same organisation is a field error (4.578958ms)
✔ the same building name is allowed in another organisation (4.786208ms)
✔ a building with issues cannot be deleted (12.231875ms)
✔ an empty building can be deleted (8.877916ms)
✔ an organisation with buildings cannot be deleted, an empty one can (20.121916ms)
✔ a logged-in POST without a token is refused with 403 (276.629791ms)
✔ a token from another session is refused (48.105166ms)
✔ the right token in the form field works (11.082833ms)
✔ every POST form on every page carries the token (42.549ms)
✔ the dashboard counts match the database (284.778125ms)
✔ only the buildings carol can see appear (6.086208ms)
✔ create a draft, edit it, submit it, approve it (283.885959ms)
✔ invalid transitions are refused with 409 and change nothing (11.589917ms)
✔ only drafts can be edited (5.093417ms)
✔ returning a submitted inspection makes it editable again (7.232291ms)
✔ concurrent approvals: exactly one wins (21.226375ms)
✔ unknown actions are 404 (3.696208ms)
✔ the issues list contains only issues from visible buildings (556.3875ms)
✔ a filter for another tenant's building returns nothing (4.222792ms)
✔ the inspections list is scoped too (10.132208ms)
✔ organisations are listed for their members only (9.343292ms)
✔ the dashboard counts only visible data (7.077667ms)
✔ view issue 101 (building 10) (469.236416ms)
✔ open the edit form for issue 101 (17.911458ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (18.854541ms)
✔ view issue 105 (building 30) and 106 (building 40) (35.238208ms)
Show 41 more lines✔ report an issue at building 20 (19.8895ms) ✔ a reporter cannot edit their own issue once it is closed (5.786542ms) ✔ only building admins may delete; refusals change nothing (12.453666ms) ✔ the edit form cannot move an issue to another building (3.410167ms) ✔ the list pages 10 at a time and reports the total (268.982458ms) ✔ pages do not overlap (16.015167ms) ✔ filters combine with AND (5.293583ms) ✔ sorting by priority puts critical first when descending (4.688959ms) ✔ unknown sort keys and SQL in the query string are ignored (28.085125ms) ✔ GET /issues lists issues from the database (268.580167ms) ✔ GET /issues/101 shows one issue with its building (5.807625ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (13.128209ms) ✔ POST /issues re-renders the form with errors (4.235958ms) ✔ POST /issues stores the issue and redirects to it (6.766709ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (3.262791ms) ✔ the stored row has the cleaned values and ignores a client-sent status (3.679917ms) ✔ an issue time in the future is rejected (3.456708ms) ✔ GET /issues/101/edit shows the current values (3.5465ms) ✔ POST /issues/:id/edit changes the status and updated_at (4.2585ms) ✔ POST /issues/:id/delete removes the issue (8.118541ms) ✔ GET /organisations lists organisations with building counts (268.311125ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.7095ms) ✔ POST /organisations validates and creates (11.597958ms) ✔ POST /organisations/:id/edit renames the organisation (8.260458ms) ✔ unknown organisations are 404 (6.084709ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (351.453375ms) ✔ anonymous requests are redirected to the login page (220.209333ms) ✔ anonymous writes are refused and change nothing (11.058167ms) ✔ login and register pages stay public (6.307166ms) ✔ login issues a new session id (no session fixation) (32.123667ms) ✔ returnTo only follows local paths (28.181834ms) ✔ new issues and transitions record the logged-in user (79.951042ms) ✔ the session cookie has the attributes we chose (25.658417ms) ℹ tests 69 ℹ suites 0 ℹ pass 69 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 6797.426333
Run and comparecaretaker/
git add -A
git commit -m "Isolate tenants in every list"
[main 5a6e597] Isolate tenants in every list
 14 files changed, 144 insertions(+), 27 deletions(-)
 create mode 100644 src/models/scope.js
 create mode 100644 test/isolation.test.js
Symptom listIssues requires the id of the user the list is for

A caller still uses the old signature. Search for listIssues(, listInspections( and listOrganisations( and pass the user ID. Failing loudly here is the point: a list without a user must never quietly return everything.

Symptom bind message supplies 2 parameters, but prepared statement requires 3

In listIssues, the user ID is now $1, so filter placeholders start at $2. The code computes numbers from params.length; make sure params starts as [userId].

Recap and next step

Lists are filtered in SQL by one shared condition, so paging and counts are correct and no other tenant's rows ever leave the database. Every list function requires a user. Filters can only narrow the visible set. The SQL condition duplicates the JavaScript rule, and we have noted that this pair must stay aligned.

Organisations, buildings and inspections still have no checks of their own. Next lesson extends can() to them, and then we look honestly at what our rules file has become.