Module 8 · Lists, writes and multi-tenant isolation
8.2 Creates and moves
Authorize a create against the parent it will belong to, using trusted data about that parent, and add a move feature that needs permission at both the source and the destination.
Starting point
Creating an issue or inspection already checks CreateIssue or CreateInspection on the chosen building (lesson 5.2), and the edit form cannot change an issue's building. There is no way to move an issue that was reported at the wrong building.
Outcome
views/issues/move.ejs (new)src/models/issues.js (+ moveIssue)src/routes/issues.js (+ GET/POST /issues/:id/move)test/issue-moves.test.js (new)- A user may move an issue only if they may update it where it is, and create issues where it goes.
- Issues never move between organisations.
- Forged building IDs in create and move forms are refused and change nothing.
The problem
Authorization needs a resource. For a create, the resource does not exist yet. Two tempting answers are both wrong:
- Build a would-be issue entity from the form (
building: Building::"<form value>") and askCreateIssueon it. The building ID comes from the client; if we also took the building's organisation from the client, an attacker could describe a building of another tenant as belonging to their own organisation. - Skip the check because "the dropdown only offers allowed buildings". Lesson 4.4 showed how easy it is to post any value.
Our approach, from lesson 5.2: the client may propose a parent (a building ID). We load that building from the database, and authorize the action on the building entity built from our row. The proposal is only an identifier; every attribute Cedar sees about the building is ours.
A move combines both cases. The issue leaves one building and joins another. Checking only the source would let Alice move an issue from her building into a building where she has no rights; checking only the destination would let anyone who may create at building 20 take issues away from building 10.
Build it
1. Data access
Add moveIssue to src/models/issues.js:
// Moves an issue to another building, only if it is still at the building we checked.export async function moveIssue(id, fromBuildingId, toBuildingId) { const { rowCount } = await query( 'UPDATE issues SET building_id = $3, updated_at = now() WHERE id = $1 AND building_id = $2', [id, fromBuildingId, toBuildingId], ); return rowCount === 1;} export async function deleteIssue(id) {
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;} // Moves an issue to another building, only if it is still at the building we checked.export async function moveIssue(id, fromBuildingId, toBuildingId) { const { rowCount } = await query( 'UPDATE issues SET building_id = $3, updated_at = now() WHERE id = $1 AND building_id = $2', [id, fromBuildingId, toBuildingId], ); return rowCount === 1;} export async function deleteIssue(id) { const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]); return rowCount === 1;}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;
}
// Moves an issue to another building, only if it is still at the building we checked.
export async function moveIssue(id, fromBuildingId, toBuildingId) {
const { rowCount } = await query(
'UPDATE issues SET building_id = $3, updated_at = now() WHERE id = $1 AND building_id = $2',
[id, fromBuildingId, toBuildingId],
);
return rowCount === 1;
}
export async function deleteIssue(id) {
const { rowCount } = await query('DELETE FROM issues WHERE id = $1', [id]);
return rowCount === 1;
}
AND building_id = $2 protects the decision we made: if another request moved the issue between our check and our update, nothing happens, and the user is asked to try again with fresh data.
2. Routes
Add the move routes before the delete route in src/routes/issues.js:
import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, moveIssue, ISSUE_SORTS } from '../models/issues.js';
// Buildings this user may move the issue to: same organisation, another building, and CreateIssue allowed there.async function moveDestinations(req, issue) { return (await listBuildings()).filter((building) => building.organisation_id === issue.organisation_id && building.id !== issue.building_id && can(req.user, 'CreateIssue', building));} issuesRouter.get('/:id/move', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); res.render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: null });}); issuesRouter.post('/:id/move', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; // Source: the user must be allowed to change the issue where it is now. if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); // Destination: the client proposes a building id; everything else about the building comes from our database. const buildingId = parseId(req.body?.building_id); const destination = buildingId === null ? null : await findBuilding(buildingId); const valid = destination && destination.id !== issue.building_id && destination.organisation_id === issue.organisation_id && can(req.user, 'CreateIssue', destination); if (!valid) { return res.status(400).render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: 'Choose another building of this organisation where you can report issues.', }); } const moved = await moveIssue(issue.id, issue.building_id, destination.id); req.flash(moved ? 'success' : 'error', moved ? `Moved to ${destination.name}.` : 'The issue changed while you were moving it. Try again.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {
Show the whole src/routes/issues.js after this change
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, moveIssue, 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: rows, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id }); // Defence in depth: the SQL filter should already match the policies. If a row on // this page is denied by Cedar, hide it and report it: the two have drifted apart. const issues = rows.filter((issue) => can(req.user, 'ViewIssue', issue)); if (issues.length !== rows.length) { console.error('list/policy mismatch', { user: req.user.id, hidden: rows.filter((e) => !issues.includes(e)).map((e) => e.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}`);}); // Buildings this user may move the issue to: same organisation, another building, and CreateIssue allowed there.async function moveDestinations(req, issue) { return (await listBuildings()).filter((building) => building.organisation_id === issue.organisation_id && building.id !== issue.building_id && can(req.user, 'CreateIssue', building));} issuesRouter.get('/:id/move', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); res.render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: null });}); issuesRouter.post('/:id/move', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; // Source: the user must be allowed to change the issue where it is now. if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res); // Destination: the client proposes a building id; everything else about the building comes from our database. const buildingId = parseId(req.body?.building_id); const destination = buildingId === null ? null : await findBuilding(buildingId); const valid = destination && destination.id !== issue.building_id && destination.organisation_id === issue.organisation_id && can(req.user, 'CreateIssue', destination); if (!valid) { return res.status(400).render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: 'Choose another building of this organisation where you can report issues.', }); } const moved = await moveIssue(issue.id, issue.building_id, destination.id); req.flash(moved ? 'success' : 'error', moved ? `Moved to ${destination.name}.` : 'The issue changed while you were moving it. Try again.'); 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');});import express from 'express';
import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, moveIssue, 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: rows, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });
// Defence in depth: the SQL filter should already match the policies. If a row on
// this page is denied by Cedar, hide it and report it: the two have drifted apart.
const issues = rows.filter((issue) => can(req.user, 'ViewIssue', issue));
if (issues.length !== rows.length) {
console.error('list/policy mismatch', { user: req.user.id, hidden: rows.filter((e) => !issues.includes(e)).map((e) => e.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}`);
});
// Buildings this user may move the issue to: same organisation, another building, and CreateIssue allowed there.
async function moveDestinations(req, issue) {
return (await listBuildings()).filter((building) => building.organisation_id === issue.organisation_id
&& building.id !== issue.building_id
&& can(req.user, 'CreateIssue', building));
}
issuesRouter.get('/:id/move', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);
res.render('issues/move', { title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue), error: null });
});
issuesRouter.post('/:id/move', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
// Source: the user must be allowed to change the issue where it is now.
if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);
// Destination: the client proposes a building id; everything else about the building comes from our database.
const buildingId = parseId(req.body?.building_id);
const destination = buildingId === null ? null : await findBuilding(buildingId);
const valid = destination
&& destination.id !== issue.building_id
&& destination.organisation_id === issue.organisation_id
&& can(req.user, 'CreateIssue', destination);
if (!valid) {
return res.status(400).render('issues/move', {
title: `Move issue #${issue.id}`, issue, destinations: await moveDestinations(req, issue),
error: 'Choose another building of this organisation where you can report issues.',
});
}
const moved = await moveIssue(issue.id, issue.building_id, destination.id);
req.flash(moved ? 'success' : 'error', moved ? `Moved to ${destination.name}.` : 'The issue changed while you were moving it. Try again.');
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');
});
Two authorization questions and one data rule:
UpdateIssueon the issue as stored: may you change it here?CreateIssueon the destination building as stored: may you put issues there?- Same organisation: issues never cross tenants, whatever roles someone holds. That is a property of the data model, so we check it in code; a user who administers two organisations still cannot move records between them.
An invalid destination, an unknown building, another tenant's building and a building without permission all get the same 400 and message. The response does not reveal which buildings exist elsewhere.
3. View and button
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues/<%= issue.id %>">Issue #<%= issue.id %></a> / Move</p><h1>Move “<%= issue.title %>”</h1><p>Currently at <strong><%= issue.building_name %></strong>.</p><% if (error) { %><div class="flash flash-error" role="alert"><%= error %></div><% } %><% if (destinations.length === 0) { %> <p class="empty">There is no other building of this organisation where you can report issues.</p><% } else { %> <form method="post" action="/issues/<%= issue.id %>/move" class="form"><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field"> <label for="building_id">Move to</label> <select id="building_id" name="building_id"> <% for (const building of destinations) { %><option value="<%= building.id %>"><%= building.name %></option><% } %> </select> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary">Move issue</button> <a class="btn" href="/issues/<%= issue.id %>">Cancel</a> </div> </form><% } %><%- include('../partials/foot') %> <% if (can('UpdateIssue', issue)) { %> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <a class="btn" href="/issues/<%= issue.id %>/move">Move</a> <% } %>
Show the whole views/issues/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p><div class="page-header"> <h1><%= issue.title %></h1> <div class="actions"> <% if (can('UpdateIssue', issue)) { %> <a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a> <a class="btn" href="/issues/<%= issue.id %>/move">Move</a> <% } %> <% if (can('DeleteIssue', issue)) { %> <form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-danger">Delete</button> </form> <% } %> </div></div><dl class="details"> <dt>Building</dt><dd><%= issue.building_name %></dd> <dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd> <dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd> <dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd> <dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd> <dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd></dl><% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %><%- include('../partials/foot') %><%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/issues">Issues</a> / #<%= issue.id %></p>
<div class="page-header">
<h1><%= issue.title %></h1>
<div class="actions">
<% if (can('UpdateIssue', issue)) { %>
<a class="btn" href="/issues/<%= issue.id %>/edit">Edit</a>
<a class="btn" href="/issues/<%= issue.id %>/move">Move</a>
<% } %>
<% if (can('DeleteIssue', issue)) { %>
<form method="post" action="/issues/<%= issue.id %>/delete" data-confirm="Delete this issue? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<% } %>
</div>
</div>
<dl class="details">
<dt>Building</dt><dd><%= issue.building_name %></dd>
<dt>Priority</dt><dd><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></dd>
<dt>Status</dt><dd><span class="badge status-<%= issue.status %>"><%= issue.status %></span></dd>
<dt>Reported by</dt><dd><%= issue.reported_by_name ?? 'unknown' %></dd>
<dt>Occurred</dt><dd><%= formatDate(issue.occurred_at) %> UTC</dd>
<dt>Last updated</dt><dd><%= formatDate(issue.updated_at) %> UTC</dd>
</dl>
<% if (issue.description) { %>
<h2>Description</h2>
<p class="prose"><%= issue.description %></p>
<% } %>
<%- include('../partials/foot') %>
4. Tests
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', 'carol', 'dave']) agents[name] = await loginAs(name);});after(() => pool.end()); const buildingOf = async (id) => (await pool.query('SELECT building_id FROM issues WHERE id = $1', [id])).rows[0].building_id;const countIssues = async () => (await pool.query('SELECT count(*)::int AS n FROM issues')).rows[0].n; test('alice may update 101 at building 10 but may not create at building 20, so she cannot move it there', async () => { const res = await agents.alice.post('/issues/101/move').type('form').send({ building_id: '20' }); assert.equal(res.status, 400); assert.equal(await buildingOf(101), 10);}); test('dave may update his own issue 103 but is not a reporter at building 10', async () => { assert.equal((await agents.dave.post('/issues/103/move').type('form').send({ building_id: '10' })).status, 400); assert.equal(await buildingOf(103), 20);}); test('dave cannot move issue 101: he may not update it where it is', async () => { assert.equal((await agents.dave.post('/issues/101/move').type('form').send({ building_id: '20' })).status, 403);}); test('carol moves 101 to building 20, but never to another organisation', async () => { assert.equal((await agents.carol.post('/issues/101/move').type('form').send({ building_id: '30' })).status, 400); assert.equal(await buildingOf(101), 10); assert.equal((await agents.carol.post('/issues/101/move').type('form').send({ building_id: '20' })).status, 303); assert.equal(await buildingOf(101), 20);}); test('a forged building id on create is refused and creates nothing', async () => { const before = await countIssues(); for (const building_id of ['30', '40', '999', '-1', 'abc']) { const res = await agents.alice.post('/issues').type('form').send({ title: 'Forged building', building_id, priority: 'low', occurred_at: '2026-11-22T09:00' }); assert.equal(res.status, 400, `building_id ${building_id}`); } assert.equal(await countIssues(), before);});Run and inspect
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (468.731416ms)
✔ edit issue 101 (22.57ms)
✔ view issue 103 (building 20) (22.46325ms)
✔ edit issue 103 (reported by dave) (23.6405ms)
✔ report an issue at building 20 (26.082541ms)
✔ view issue 105 (building 30) (21.422167ms)
✔ view issue 106 (building 40, reported by bob) (15.833708ms)
✔ approve inspection 201 (created by dave) (18.678417ms)
✔ approve inspection 202 (created by alice) (20.074416ms)
✔ update organisation 1 (19.621209ms)
✔ change own role at building 10 (4.89175ms)
✔ grant building_admin at building 10 to dave (28.908791ms)
✔ grant viewer at building 10 to dave (17.07475ms)
✔ issues in each user's list come only from the expected buildings (107.4035ms)
✔ the scenario loads exactly as specified (205.910166ms)
✔ only one active assignment per user, building and role (0.814375ms)
✔ a revoked role can be granted again (1.279709ms)
✔ the My access page shows what the server loaded (71.030667ms)
✔ a correct login creates a session and shows the user (264.282334ms)
✔ a wrong password or unknown email gets the same 401 (52.593958ms)
✔ registration validates, creates a user, and logs them in (43.600709ms)
✔ registering an existing email is a field error (29.730292ms)
✔ logout destroys the session (49.7ms)
✔ allow: a permit matched and nothing forbade it (215.609791ms)
✔ explicit deny: a forbid overrides a matching permit (2.7795ms)
✔ implicit deny: no permit matched (2.166417ms)
authz problem {
user: 1,
action: 'ApproveInspection',
resource: 'Inspection::201',
decision: 'failure',
errors: [
'entity does not conform to the schema: in attribute `status` on `Caretaker::Inspection::"201"`, type mismatch: value was expected to have type string, but it actually has type long: `7`'
]
}
✔ failure: a row that does not fit the schema is never allowed (2.988084ms)
Show 97 more lines
✔ unknown actions throw instead of deciding (1.283334ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (442.725291ms)
✔ a revoked assignment cannot be revoked again (5.191041ms)
✔ an assignment id from another building is not found here (4.436083ms)
✔ alice cannot revoke her own building_admin role; carol can (12.244792ms)
✔ grants are limited to members of the building's organisation (5.590541ms)
✔ a building can be created inside an organisation (288.314167ms)
✔ a duplicate building name in the same organisation is a field error (5.713917ms)
✔ the same building name is allowed in another organisation (10.649375ms)
✔ a building with issues cannot be deleted (13.817042ms)
✔ an empty building can be deleted (11.097959ms)
✔ an organisation with buildings cannot be deleted, an empty one can (25.005958ms)
✔ a logged-in POST without a token is refused with 403 (270.417917ms)
✔ a token from another session is refused (37.456625ms)
✔ the right token in the form field works (19.674875ms)
✔ every POST form on every page carries the token (55.313958ms)
✔ the dashboard counts match the database (273.548083ms)
✔ only the buildings carol can see appear (6.058667ms)
✔ create a draft, edit it, submit it, approve it (328.616458ms)
✔ invalid transitions are refused with 409 and change nothing (11.282375ms)
✔ only drafts can be edited (5.687625ms)
✔ returning a submitted inspection makes it editable again (8.520666ms)
✔ concurrent approvals: exactly one wins (27.493875ms)
✔ unknown actions are 404 (3.498583ms)
✔ the issues list contains only issues from visible buildings (578.387958ms)
✔ a filter for another tenant's building returns nothing (3.639791ms)
✔ the inspections list is scoped too (9.444542ms)
✔ organisations are listed for their members only (8.868625ms)
✔ the dashboard counts only visible data (6.4515ms)
✔ view issue 101 (building 10) (506.713875ms)
✔ open the edit form for issue 101 (22.344083ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (26.152167ms)
✔ view issue 105 (building 30) and 106 (building 40) (44.382ms)
✔ report an issue at building 20 (42.633833ms)
✔ a reporter cannot edit their own issue once it is closed (11.060125ms)
✔ only building admins may delete; refusals change nothing (19.255708ms)
✔ the edit form cannot move an issue to another building (4.230458ms)
✔ the list pages 10 at a time and reports the total (383.880958ms)
✔ pages do not overlap (30.754667ms)
✔ filters combine with AND (7.954458ms)
✔ sorting by priority puts critical first when descending (8.783708ms)
✔ unknown sort keys and SQL in the query string are ignored (51.996875ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (574.563375ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (8.941208ms)
✔ dave cannot move issue 101: he may not update it where it is (6.044625ms)
✔ carol moves 101 to building 20, but never to another organisation (12.694333ms)
✔ a forged building id on create is refused and creates nothing (30.702959ms)
✔ GET /issues lists issues from the database (287.8575ms)
✔ GET /issues/101 shows one issue with its building (7.494458ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.723708ms)
✔ POST /issues re-renders the form with errors (5.111ms)
✔ POST /issues stores the issue and redirects to it (8.619792ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.713916ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.840875ms)
✔ an issue time in the future is rejected (4.532958ms)
✔ GET /issues/101/edit shows the current values (5.573875ms)
✔ POST /issues/:id/edit changes the status and updated_at (6.389333ms)
✔ POST /issues/:id/delete removes the issue (13.949625ms)
✔ the issues list contains exactly the issues Cedar lets each user view (340.716208ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (19.982583ms)
✔ only organisation admins can open the members page (417.875667ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (16.113375ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (10.961625ms)
✔ nobody changes their own membership (3.666084ms)
✔ unknown emails and roles are form errors (8.447208ms)
✔ a member cannot add members, even with a well-formed request (3.11175ms)
✔ GET /organisations lists organisations with building counts (272.456083ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (15.212041ms)
✔ POST /organisations validates and creates (14.60225ms)
✔ POST /organisations/:id/edit renames the organisation (11.0995ms)
✔ unknown organisations are 404 (6.028208ms)
✔ every policy is valid against the schema (32.856458ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.347459ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (345.488959ms)
✔ anonymous requests are redirected to the login page (217.177917ms)
✔ anonymous writes are refused and change nothing (10.709375ms)
✔ login and register pages stay public (5.85625ms)
✔ login issues a new session id (no session fixation) (31.430166ms)
✔ returnTo only follows local paths (28.422ms)
✔ new issues and transitions record the logged-in user (84.135166ms)
✔ the session cookie has the attributes we chose (26.252709ms)
✔ organisation 1: view and update (508.067125ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (7.818208ms)
✔ building 10: view, update, delete (59.971417ms)
✔ creating buildings needs org_admin (15.227291ms)
✔ creating an organisation makes the creator its admin (13.709041ms)
✔ inspections: view 201, open the edit form for draft 203 (49.210292ms)
✔ approve inspection 201 (dave's): only building admins (21.229833ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (14.944416ms)
ℹ tests 116
ℹ suites 0
ℹ pass 116
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12993.331
AUTHZ_LOG=1 npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000

Watch the two questions in the log when Carol moves issue 104 from building 20 to building 10:
rm -f /tmp/carol.txt
TOKEN=$(curl -s -c /tmp/carol.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/carol.txt -c /tmp/carol.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=carol@example.test -d password=password123
TOKEN=$(curl -s -b /tmp/carol.txt http://localhost:3000/account | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/carol.txt http://localhost:3000/issues/104/move -d _csrf=$TOKEN -d building_id=10
303
authz user=3 action=ViewIssue resource=Issue::104 decision=allow reasons=building-read
authz user=3 action=UpdateIssue resource=Issue::104 decision=allow reasons=building-admin
authz user=3 action=CreateIssue resource=Building::10 decision=allow reasons=building-admin
POST /issues/104/move -> 303 (15 ms)
ViewIssue (from loadIssue), UpdateIssue on Issue::104 (the source) and CreateIssue on Building::10 (the destination): three decisions, all from server-side data.
Experiment
Suppose a developer "simplifies" the move route to check only the destination.
Reveal Answer
Anyone who may create issues at another building of Liffey Estates, for example Dave, who is a reporter at building 20 and only an inspector at 10. He could take the stuck-lift issue away from building 10, where Alice's team would no longer see it. The test "dave cannot move issue 101" exists to catch exactly that change: remove the UpdateIssue line, run npm test, see it fail with 303 instead of 403, and restore the line.
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (463.096667ms)
✔ edit issue 101 (22.29875ms)
✔ view issue 103 (building 20) (24.593584ms)
✔ edit issue 103 (reported by dave) (27.008625ms)
✔ report an issue at building 20 (28.879459ms)
✔ view issue 105 (building 30) (18.584542ms)
✔ view issue 106 (building 40, reported by bob) (19.421625ms)
✔ approve inspection 201 (created by dave) (17.558375ms)
✔ approve inspection 202 (created by alice) (19.70175ms)
✔ update organisation 1 (21.457ms)
✔ change own role at building 10 (4.274333ms)
✔ grant building_admin at building 10 to dave (21.780958ms)
✔ grant viewer at building 10 to dave (16.1725ms)
✔ issues in each user's list come only from the expected buildings (121.696833ms)
✔ the scenario loads exactly as specified (211.236333ms)
✔ only one active assignment per user, building and role (0.861666ms)
✔ a revoked role can be granted again (1.225375ms)
✔ the My access page shows what the server loaded (74.418875ms)
✔ a correct login creates a session and shows the user (269.371ms)
✔ a wrong password or unknown email gets the same 401 (52.867875ms)
✔ registration validates, creates a user, and logs them in (43.403541ms)
✔ registering an existing email is a field error (30.388208ms)
✔ logout destroys the session (49.833333ms)
✔ allow: a permit matched and nothing forbade it (214.82775ms)
✔ explicit deny: a forbid overrides a matching permit (2.51775ms)
✔ implicit deny: no permit matched (2.311166ms)
authz problem {
user: 1,
action: 'ApproveInspection',
resource: 'Inspection::201',
decision: 'failure',
errors: [
'entity does not conform to the schema: in attribute `status` on `Caretaker::Inspection::"201"`, type mismatch: value was expected to have type string, but it actually has type long: `7`'
]
}
✔ failure: a row that does not fit the schema is never allowed (3.187042ms)
Show 97 more lines
✔ unknown actions throw instead of deciding (1.236334ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (397.898583ms)
✔ a revoked assignment cannot be revoked again (4.882375ms)
✔ an assignment id from another building is not found here (4.344583ms)
✔ alice cannot revoke her own building_admin role; carol can (12.591167ms)
✔ grants are limited to members of the building's organisation (6.210375ms)
✔ a building can be created inside an organisation (301.865958ms)
✔ a duplicate building name in the same organisation is a field error (5.4765ms)
✔ the same building name is allowed in another organisation (10.969041ms)
✔ a building with issues cannot be deleted (14.24775ms)
✔ an empty building can be deleted (10.722417ms)
✔ an organisation with buildings cannot be deleted, an empty one can (24.138958ms)
✔ a logged-in POST without a token is refused with 403 (268.755667ms)
✔ a token from another session is refused (37.979917ms)
✔ the right token in the form field works (19.060875ms)
✔ every POST form on every page carries the token (55.996792ms)
✔ the dashboard counts match the database (272.819042ms)
✔ only the buildings carol can see appear (4.857292ms)
✔ create a draft, edit it, submit it, approve it (353.447083ms)
✔ invalid transitions are refused with 409 and change nothing (11.682667ms)
✔ only drafts can be edited (5.683042ms)
✔ returning a submitted inspection makes it editable again (8.724125ms)
✔ concurrent approvals: exactly one wins (25.03425ms)
✔ unknown actions are 404 (3.673708ms)
✔ the issues list contains only issues from visible buildings (582.489334ms)
✔ a filter for another tenant's building returns nothing (3.667083ms)
✔ the inspections list is scoped too (8.665625ms)
✔ organisations are listed for their members only (7.673584ms)
✔ the dashboard counts only visible data (6.027125ms)
✔ view issue 101 (building 10) (469.61025ms)
✔ open the edit form for issue 101 (26.441292ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (25.870458ms)
✔ view issue 105 (building 30) and 106 (building 40) (53.01575ms)
✔ report an issue at building 20 (26.23225ms)
✔ a reporter cannot edit their own issue once it is closed (9.088208ms)
✔ only building admins may delete; refusals change nothing (16.6005ms)
✔ the edit form cannot move an issue to another building (3.924333ms)
✔ the list pages 10 at a time and reports the total (294.722834ms)
✔ pages do not overlap (23.720458ms)
✔ filters combine with AND (7.213625ms)
✔ sorting by priority puts critical first when descending (7.472959ms)
✔ unknown sort keys and SQL in the query string are ignored (40.870375ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (348.304875ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (6.279083ms)
✔ dave cannot move issue 101: he may not update it where it is (4.631584ms)
✔ carol moves 101 to building 20, but never to another organisation (13.951125ms)
✔ a forged building id on create is refused and creates nothing (23.357167ms)
✔ GET /issues lists issues from the database (270.30025ms)
✔ GET /issues/101 shows one issue with its building (6.748125ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.998583ms)
✔ POST /issues re-renders the form with errors (5.164125ms)
✔ POST /issues stores the issue and redirects to it (8.901ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.560834ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.336167ms)
✔ an issue time in the future is rejected (4.441292ms)
✔ GET /issues/101/edit shows the current values (5.718333ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.507458ms)
✔ POST /issues/:id/delete removes the issue (11.144792ms)
✔ the issues list contains exactly the issues Cedar lets each user view (342.5585ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (23.391542ms)
✔ only organisation admins can open the members page (436.904375ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (14.777042ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (15.619833ms)
✔ nobody changes their own membership (3.782625ms)
✔ unknown emails and roles are form errors (8.737542ms)
✔ a member cannot add members, even with a well-formed request (3.297334ms)
✔ GET /organisations lists organisations with building counts (255.687083ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (15.593708ms)
✔ POST /organisations validates and creates (14.381959ms)
✔ POST /organisations/:id/edit renames the organisation (11.125792ms)
✔ unknown organisations are 404 (5.990375ms)
✔ every policy is valid against the schema (31.874958ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.047959ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (336.126209ms)
✔ anonymous requests are redirected to the login page (215.857333ms)
✔ anonymous writes are refused and change nothing (10.834208ms)
✔ login and register pages stay public (6.841916ms)
✔ login issues a new session id (no session fixation) (32.27675ms)
✔ returnTo only follows local paths (28.793291ms)
✔ new issues and transitions record the logged-in user (88.840458ms)
✔ the session cookie has the attributes we chose (39.27275ms)
✔ organisation 1: view and update (551.967833ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (7.523667ms)
✔ building 10: view, update, delete (57.244041ms)
✔ creating buildings needs org_admin (15.009625ms)
✔ creating an organisation makes the creator its admin (8.718209ms)
✔ inspections: view 201, open the edit form for draft 203 (39.841166ms)
✔ approve inspection 201 (dave's): only building admins (16.65975ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (11.841042ms)
ℹ tests 116
ℹ suites 0
ℹ pass 116
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12486.85225
git add -A
git commit -m "Move issues with source and destination checks"
[main bb3c7e9] Move issues with source and destination checks
5 files changed, 115 insertions(+), 1 deletion(-)
create mode 100644 test/issue-moves.test.js
create mode 100644 views/issues/move.ejs
Symptom Every move returns 400
findBuilding must return organisation_id, and findIssue too (it comes from the join with buildings). Compare them as numbers.
Recap and next step
A create is authorized on the parent it will belong to, loaded from our database by the proposed ID. A move needs the right to change the record where it is and the right to create where it goes, plus the data rule that records never cross organisations. Forged IDs get one generic answer and change nothing.
Next lesson collects every isolation scenario into one suite: identifier substitution on every route, cross-tenant reads, writes and deletes, lists, and revocation.
Open the checkpoint files for lesson 8.2 (separate page; only files from this lesson and earlier)