Module 10 · Complete, test and operate the application
10.5 Capstone solution: work orders
A complete, replay-verified solution to the capstone, with the reasoning behind each choice. Open it after you have tried the feature yourself.
This is the capstone solution. Build the feature from lesson 10.4 first. When you are done or stuck, open the solution.
Starting point
This is the solution to lesson 10.4. It starts from the end of lesson 10.3 (131 tests) and is replayed and tested like every other lesson. If you built the feature yourself, compare your decisions with the ones below, not your line count.
Outcome
migrations/007_create_work_orders.sqlsrc/models/work-orders.jssrc/authz/policies/reporter-creates-work-orders.cedarsrc/authz/policies/assignee-completes-work-order.cedarsrc/authz/policies/forbid-self-assignment.cedartest/work-orders.test.jsEvery cell of the capstone table holds, Bob is refused on every new route with no database change, and the issue page shows the right buttons for each user.
The problem
Three decisions shape the solution:
- Where does a work order sit in the hierarchy? Under its issue. Then the existing
building-readandbuilding-adminpolicies cover it through parents and groups. - What is the resource for "create"? The issue, the parent, with the proposed assignee in the context.
- What is a policy and what is a data rule? "Assignee must be able to view the issue" is about the assignee, not the requester; it is a data rule checked before Cedar is asked. "Nobody assigns to themselves" is about the requester; it is a forbid.
Build it
1. Data
CREATE TABLE work_orders ( id integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, issue_id integer NOT NULL REFERENCES issues (id) ON DELETE CASCADE, title text NOT NULL CHECK (length(title) BETWEEN 3 AND 200), assignee_id integer NOT NULL REFERENCES users (id) ON DELETE RESTRICT, created_by integer REFERENCES users (id) ON DELETE SET NULL, due_on date NOT NULL, status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'done')), completed_at timestamptz, created_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX work_orders_issue_id_idx ON work_orders (issue_id);npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 007_create_work_orders.sql
migrations are up to date
Seed work order 301 and move its sequence along with the others:
for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments']) { await client.query( `INSERT INTO work_orders (id, issue_id, title, assignee_id, created_by, due_on) VALUES (301, 101, 'Replace the lift door sensor on floor 2', 4, 1, '2026-12-15')`, ); for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments', 'work_orders']) {
Show the whole src/seed.js after this change
import { hashPassword } from './models/users.js'; // Every seeded user has this password. Local learning data only.export const SEED_PASSWORD = 'password123'; export const users = [ { id: 1, email: 'alice@example.test', name: 'Alice Byrne' }, { id: 2, email: 'bob@example.test', name: 'Bob Okafor' }, { id: 3, email: 'carol@example.test', name: 'Carol Duffy' }, { id: 4, email: 'dave@example.test', name: 'Dave Murphy' }, { id: 5, email: 'nora@example.test', name: 'Nora Quinn' }, { id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },]; export const organisations = [ { id: 1, name: 'Liffey Estates' }, { id: 2, name: 'Harbour Lets' },]; export const buildings = [ { id: 10, organisationId: 1, name: 'Dublin Offices' }, { id: 20, organisationId: 1, name: 'Cork Apartments' }, { id: 30, organisationId: 2, name: 'Galway Studios' }, { id: 40, organisationId: 2, name: 'Limerick House' },]; const namedIssues = [ { id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' }, { id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' }, { id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' }, { id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' }, { id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' }, { id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },]; const fillerTitles = [ 'Loose handrail on stairs', 'Bins not collected', 'Corridor light not working', 'Radiator cold in room 2', 'Window does not close fully', 'Loose floor tile at entrance', 'Toilet cistern keeps running', 'Blocked sink in kitchen',]; // 24 extra issues (ids 107-130) alternate between buildings 10 and 20,// so that lists have enough rows to page, sort and filter.function fillerIssues() { const priorities = ['low', 'medium', 'high', 'critical']; const statuses = ['open', 'investigating', 'closed']; const issues = []; for (let i = 0; i < 24; i++) { issues.push({ id: 107 + i, buildingId: i % 2 === 0 ? 10 : 20, title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`, priority: priorities[i % priorities.length], status: statuses[i % statuses.length], occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(), description: '', }); } return issues;} export const issues = [...namedIssues, ...fillerIssues()]; // Organisation memberships: [userId, organisationId, role]export const memberships = [ [1, 1, 'member'], // alice, Liffey [2, 2, 'member'], // bob, Harbour Lets [3, 1, 'org_admin'], // carol, Liffey [4, 1, 'member'], // dave, Liffey [6, 2, 'member'], // ravi, Harbour Lets]; // Building role assignments. Ravi's was revoked by Bob on 20 November.export const assignments = [ { id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 }, { id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 }, { id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null }, { id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 }, { id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 }, { id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },]; export const inspections = [ { id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' }, { id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' }, { id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' }, { id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },]; export async function seed(client) { await client.query('BEGIN'); try { await client.query('TRUNCATE building_role_assignments, memberships, inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE'); for (const u of users) { await client.query( 'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)', [u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)], ); } for (const o of organisations) { await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]); } for (const s of buildings) { await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]); } for (const e of issues) { await client.query( `INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt], ); } for (const a of inspections) { await client.query( `INSERT INTO inspections (id, building_id, title, findings, status, submitted_at) VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`, [a.id, a.buildingId, a.title, a.findings, a.status], ); if (a.status === 'submitted') { await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]); } } // Who reported each issue and created each inspection (see the scenario table in lesson 0.1). await client.query(`UPDATE issues SET reported_by = CASE WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2 WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`); await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END'); for (const [userId, organisationId, role] of memberships) { await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]); } for (const a of assignments) { await client.query( `INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at) VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`, [a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null], ); } await client.query( `INSERT INTO work_orders (id, issue_id, title, assignee_id, created_by, due_on) VALUES (301, 101, 'Replace the lift door sensor on floor 2', 4, 1, '2026-12-15')`, ); for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments', 'work_orders']) { await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]); } await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; }}import { hashPassword } from './models/users.js';
// Every seeded user has this password. Local learning data only.
export const SEED_PASSWORD = 'password123';
export const users = [
{ id: 1, email: 'alice@example.test', name: 'Alice Byrne' },
{ id: 2, email: 'bob@example.test', name: 'Bob Okafor' },
{ id: 3, email: 'carol@example.test', name: 'Carol Duffy' },
{ id: 4, email: 'dave@example.test', name: 'Dave Murphy' },
{ id: 5, email: 'nora@example.test', name: 'Nora Quinn' },
{ id: 6, email: 'ravi@example.test', name: 'Ravi Shah' },
];
export const organisations = [
{ id: 1, name: 'Liffey Estates' },
{ id: 2, name: 'Harbour Lets' },
];
export const buildings = [
{ id: 10, organisationId: 1, name: 'Dublin Offices' },
{ id: 20, organisationId: 1, name: 'Cork Apartments' },
{ id: 30, organisationId: 2, name: 'Galway Studios' },
{ id: 40, organisationId: 2, name: 'Limerick House' },
];
const namedIssues = [
{ id: 101, buildingId: 10, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', occurredAt: '2026-11-02T09:15:00Z', description: 'The lift stopped between floors with nobody inside. Engineer called.' },
{ id: 102, buildingId: 10, title: 'Dripping tap in the second-floor kitchen', priority: 'low', status: 'closed', occurredAt: '2026-11-05T14:40:00Z', description: 'Worn washer. Tap replaced and floor dried.' },
{ id: 103, buildingId: 20, title: 'Front door lock sticks at entrance 4', priority: 'medium', status: 'open', occurredAt: '2026-11-08T07:05:00Z', description: 'The key turns only after several tries.' },
{ id: 104, buildingId: 20, title: 'Water stain on the ceiling of flat 7', priority: 'high', status: 'investigating', occurredAt: '2026-11-10T11:30:00Z', description: 'Stain about 40 cm wide. Roof drain to be checked.' },
{ id: 105, buildingId: 30, title: 'Boiler lost pressure in plant room', priority: 'critical', status: 'open', occurredAt: '2026-11-11T06:50:00Z', description: 'No heating on the ground floor.' },
{ id: 106, buildingId: 40, title: 'Car park barrier stuck open', priority: 'low', status: 'open', occurredAt: '2026-11-12T16:20:00Z', description: '' },
];
const fillerTitles = [
'Loose handrail on stairs',
'Bins not collected',
'Corridor light not working',
'Radiator cold in room 2',
'Window does not close fully',
'Loose floor tile at entrance',
'Toilet cistern keeps running',
'Blocked sink in kitchen',
];
// 24 extra issues (ids 107-130) alternate between buildings 10 and 20,
// so that lists have enough rows to page, sort and filter.
function fillerIssues() {
const priorities = ['low', 'medium', 'high', 'critical'];
const statuses = ['open', 'investigating', 'closed'];
const issues = [];
for (let i = 0; i < 24; i++) {
issues.push({
id: 107 + i,
buildingId: i % 2 === 0 ? 10 : 20,
title: `${fillerTitles[i % fillerTitles.length]} (#${107 + i})`,
priority: priorities[i % priorities.length],
status: statuses[i % statuses.length],
occurredAt: new Date(Date.UTC(2026, 9, 1 + i, 8 + (i % 9))).toISOString(),
description: '',
});
}
return issues;
}
export const issues = [...namedIssues, ...fillerIssues()];
// Organisation memberships: [userId, organisationId, role]
export const memberships = [
[1, 1, 'member'], // alice, Liffey
[2, 2, 'member'], // bob, Harbour Lets
[3, 1, 'org_admin'], // carol, Liffey
[4, 1, 'member'], // dave, Liffey
[6, 2, 'member'], // ravi, Harbour Lets
];
// Building role assignments. Ravi's was revoked by Bob on 20 November.
export const assignments = [
{ id: 1, userId: 1, buildingId: 10, role: 'building_admin', grantedBy: 3 },
{ id: 2, userId: 1, buildingId: 20, role: 'viewer', grantedBy: 3 },
{ id: 3, userId: 2, buildingId: 30, role: 'building_admin', grantedBy: null },
{ id: 4, userId: 4, buildingId: 10, role: 'inspector', grantedBy: 1 },
{ id: 5, userId: 4, buildingId: 20, role: 'reporter', grantedBy: 3 },
{ id: 6, userId: 6, buildingId: 30, role: 'viewer', grantedBy: 2, revokedBy: 2, revokedAt: '2026-11-20T10:00:00Z' },
];
export const inspections = [
{ id: 201, buildingId: 10, title: 'Q4 lift maintenance inspection', status: 'submitted', findings: 'Service log not signed for October. Emergency phone in lift 2 needs a new battery.' },
{ id: 202, buildingId: 10, title: 'Roof and gutter check, all four sides', status: 'submitted', findings: 'One blocked gutter on the north side.' },
{ id: 203, buildingId: 20, title: 'Door and lock check', status: 'draft', findings: '' },
{ id: 204, buildingId: 30, title: 'Boiler room review', status: 'draft', findings: '' },
];
export async function seed(client) {
await client.query('BEGIN');
try {
await client.query('TRUNCATE building_role_assignments, memberships, inspection_status_changes, inspections, issues, buildings, organisations, users RESTART IDENTITY CASCADE');
for (const u of users) {
await client.query(
'INSERT INTO users (id, email, name, password_hash) VALUES ($1, $2, $3, $4)',
[u.id, u.email, u.name, await hashPassword(SEED_PASSWORD)],
);
}
for (const o of organisations) {
await client.query('INSERT INTO organisations (id, name) VALUES ($1, $2)', [o.id, o.name]);
}
for (const s of buildings) {
await client.query('INSERT INTO buildings (id, organisation_id, name) VALUES ($1, $2, $3)', [s.id, s.organisationId, s.name]);
}
for (const e of issues) {
await client.query(
`INSERT INTO issues (id, building_id, title, description, priority, status, occurred_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
[e.id, e.buildingId, e.title, e.description, e.priority, e.status, e.occurredAt],
);
}
for (const a of inspections) {
await client.query(
`INSERT INTO inspections (id, building_id, title, findings, status, submitted_at)
VALUES ($1, $2, $3, $4, $5, CASE WHEN $5 = 'submitted' THEN now() END)`,
[a.id, a.buildingId, a.title, a.findings, a.status],
);
if (a.status === 'submitted') {
await client.query("INSERT INTO inspection_status_changes (inspection_id, from_status, to_status) VALUES ($1, 'draft', 'submitted')", [a.id]);
}
}
// Who reported each issue and created each inspection (see the scenario table in lesson 0.1).
await client.query(`UPDATE issues SET reported_by = CASE
WHEN id IN (101, 102) THEN 1 WHEN id IN (103, 104) THEN 4 WHEN id IN (105, 106) THEN 2
WHEN building_id = 10 THEN 1 WHEN building_id = 20 THEN 4 END`);
await client.query('UPDATE inspections SET created_by = CASE id WHEN 201 THEN 4 WHEN 202 THEN 1 WHEN 203 THEN 3 WHEN 204 THEN 2 END');
for (const [userId, organisationId, role] of memberships) {
await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]);
}
for (const a of assignments) {
await client.query(
`INSERT INTO building_role_assignments (id, user_id, building_id, role, granted_by, granted_at, revoked_by, revoked_at)
VALUES ($1, $2, $3, $4, $5, '2026-11-01T09:00:00Z', $6, $7)`,
[a.id, a.userId, a.buildingId, a.role, a.grantedBy, a.revokedBy ?? null, a.revokedAt ?? null],
);
}
await client.query(
`INSERT INTO work_orders (id, issue_id, title, assignee_id, created_by, due_on)
VALUES (301, 101, 'Replace the lift door sensor on floor 2', 4, 1, '2026-12-15')`,
);
for (const table of ['users', 'organisations', 'buildings', 'issues', 'inspections', 'building_role_assignments', 'work_orders']) {
await client.query(`SELECT setval(pg_get_serial_sequence($1, 'id'), (SELECT max(id) FROM ${table}))`, [table]);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}
TRUNCATE ... CASCADE at the top of the seed already empties work_orders, because it references tables in the list.
Create src/models/work-orders.js:
import { query } from '../db.js';import { visibleBuildingCondition } from './scope.js'; // due_on is a date without time. Formatting it in SQL avoids JavaScript's Date shifting it by time zone.const COLUMNS = ` ca.id, ca.issue_id, ca.title, ca.assignee_id, u.name AS assignee_name, ca.created_by, to_char(ca.due_on, 'YYYY-MM-DD') AS due_on, ca.status, ca.completed_at`; export async function listWorkOrders(issueId) { const { rows } = await query( `SELECT ${COLUMNS} FROM work_orders ca JOIN users u ON u.id = ca.assignee_id WHERE ca.issue_id = $1 ORDER BY ca.status DESC, ca.due_on, ca.id`, [issueId], ); return rows;} // Bound to the issue in the URL: a work order of another issue is "not found" here.export async function findWorkOrder(id, issueId) { const { rows } = await query( `SELECT ${COLUMNS} FROM work_orders ca JOIN users u ON u.id = ca.assignee_id WHERE ca.id = $1 AND ca.issue_id = $2`, [id, issueId], ); return rows[0] ?? null;} // Users who may view issues at the building: the same condition as every list (lesson 5.3),// with the user taken from each row (u.id) instead of a parameter.export async function listEligibleAssignees(buildingId) { const { rows } = await query( `SELECT u.id, u.name FROM users u JOIN buildings s ON s.id = $1 WHERE ${visibleBuildingCondition('s', 'u.id')} ORDER BY u.name`, [buildingId], ); return rows;} export async function createWorkOrder({ issueId, title, assigneeId, dueOn, createdBy }) { const { rows } = await query( 'INSERT INTO work_orders (issue_id, title, assignee_id, due_on, created_by) VALUES ($1, $2, $3, $4, $5) RETURNING id', [issueId, title, assigneeId, dueOn, createdBy], ); return rows[0];} export async function completeWorkOrder(id) { const { rowCount } = await query("UPDATE work_orders SET status = 'done', completed_at = now() WHERE id = $1 AND status = 'open'", [id]); return rowCount === 1;} export async function deleteWorkOrder(id) { await query('DELETE FROM work_orders WHERE id = $1', [id]);}2. Schema, mapper and policies
entity WorkOrder in [Issue] = { issue: Issue, assignee: User, status: String, createdBy?: User, }; entity Inspection in [Building] = {
action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo { principal: [User], resource: [Inspection], }; action ViewWorkOrder in [ReadBuildingData] appliesTo { principal: [User], resource: [WorkOrder] }; action CompleteWorkOrder, DeleteWorkOrder in [AdministerBuilding] appliesTo { principal: [User], resource: [WorkOrder], }; action CreateWorkOrder in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue], context: { assignee: User }, };}
Show the whole src/authz/schema.cedarschema after this change
// What Cedar may see in Caretaker, and in what shape. Version 2.namespace Caretaker { entity Organisation; entity Building in [Organisation] = { organisation: Organisation, }; // Version 2: facts only. Each set holds exactly the rows the database has. entity User = { viewerBuildings: Set<Building>, reporterBuildings: Set<Building>, inspectorBuildings: Set<Building>, adminBuildings: Set<Building>, memberOrganisations: Set<Organisation>, adminOrganisations: Set<Organisation>, }; entity Issue in [Building] = { building: Building, status: String, priority: String, reportedBy?: User, }; entity WorkOrder in [Issue] = { issue: Issue, assignee: User, status: String, createdBy?: User, }; entity Inspection in [Building] = { building: Building, status: String, createdBy?: User, }; // Action groups. A policy about a group applies to every action in it. action ReadBuildingData; action AdministerBuilding; action AdministerOrganisation; action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] }; action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation], }; action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] }; action ViewMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation] }; action ManageMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation], context: { targetUser: User, role: String }, }; action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] }; action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] }; action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] }; action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] }; action ViewBuildingAccess in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] }; action ManageBuildingRoles in [AdministerBuilding] appliesTo { principal: [User], resource: [Building], context: { targetUser: User, role: String }, }; action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] }; action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo { principal: [User], resource: [Inspection], }; action ViewWorkOrder in [ReadBuildingData] appliesTo { principal: [User], resource: [WorkOrder] }; action CompleteWorkOrder, DeleteWorkOrder in [AdministerBuilding] appliesTo { principal: [User], resource: [WorkOrder], }; action CreateWorkOrder in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue], context: { assignee: User }, };}// What Cedar may see in Caretaker, and in what shape. Version 2.
namespace Caretaker {
entity Organisation;
entity Building in [Organisation] = {
organisation: Organisation,
};
// Version 2: facts only. Each set holds exactly the rows the database has.
entity User = {
viewerBuildings: Set<Building>,
reporterBuildings: Set<Building>,
inspectorBuildings: Set<Building>,
adminBuildings: Set<Building>,
memberOrganisations: Set<Organisation>,
adminOrganisations: Set<Organisation>,
};
entity Issue in [Building] = {
building: Building,
status: String,
priority: String,
reportedBy?: User,
};
entity WorkOrder in [Issue] = {
issue: Issue,
assignee: User,
status: String,
createdBy?: User,
};
entity Inspection in [Building] = {
building: Building,
status: String,
createdBy?: User,
};
// Action groups. A policy about a group applies to every action in it.
action ReadBuildingData;
action AdministerBuilding;
action AdministerOrganisation;
action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] };
action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo {
principal: [User],
resource: [Organisation],
};
action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] };
action ViewMembers in [AdministerOrganisation] appliesTo { principal: [User], resource: [Organisation] };
action ManageMembers in [AdministerOrganisation] appliesTo {
principal: [User],
resource: [Organisation],
context: { targetUser: User, role: String },
};
action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] };
action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] };
action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] };
action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] };
action ViewBuildingAccess in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] };
action ManageBuildingRoles in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Building],
context: { targetUser: User, role: String },
};
action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] };
action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Inspection],
};
action ViewWorkOrder in [ReadBuildingData] appliesTo { principal: [User], resource: [WorkOrder] };
action CompleteWorkOrder, DeleteWorkOrder in [AdministerBuilding] appliesTo {
principal: [User],
resource: [WorkOrder],
};
action CreateWorkOrder in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Issue],
context: { assignee: User },
};
}
Because of the parent chain and the groups, building-read and building-admin already decide viewing, deleting, completing and creating for building admins and organisation admins. Only the special cases need new policies:
// The reporter of an issue may plan work orders for it while it is not closed.permit (principal, action == Caretaker::Action::"CreateWorkOrder", resource)when { resource in principal.reporterBuildings && resource has reportedBy && resource.reportedBy == principal && resource.status != "closed"};// The assignee may mark their own open work order as done.permit (principal, action == Caretaker::Action::"CompleteWorkOrder", resource)when { resource.assignee == principal && resource.status == "open" };// Nobody assigns a work order to themselves.forbid (principal, action == Caretaker::Action::"CreateWorkOrder", resource)when { context.assignee == principal };npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
15 policies are valid against the schema
The assignee policy does not mention the building. That is deliberate and safe here: every route loads the issue first and answers 404 unless the user may view it, so an assignee whose building role was revoked never reaches the work order.
The mapper builds the new entity:
export function workOrderEntity(action) { const attrs = { issue: ref('Issue', action.issue_id), assignee: ref('User', action.assignee_id), status: action.status }; if (action.created_by !== null) { attrs.createdBy = ref('User', action.created_by); } return { uid: ref('WorkOrder', action.id), attrs, parents: [ref('Issue', action.issue_id)] };} export function inspectionEntity(inspection) {
Show the whole src/authz/entities.js after this change
// The entity mapper: turns rows the application already loaded into Cedar entities.// Every value comes from the database (through loadAccess and the models) or from// the session (the user id). Nothing comes from the HTTP request. const NAMESPACE = 'Caretaker'; export function ref(type, id) { return { type: `${NAMESPACE}::${type}`, id: String(id) };} function refs(type, ids) { return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));} function buildingsWithRole(user, role) { return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));} // Version 2: facts only. Each set is exactly the active rows of one role.// Inheritance (organisation -> building) and the role ladder are decided by the policies.export function userEntity(user) { return { uid: ref('User', user.id), attrs: { viewerBuildings: buildingsWithRole(user, 'viewer'), reporterBuildings: buildingsWithRole(user, 'reporter'), inspectorBuildings: buildingsWithRole(user, 'inspector'), adminBuildings: buildingsWithRole(user, 'building_admin'), memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)), adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)), }, parents: [], };} export function organisationEntity(organisationId) { return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };} export function buildingEntity({ id, organisation_id }) { return { uid: ref('Building', id), attrs: { organisation: ref('Organisation', organisation_id) }, parents: [ref('Organisation', organisation_id)], };} export function issueEntity(issue) { const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority }; if (issue.reported_by !== null) { attrs.reportedBy = ref('User', issue.reported_by); } return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };} export function workOrderEntity(action) { const attrs = { issue: ref('Issue', action.issue_id), assignee: ref('User', action.assignee_id), status: action.status }; if (action.created_by !== null) { attrs.createdBy = ref('User', action.created_by); } return { uid: ref('WorkOrder', action.id), attrs, parents: [ref('Issue', action.issue_id)] };} export function inspectionEntity(inspection) { const attrs = { building: ref('Building', inspection.building_id), status: inspection.status }; if (inspection.created_by !== null) { attrs.createdBy = ref('User', inspection.created_by); } return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };}// The entity mapper: turns rows the application already loaded into Cedar entities.
// Every value comes from the database (through loadAccess and the models) or from
// the session (the user id). Nothing comes from the HTTP request.
const NAMESPACE = 'Caretaker';
export function ref(type, id) {
return { type: `${NAMESPACE}::${type}`, id: String(id) };
}
function refs(type, ids) {
return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));
}
function buildingsWithRole(user, role) {
return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));
}
// Version 2: facts only. Each set is exactly the active rows of one role.
// Inheritance (organisation -> building) and the role ladder are decided by the policies.
export function userEntity(user) {
return {
uid: ref('User', user.id),
attrs: {
viewerBuildings: buildingsWithRole(user, 'viewer'),
reporterBuildings: buildingsWithRole(user, 'reporter'),
inspectorBuildings: buildingsWithRole(user, 'inspector'),
adminBuildings: buildingsWithRole(user, 'building_admin'),
memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)),
adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)),
},
parents: [],
};
}
export function organisationEntity(organisationId) {
return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };
}
export function buildingEntity({ id, organisation_id }) {
return {
uid: ref('Building', id),
attrs: { organisation: ref('Organisation', organisation_id) },
parents: [ref('Organisation', organisation_id)],
};
}
export function issueEntity(issue) {
const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority };
if (issue.reported_by !== null) {
attrs.reportedBy = ref('User', issue.reported_by);
}
return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };
}
export function workOrderEntity(action) {
const attrs = { issue: ref('Issue', action.issue_id), assignee: ref('User', action.assignee_id), status: action.status };
if (action.created_by !== null) {
attrs.createdBy = ref('User', action.created_by);
}
return { uid: ref('WorkOrder', action.id), attrs, parents: [ref('Issue', action.issue_id)] };
}
export function inspectionEntity(inspection) {
const attrs = { building: ref('Building', inspection.building_id), status: inspection.status };
if (inspection.created_by !== null) {
attrs.createdBy = ref('User', inspection.created_by);
}
return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };
}
A request about a work order needs the work order, its issue, the building and the organisation. Routes pass a work order row with its issue attached as issue:
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity } from './entities.js';import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity, workOrderEntity } from './entities.js';
ReturnInspection: 'Inspection', ViewWorkOrder: 'WorkOrder', CompleteWorkOrder: 'WorkOrder', DeleteWorkOrder: 'WorkOrder', CreateWorkOrder: 'Issue',
case 'WorkOrder': { const { issue } = row; return [workOrderEntity(row), issueEntity(issue), buildingEntity({ id: issue.building_id, organisation_id: issue.organisation_id }), organisationEntity(issue.organisation_id)]; } default: throw new Error(`Unknown resource type ${type}`);
Show the whole src/authz/request.js after this change
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity, workOrderEntity } from './entities.js'; // Which entity type each action's resource is. Must match the schema's appliesTo.export const RESOURCE_TYPES = { ViewOrganisation: 'Organisation', UpdateOrganisation: 'Organisation', DeleteOrganisation: 'Organisation', CreateBuilding: 'Organisation', ViewMembers: 'Organisation', ManageMembers: 'Organisation', ViewBuilding: 'Building', UpdateBuilding: 'Building', DeleteBuilding: 'Building', CreateIssue: 'Building', CreateInspection: 'Building', ViewBuildingAccess: 'Building', ManageBuildingRoles: 'Building', ViewIssue: 'Issue', UpdateIssue: 'Issue', DeleteIssue: 'Issue', ViewInspection: 'Inspection', UpdateInspection: 'Inspection', SubmitInspection: 'Inspection', ApproveInspection: 'Inspection', ReturnInspection: 'Inspection', ViewWorkOrder: 'WorkOrder', CompleteWorkOrder: 'WorkOrder', DeleteWorkOrder: 'WorkOrder', CreateWorkOrder: 'Issue',}; // The resource entity for a database row, followed by the building and organisation it belongs to.function resourceEntities(type, row) { switch (type) { case 'Organisation': return [organisationEntity(row.id)]; case 'Building': return [buildingEntity(row), organisationEntity(row.organisation_id)]; case 'Issue': return [issueEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)]; case 'Inspection': return [inspectionEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)]; case 'WorkOrder': { const { issue } = row; return [workOrderEntity(row), issueEntity(issue), buildingEntity({ id: issue.building_id, organisation_id: issue.organisation_id }), organisationEntity(issue.organisation_id)]; } default: throw new Error(`Unknown resource type ${type}`); }} // Builds the request part of an isAuthorized call for one user, action and database row.export function buildAuthorizationCall(user, action, row, context = {}) { const type = RESOURCE_TYPES[action]; if (!type) { throw new Error(`No Cedar resource type for action ${action}`); } const [resource, ...related] = resourceEntities(type, row); return { principal: ref('User', user.id), action: { type: 'Caretaker::Action', id: action }, resource: resource.uid, context, entities: [userEntity(user), resource, ...related], };}import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity, workOrderEntity } from './entities.js';
// Which entity type each action's resource is. Must match the schema's appliesTo.
export const RESOURCE_TYPES = {
ViewOrganisation: 'Organisation',
UpdateOrganisation: 'Organisation',
DeleteOrganisation: 'Organisation',
CreateBuilding: 'Organisation',
ViewMembers: 'Organisation',
ManageMembers: 'Organisation',
ViewBuilding: 'Building',
UpdateBuilding: 'Building',
DeleteBuilding: 'Building',
CreateIssue: 'Building',
CreateInspection: 'Building',
ViewBuildingAccess: 'Building',
ManageBuildingRoles: 'Building',
ViewIssue: 'Issue',
UpdateIssue: 'Issue',
DeleteIssue: 'Issue',
ViewInspection: 'Inspection',
UpdateInspection: 'Inspection',
SubmitInspection: 'Inspection',
ApproveInspection: 'Inspection',
ReturnInspection: 'Inspection',
ViewWorkOrder: 'WorkOrder',
CompleteWorkOrder: 'WorkOrder',
DeleteWorkOrder: 'WorkOrder',
CreateWorkOrder: 'Issue',
};
// The resource entity for a database row, followed by the building and organisation it belongs to.
function resourceEntities(type, row) {
switch (type) {
case 'Organisation':
return [organisationEntity(row.id)];
case 'Building':
return [buildingEntity(row), organisationEntity(row.organisation_id)];
case 'Issue':
return [issueEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)];
case 'Inspection':
return [inspectionEntity(row), buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)];
case 'WorkOrder': {
const { issue } = row;
return [workOrderEntity(row), issueEntity(issue), buildingEntity({ id: issue.building_id, organisation_id: issue.organisation_id }), organisationEntity(issue.organisation_id)];
}
default:
throw new Error(`Unknown resource type ${type}`);
}
}
// Builds the request part of an isAuthorized call for one user, action and database row.
export function buildAuthorizationCall(user, action, row, context = {}) {
const type = RESOURCE_TYPES[action];
if (!type) {
throw new Error(`No Cedar resource type for action ${action}`);
}
const [resource, ...related] = resourceEntities(type, row);
return {
principal: ref('User', user.id),
action: { type: 'Caretaker::Action', id: action },
resource: resource.uid,
context,
entities: [userEntity(user), resource, ...related],
};
}
3. Routes
import { can } from '../authz/rules.js';import { ref } from '../authz/entities.js';import { listWorkOrders, findWorkOrder, listEligibleAssignees, createWorkOrder, completeWorkOrder, deleteWorkOrder } from '../models/work-orders.js';
// The issue page, with its work orders and (for people who may plan them) the add form.async function renderIssuePage(req, res, status, issue, { values = {}, errors = {} } = {}) { const actions = (await listWorkOrders(issue.id)).filter((a) => can(req.user, 'ViewWorkOrder', { ...a, issue })); // UpdateIssue is allowed for exactly the people CreateWorkOrder permits (admins; the open issue's reporter). const assignees = can(req.user, 'UpdateIssue', issue) ? await listEligibleAssignees(issue.building_id) : []; res.status(status).render('issues/show', { title: issue.title, issue, actions, assignees, values, errors });} issuesRouter.get('/:id', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; res.render('issues/show', { title: issue.title, issue }); await renderIssuePage(req, res, 200, issue);}); function validateAction(input) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const dueOn = typeof input.due_on === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(input.due_on) ? input.due_on : null; const assigneeId = parseId(input.assignee_id); if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.'; if (!dueOn) errors.due_on = 'Choose a due date.'; if (assigneeId === null) errors.assignee_id = 'Choose who will do it.'; return { errors, values: { title: title.text, due_on: dueOn, assignee_id: assigneeId } };} // Loads a work order of THIS issue, or answers 404. Returns the work order with its issue attached.async function loadAction(req, res, issue) { const id = parseId(req.params.actionId); const action = id === null ? null : await findWorkOrder(id, issue.id); if (!action || !can(req.user, 'ViewWorkOrder', { ...action, issue })) { notFound(req, res); return null; } return { ...action, issue };} issuesRouter.post('/:id/actions', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const { errors, values } = validateAction(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssuePage(req, res, 400, issue, { values, errors }); } // Data rule: the assignee must be someone who may view this issue. const eligible = await listEligibleAssignees(issue.building_id); if (!eligible.some((u) => u.id === values.assignee_id)) { return renderIssuePage(req, res, 400, issue, { values, errors: { assignee_id: 'Choose someone who can view this issue.' } }); } if (!can(req.user, 'CreateWorkOrder', issue, { assignee: ref('User', values.assignee_id) })) { return forbidden(res, 'You cannot assign this work order.'); } await createWorkOrder({ issueId: issue.id, title: values.title, assigneeId: values.assignee_id, dueOn: values.due_on, createdBy: req.user.id }); req.flash('success', 'Work order added.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/actions/:actionId/complete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const action = await loadAction(req, res, issue); if (!action) return; if (!can(req.user, 'CompleteWorkOrder', action)) return forbidden(res); const done = await completeWorkOrder(action.id); req.flash(done ? 'success' : 'error', done ? 'Marked as done.' : 'That work order was already done.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/actions/:actionId/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const action = await loadAction(req, res, issue); if (!action) return; if (!can(req.user, 'DeleteWorkOrder', action)) return forbidden(res); await deleteWorkOrder(action.id); req.flash('success', 'Work order deleted.'); res.redirect(303, `/issues/${issue.id}`);});
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 { ref } from '../authz/entities.js';import { listWorkOrders, findWorkOrder, listEligibleAssignees, createWorkOrder, completeWorkOrder, deleteWorkOrder } from '../models/work-orders.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}`);}); // The issue page, with its work orders and (for people who may plan them) the add form.async function renderIssuePage(req, res, status, issue, { values = {}, errors = {} } = {}) { const actions = (await listWorkOrders(issue.id)).filter((a) => can(req.user, 'ViewWorkOrder', { ...a, issue })); // UpdateIssue is allowed for exactly the people CreateWorkOrder permits (admins; the open issue's reporter). const assignees = can(req.user, 'UpdateIssue', issue) ? await listEligibleAssignees(issue.building_id) : []; res.status(status).render('issues/show', { title: issue.title, issue, actions, assignees, values, errors });} issuesRouter.get('/:id', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; await renderIssuePage(req, res, 200, issue);}); function validateAction(input) { const errors = {}; const title = cleanText(input.title, { min: 3, max: 200 }); const dueOn = typeof input.due_on === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(input.due_on) ? input.due_on : null; const assigneeId = parseId(input.assignee_id); if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.'; if (!dueOn) errors.due_on = 'Choose a due date.'; if (assigneeId === null) errors.assignee_id = 'Choose who will do it.'; return { errors, values: { title: title.text, due_on: dueOn, assignee_id: assigneeId } };} // Loads a work order of THIS issue, or answers 404. Returns the work order with its issue attached.async function loadAction(req, res, issue) { const id = parseId(req.params.actionId); const action = id === null ? null : await findWorkOrder(id, issue.id); if (!action || !can(req.user, 'ViewWorkOrder', { ...action, issue })) { notFound(req, res); return null; } return { ...action, issue };} issuesRouter.post('/:id/actions', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const { errors, values } = validateAction(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssuePage(req, res, 400, issue, { values, errors }); } // Data rule: the assignee must be someone who may view this issue. const eligible = await listEligibleAssignees(issue.building_id); if (!eligible.some((u) => u.id === values.assignee_id)) { return renderIssuePage(req, res, 400, issue, { values, errors: { assignee_id: 'Choose someone who can view this issue.' } }); } if (!can(req.user, 'CreateWorkOrder', issue, { assignee: ref('User', values.assignee_id) })) { return forbidden(res, 'You cannot assign this work order.'); } await createWorkOrder({ issueId: issue.id, title: values.title, assigneeId: values.assignee_id, dueOn: values.due_on, createdBy: req.user.id }); req.flash('success', 'Work order added.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/actions/:actionId/complete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const action = await loadAction(req, res, issue); if (!action) return; if (!can(req.user, 'CompleteWorkOrder', action)) return forbidden(res); const done = await completeWorkOrder(action.id); req.flash(done ? 'success' : 'error', done ? 'Marked as done.' : 'That work order was already done.'); res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/actions/:actionId/delete', async (req, res) => { const issue = await loadIssue(req, res); if (!issue) return; const action = await loadAction(req, res, issue); if (!action) return; if (!can(req.user, 'DeleteWorkOrder', action)) return forbidden(res); await deleteWorkOrder(action.id); req.flash('success', 'Work order deleted.'); res.redirect(303, `/issues/${issue.id}`);}); 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 { ref } from '../authz/entities.js';
import { listWorkOrders, findWorkOrder, listEligibleAssignees, createWorkOrder, completeWorkOrder, deleteWorkOrder } from '../models/work-orders.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}`);
});
// The issue page, with its work orders and (for people who may plan them) the add form.
async function renderIssuePage(req, res, status, issue, { values = {}, errors = {} } = {}) {
const actions = (await listWorkOrders(issue.id)).filter((a) => can(req.user, 'ViewWorkOrder', { ...a, issue }));
// UpdateIssue is allowed for exactly the people CreateWorkOrder permits (admins; the open issue's reporter).
const assignees = can(req.user, 'UpdateIssue', issue) ? await listEligibleAssignees(issue.building_id) : [];
res.status(status).render('issues/show', { title: issue.title, issue, actions, assignees, values, errors });
}
issuesRouter.get('/:id', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
await renderIssuePage(req, res, 200, issue);
});
function validateAction(input) {
const errors = {};
const title = cleanText(input.title, { min: 3, max: 200 });
const dueOn = typeof input.due_on === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(input.due_on) ? input.due_on : null;
const assigneeId = parseId(input.assignee_id);
if (!title.ok) errors.title = 'Title must be between 3 and 200 characters.';
if (!dueOn) errors.due_on = 'Choose a due date.';
if (assigneeId === null) errors.assignee_id = 'Choose who will do it.';
return { errors, values: { title: title.text, due_on: dueOn, assignee_id: assigneeId } };
}
// Loads a work order of THIS issue, or answers 404. Returns the work order with its issue attached.
async function loadAction(req, res, issue) {
const id = parseId(req.params.actionId);
const action = id === null ? null : await findWorkOrder(id, issue.id);
if (!action || !can(req.user, 'ViewWorkOrder', { ...action, issue })) {
notFound(req, res);
return null;
}
return { ...action, issue };
}
issuesRouter.post('/:id/actions', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
const { errors, values } = validateAction(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderIssuePage(req, res, 400, issue, { values, errors });
}
// Data rule: the assignee must be someone who may view this issue.
const eligible = await listEligibleAssignees(issue.building_id);
if (!eligible.some((u) => u.id === values.assignee_id)) {
return renderIssuePage(req, res, 400, issue, { values, errors: { assignee_id: 'Choose someone who can view this issue.' } });
}
if (!can(req.user, 'CreateWorkOrder', issue, { assignee: ref('User', values.assignee_id) })) {
return forbidden(res, 'You cannot assign this work order.');
}
await createWorkOrder({ issueId: issue.id, title: values.title, assigneeId: values.assignee_id, dueOn: values.due_on, createdBy: req.user.id });
req.flash('success', 'Work order added.');
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/actions/:actionId/complete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
const action = await loadAction(req, res, issue);
if (!action) return;
if (!can(req.user, 'CompleteWorkOrder', action)) return forbidden(res);
const done = await completeWorkOrder(action.id);
req.flash(done ? 'success' : 'error', done ? 'Marked as done.' : 'That work order was already done.');
res.redirect(303, `/issues/${issue.id}`);
});
issuesRouter.post('/:id/actions/:actionId/delete', async (req, res) => {
const issue = await loadIssue(req, res);
if (!issue) return;
const action = await loadAction(req, res, issue);
if (!action) return;
if (!can(req.user, 'DeleteWorkOrder', action)) return forbidden(res);
await deleteWorkOrder(action.id);
req.flash('success', 'Work order deleted.');
res.redirect(303, `/issues/${issue.id}`);
});
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');
});
The order in POST /:id/actions is the familiar one: load and view the issue; validate the form; check the data rule against our own query; ask Cedar with a context built from checked values; act. An admin completing a work order that is already done passes authorization and then meets the conditional UPDATE, which reports it.
4. The issue page
<% if (issue.description) { %> <h2>Description</h2> <p class="prose"><%= issue.description %></p><% } %> <h2>Work orders</h2><% if (actions.length === 0) { %> <p class="muted">No work orders yet.</p><% } else { %> <table class="data"> <thead><tr><th>Work order</th><th>Assignee</th><th>Due</th><th>Status</th><th></th></tr></thead> <tbody> <% for (const a of actions) { const actionRef = { ...a, issue }; %> <tr> <td><%= a.title %></td> <td><%= a.assignee_name %></td> <td><%= a.due_on %></td> <td><span class="badge status-<%= a.status === 'done' ? 'closed' : 'open' %>"><%= a.status %></span></td> <td class="actions"> <% if (a.status === 'open' && can('CompleteWorkOrder', actionRef)) { %> <form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/complete"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small">Mark done</button></form> <% } %> <% if (can('DeleteWorkOrder', actionRef)) { %> <form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/delete" data-confirm="Delete this work order?"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small btn-danger">Delete</button></form> <% } %> </td> </tr> <% } %> </tbody> </table><% } %> <% if (assignees.length > 0) { %> <h3>Add a work order</h3> <form method="post" action="/issues/<%= issue.id %>/actions" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="action-title">What needs to be done</label> <input id="action-title" name="title" value="<%= values.title ?? '' %>" maxlength="200"> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <div class="field<%= errors.assignee_id ? ' has-error' : '' %>"> <label for="assignee_id">Assignee</label> <select id="assignee_id" name="assignee_id"> <% for (const u of assignees) { %><option value="<%= u.id %>"<%= values.assignee_id === u.id ? ' selected' : '' %>><%= u.name %></option><% } %> </select> <% if (errors.assignee_id) { %><p class="field-error"><%= errors.assignee_id %></p><% } %> </div> <div class="field<%= errors.due_on ? ' has-error' : '' %>"> <label for="due_on">Due</label> <input id="due_on" name="due_on" type="date" value="<%= values.due_on ?? '' %>"> <% if (errors.due_on) { %><p class="field-error"><%= errors.due_on %></p><% } %> </div> <div class="form-actions"><button type="submit" class="btn btn-primary">Add work order</button></div> </form><% } %><%- include('../partials/foot') %>
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><% } %> <h2>Work orders</h2><% if (actions.length === 0) { %> <p class="muted">No work orders yet.</p><% } else { %> <table class="data"> <thead><tr><th>Work order</th><th>Assignee</th><th>Due</th><th>Status</th><th></th></tr></thead> <tbody> <% for (const a of actions) { const actionRef = { ...a, issue }; %> <tr> <td><%= a.title %></td> <td><%= a.assignee_name %></td> <td><%= a.due_on %></td> <td><span class="badge status-<%= a.status === 'done' ? 'closed' : 'open' %>"><%= a.status %></span></td> <td class="actions"> <% if (a.status === 'open' && can('CompleteWorkOrder', actionRef)) { %> <form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/complete"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small">Mark done</button></form> <% } %> <% if (can('DeleteWorkOrder', actionRef)) { %> <form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/delete" data-confirm="Delete this work order?"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small btn-danger">Delete</button></form> <% } %> </td> </tr> <% } %> </tbody> </table><% } %> <% if (assignees.length > 0) { %> <h3>Add a work order</h3> <form method="post" action="/issues/<%= issue.id %>/actions" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field<%= errors.title ? ' has-error' : '' %>"> <label for="action-title">What needs to be done</label> <input id="action-title" name="title" value="<%= values.title ?? '' %>" maxlength="200"> <% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %> </div> <div class="field<%= errors.assignee_id ? ' has-error' : '' %>"> <label for="assignee_id">Assignee</label> <select id="assignee_id" name="assignee_id"> <% for (const u of assignees) { %><option value="<%= u.id %>"<%= values.assignee_id === u.id ? ' selected' : '' %>><%= u.name %></option><% } %> </select> <% if (errors.assignee_id) { %><p class="field-error"><%= errors.assignee_id %></p><% } %> </div> <div class="field<%= errors.due_on ? ' has-error' : '' %>"> <label for="due_on">Due</label> <input id="due_on" name="due_on" type="date" value="<%= values.due_on ?? '' %>"> <% if (errors.due_on) { %><p class="field-error"><%= errors.due_on %></p><% } %> </div> <div class="form-actions"><button type="submit" class="btn btn-primary">Add work order</button></div> </form><% } %><%- 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>
<% } %>
<h2>Work orders</h2>
<% if (actions.length === 0) { %>
<p class="muted">No work orders yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>Work order</th><th>Assignee</th><th>Due</th><th>Status</th><th></th></tr></thead>
<tbody>
<% for (const a of actions) { const actionRef = { ...a, issue }; %>
<tr>
<td><%= a.title %></td>
<td><%= a.assignee_name %></td>
<td><%= a.due_on %></td>
<td><span class="badge status-<%= a.status === 'done' ? 'closed' : 'open' %>"><%= a.status %></span></td>
<td class="actions">
<% if (a.status === 'open' && can('CompleteWorkOrder', actionRef)) { %>
<form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/complete"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small">Mark done</button></form>
<% } %>
<% if (can('DeleteWorkOrder', actionRef)) { %>
<form method="post" action="/issues/<%= issue.id %>/actions/<%= a.id %>/delete" data-confirm="Delete this work order?"><input type="hidden" name="_csrf" value="<%= csrfToken %>"><button type="submit" class="btn btn-small btn-danger">Delete</button></form>
<% } %>
</td>
</tr>
<% } %>
</tbody>
</table>
<% } %>
<% if (assignees.length > 0) { %>
<h3>Add a work order</h3>
<form method="post" action="/issues/<%= issue.id %>/actions" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<div class="field<%= errors.title ? ' has-error' : '' %>">
<label for="action-title">What needs to be done</label>
<input id="action-title" name="title" value="<%= values.title ?? '' %>" maxlength="200">
<% if (errors.title) { %><p class="field-error"><%= errors.title %></p><% } %>
</div>
<div class="field<%= errors.assignee_id ? ' has-error' : '' %>">
<label for="assignee_id">Assignee</label>
<select id="assignee_id" name="assignee_id">
<% for (const u of assignees) { %><option value="<%= u.id %>"<%= values.assignee_id === u.id ? ' selected' : '' %>><%= u.name %></option><% } %>
</select>
<% if (errors.assignee_id) { %><p class="field-error"><%= errors.assignee_id %></p><% } %>
</div>
<div class="field<%= errors.due_on ? ' has-error' : '' %>">
<label for="due_on">Due</label>
<input id="due_on" name="due_on" type="date" value="<%= values.due_on ?? '' %>">
<% if (errors.due_on) { %><p class="field-error"><%= errors.due_on %></p><% } %>
</div>
<div class="form-actions"><button type="submit" class="btn btn-primary">Add work order</button></div>
</form>
<% } %>
<%- include('../partials/foot') %>
5. 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', 'bob', 'carol', 'dave']) agents[name] = await loginAs(name);});after(() => pool.end()); const form = (assigneeId) => ({ title: 'Reset the lift controller and test each floor', assignee_id: String(assigneeId), due_on: '2026-12-20' });const statusOf = async (id) => (await pool.query('SELECT status FROM work_orders WHERE id = $1', [id])).rows[0]?.status;const newestAction = async () => (await pool.query('SELECT max(id) AS id FROM work_orders')).rows[0].id; test('add a work order to issue 101, assigned to dave', async () => { const statuses = {}; for (const name of ['bob', 'dave', 'alice', 'carol']) statuses[name] = (await agents[name].post('/issues/101/actions').type('form').send(form(4))).status; assert.deepEqual(statuses, { bob: 404, dave: 403, alice: 303, carol: 303 });}); test('nobody assigns a work order to themselves', async () => { const statuses = {}; for (const [name, id] of [['alice', 1], ['carol', 3], ['dave', 4]]) statuses[name] = (await agents[name].post('/issues/101/actions').type('form').send(form(id))).status; assert.deepEqual(statuses, { alice: 403, carol: 403, dave: 403 });}); test('mark done: the assignee, building admins and organisation admins', async () => { assert.equal((await agents.bob.post('/issues/101/actions/301/complete')).status, 404); assert.equal((await agents.dave.post('/issues/101/actions/301/complete')).status, 303); assert.equal(await statusOf(301), 'done'); await agents.alice.post('/issues/101/actions').type('form').send(form(4)); const forAlice = await newestAction(); assert.equal((await agents.alice.post(`/issues/101/actions/${forAlice}/complete`)).status, 303); assert.equal(await statusOf(forAlice), 'done'); await agents.alice.post('/issues/101/actions').type('form').send(form(4)); const forCarol = await newestAction(); assert.equal((await agents.carol.post(`/issues/101/actions/${forCarol}/complete`)).status, 303); assert.equal(await statusOf(forCarol), 'done');}); test('delete: building admins only', async () => { const statuses = {}; for (const name of ['bob', 'dave', 'alice']) statuses[name] = (await agents[name].post('/issues/101/actions/301/delete')).status; assert.deepEqual(statuses, { bob: 404, dave: 403, alice: 303 }); assert.equal(await statusOf(301), undefined);}); test('the assignee must be able to view the issue', async () => { const res = await agents.alice.post('/issues/101/actions').type('form').send(form(2)); assert.equal(res.status, 400); assert.match(res.text, /Choose someone who can view this issue/);}); test('a work order id from another issue is not found', async () => { await agents.carol.post('/issues/103/actions').type('form').send(form(4)); const otherIssuesAction = await newestAction(); assert.equal((await agents.carol.post(`/issues/101/actions/${otherIssuesAction}/complete`)).status, 404); assert.equal(await statusOf(otherIssuesAction), 'open');});Add the new routes and table to the isolation suite:
const TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes'];const TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes', 'work_orders'];
['POST', '/issues/101/delete'], ['POST', '/issues/101/actions', { title: 'Injected work order', assignee_id: '2', due_on: '2026-12-20' }], ['POST', '/issues/101/actions/301/complete'], ['POST', '/issues/101/actions/301/delete'],
Show the whole test/tenant-isolation.test.js after this change
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 TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes', 'work_orders']; async function fingerprint() { const result = {}; for (const table of TABLES) { const { rows } = await pool.query(`SELECT md5(coalesce(string_agg(t::text, '|' ORDER BY t::text), '')) AS hash FROM ${table} t`); result[table] = rows[0].hash; } return result;} // Every route, pointed at Liffey (organisation 1, buildings 10 and 20).const ATTACKS_ON_LIFFEY = [ ['GET', '/organisations/1'], ['GET', '/organisations/1/edit'], ['POST', '/organisations/1/edit', { name: 'Taken over' }], ['POST', '/organisations/1/delete'], ['GET', '/organisations/1/members'], ['POST', '/organisations/1/members', { email: 'bob@example.test', role: 'org_admin' }], ['GET', '/organisations/1/buildings/new'], ['POST', '/organisations/1/buildings', { name: 'Hidden annex' }], ['GET', '/buildings/10'], ['GET', '/buildings/10/edit'], ['POST', '/buildings/10/edit', { name: 'Renamed' }], ['POST', '/buildings/10/delete'], ['GET', '/buildings/10/access'], ['POST', '/buildings/10/access', { user_id: '2', role: 'building_admin' }], ['POST', '/buildings/10/access/1/revoke'], ['GET', '/issues/101'], ['GET', '/issues/101/edit'], ['POST', '/issues/101/edit', { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-02T09:15' }], ['GET', '/issues/101/move'], ['POST', '/issues/101/move', { building_id: '30' }], ['POST', '/issues/101/delete'], ['POST', '/issues/101/actions', { title: 'Injected work order', assignee_id: '2', due_on: '2026-12-20' }], ['POST', '/issues/101/actions/301/complete'], ['POST', '/issues/101/actions/301/delete'], ['GET', '/inspections/201'], ['GET', '/inspections/203/edit'], ['POST', '/inspections/203/edit', { title: 'Changed', findings: '' }], ['POST', '/inspections/203/submit'], ['POST', '/inspections/201/approve'], ['POST', '/inspections/201/return'],]; const CREATES_IN_LIFFEY = [ ['POST', '/issues', { title: 'Injected issue', building_id: '10', priority: 'low', occurred_at: '2026-11-22T09:00' }], ['POST', '/inspections', { title: 'Injected inspection', building_id: '20', findings: '' }],]; const send = (agent, [method, path, form]) => (method === 'GET' ? agent.get(path) : agent.post(path).type('form').send(form ?? {})); let agents;before(async () => { await resetDatabase(); agents = { bob: await loginAs('bob'), ravi: await loginAs('ravi'), nora: await loginAs('nora') };});after(() => pool.end()); for (const name of ['bob', 'ravi', 'nora']) { test(`${name} gets 404 for every Liffey route, and nothing changes`, async () => { const before = await fingerprint(); const unexpected = []; for (const attack of ATTACKS_ON_LIFFEY) { const res = await send(agents[name], attack); if (res.status !== 404) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`); } for (const attack of CREATES_IN_LIFFEY) { const res = await send(agents[name], attack); if (res.status !== 400) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`); } assert.deepEqual(unexpected, []); assert.deepEqual(await fingerprint(), before); });} test('inside one tenant: alice, a viewer at building 20, cannot change anything there', async () => { const alice = await loginAs('alice'); const before = await fingerprint(); const attempts = [ ['GET', '/issues/103/edit', 403], ['POST', '/issues/103/edit', 403, { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-08T07:05' }], ['POST', '/issues/104/delete', 403], ['GET', '/buildings/20/edit', 403], ['GET', '/buildings/20/access', 403], ['POST', '/buildings/20/access/5/revoke', 403], ['POST', '/buildings/10/access/5/revoke', 404], ['POST', '/inspections/203/submit', 403], ]; const unexpected = []; for (const [method, path, expected, form] of attempts) { const res = await send(alice, [method, path, form]); if (res.status !== expected) unexpected.push(`${method} ${path} -> ${res.status}, expected ${expected}`); } assert.deepEqual(unexpected, []); assert.deepEqual(await fingerprint(), before);});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 TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes', 'work_orders'];
async function fingerprint() {
const result = {};
for (const table of TABLES) {
const { rows } = await pool.query(`SELECT md5(coalesce(string_agg(t::text, '|' ORDER BY t::text), '')) AS hash FROM ${table} t`);
result[table] = rows[0].hash;
}
return result;
}
// Every route, pointed at Liffey (organisation 1, buildings 10 and 20).
const ATTACKS_ON_LIFFEY = [
['GET', '/organisations/1'],
['GET', '/organisations/1/edit'],
['POST', '/organisations/1/edit', { name: 'Taken over' }],
['POST', '/organisations/1/delete'],
['GET', '/organisations/1/members'],
['POST', '/organisations/1/members', { email: 'bob@example.test', role: 'org_admin' }],
['GET', '/organisations/1/buildings/new'],
['POST', '/organisations/1/buildings', { name: 'Hidden annex' }],
['GET', '/buildings/10'],
['GET', '/buildings/10/edit'],
['POST', '/buildings/10/edit', { name: 'Renamed' }],
['POST', '/buildings/10/delete'],
['GET', '/buildings/10/access'],
['POST', '/buildings/10/access', { user_id: '2', role: 'building_admin' }],
['POST', '/buildings/10/access/1/revoke'],
['GET', '/issues/101'],
['GET', '/issues/101/edit'],
['POST', '/issues/101/edit', { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-02T09:15' }],
['GET', '/issues/101/move'],
['POST', '/issues/101/move', { building_id: '30' }],
['POST', '/issues/101/delete'],
['POST', '/issues/101/actions', { title: 'Injected work order', assignee_id: '2', due_on: '2026-12-20' }],
['POST', '/issues/101/actions/301/complete'],
['POST', '/issues/101/actions/301/delete'],
['GET', '/inspections/201'],
['GET', '/inspections/203/edit'],
['POST', '/inspections/203/edit', { title: 'Changed', findings: '' }],
['POST', '/inspections/203/submit'],
['POST', '/inspections/201/approve'],
['POST', '/inspections/201/return'],
];
const CREATES_IN_LIFFEY = [
['POST', '/issues', { title: 'Injected issue', building_id: '10', priority: 'low', occurred_at: '2026-11-22T09:00' }],
['POST', '/inspections', { title: 'Injected inspection', building_id: '20', findings: '' }],
];
const send = (agent, [method, path, form]) => (method === 'GET' ? agent.get(path) : agent.post(path).type('form').send(form ?? {}));
let agents;
before(async () => {
await resetDatabase();
agents = { bob: await loginAs('bob'), ravi: await loginAs('ravi'), nora: await loginAs('nora') };
});
after(() => pool.end());
for (const name of ['bob', 'ravi', 'nora']) {
test(`${name} gets 404 for every Liffey route, and nothing changes`, async () => {
const before = await fingerprint();
const unexpected = [];
for (const attack of ATTACKS_ON_LIFFEY) {
const res = await send(agents[name], attack);
if (res.status !== 404) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`);
}
for (const attack of CREATES_IN_LIFFEY) {
const res = await send(agents[name], attack);
if (res.status !== 400) unexpected.push(`${attack[0]} ${attack[1]} -> ${res.status}`);
}
assert.deepEqual(unexpected, []);
assert.deepEqual(await fingerprint(), before);
});
}
test('inside one tenant: alice, a viewer at building 20, cannot change anything there', async () => {
const alice = await loginAs('alice');
const before = await fingerprint();
const attempts = [
['GET', '/issues/103/edit', 403],
['POST', '/issues/103/edit', 403, { title: 'Changed', priority: 'low', status: 'closed', occurred_at: '2026-11-08T07:05' }],
['POST', '/issues/104/delete', 403],
['GET', '/buildings/20/edit', 403],
['GET', '/buildings/20/access', 403],
['POST', '/buildings/20/access/5/revoke', 403],
['POST', '/buildings/10/access/5/revoke', 404],
['POST', '/inspections/203/submit', 403],
];
const unexpected = [];
for (const [method, path, expected, form] of attempts) {
const res = await send(alice, [method, path, form]);
if (res.status !== expected) unexpected.push(`${method} ${path} -> ${res.status}, expected ${expected}`);
}
assert.deepEqual(unexpected, []);
assert.deepEqual(await fingerprint(), before);
});
Run and inspect
npm run check
> caretaker@1.0.0 check
> npm run authz:validate && npm test
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
15 policies are valid against the schema
> 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) (492.695375ms)
✔ edit issue 101 (26.801125ms)
✔ view issue 103 (building 20) (28.910375ms)
✔ edit issue 103 (reported by dave) (25.233ms)
✔ report an issue at building 20 (30.0155ms)
✔ view issue 105 (building 30) (19.83575ms)
✔ view issue 106 (building 40, reported by bob) (22.323167ms)
✔ approve inspection 201 (created by dave) (18.843917ms)
✔ approve inspection 202 (created by alice) (20.747083ms)
✔ update organisation 1 (25.736875ms)
✔ change own role at building 10 (4.512208ms)
✔ grant building_admin at building 10 to dave (19.103417ms)
✔ grant viewer at building 10 to dave (17.856208ms)
✔ issues in each user's list come only from the expected buildings (112.594291ms)
✔ the scenario loads exactly as specified (211.770792ms)
✔ only one active assignment per user, building and role (0.933541ms)
✔ a revoked role can be granted again (1.237875ms)
✔ the My access page shows what the server loaded (71.306792ms)
✔ a correct login creates a session and shows the user (275.10625ms)
✔ a wrong password or unknown email gets the same 401 (52.506709ms)
✔ registration validates, creates a user, and logs them in (42.193333ms)
✔ registering an existing email is a field error (33.900334ms)
✔ logout destroys the session (46.500584ms)
✔ allow: a permit matched and nothing forbade it (213.445458ms)
✔ explicit deny: a forbid overrides a matching permit (3.263333ms)
✔ implicit deny: no permit matched (2.48175ms)
authz problem {
Show 127 more lines
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.599708ms)
✔ unknown actions throw instead of deciding (1.296875ms)
✔ unknown callers are refused (196.720125ms)
✔ decisions match the app (25.798167ms)
✔ attributes sent by the caller are ignored (3.33025ms)
✔ context is validated and used (10.207084ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (405.351375ms)
✔ a revoked assignment cannot be revoked again (4.216ms)
✔ an assignment id from another building is not found here (6.627625ms)
✔ alice cannot revoke her own building_admin role; carol can (12.888875ms)
✔ grants are limited to members of the building's organisation (6.482542ms)
✔ a building can be created inside an organisation (294.661625ms)
✔ a duplicate building name in the same organisation is a field error (5.53725ms)
✔ the same building name is allowed in another organisation (9.131959ms)
✔ a building with issues cannot be deleted (15.500542ms)
✔ an empty building can be deleted (10.925666ms)
✔ an organisation with buildings cannot be deleted, an empty one can (24.372917ms)
✔ a logged-in POST without a token is refused with 403 (273.932208ms)
✔ a token from another session is refused (37.428625ms)
✔ the right token in the form field works (19.963084ms)
✔ every POST form on every page carries the token (57.874417ms)
✔ the dashboard counts match the database (272.304917ms)
✔ only the buildings carol can see appear (4.7375ms)
✔ headers that claim another identity are ignored (282.993708ms)
✔ query strings and form fields that claim roles are ignored (11.042334ms)
✔ a forged reporter or status in an edit form does not reach the database (6.246583ms)
✔ a forged grant context cannot make dave a building admin (5.096167ms)
✔ responses carry security headers and a request id, and no framework banner (211.986125ms)
✔ error pages show the request id as a reference (68.144792ms)
✔ unsafe production settings are reported (0.337584ms)
✔ create a draft, edit it, submit it, approve it (349.849958ms)
✔ invalid transitions are refused with 409 and change nothing (12.107917ms)
✔ only drafts can be edited (5.63625ms)
✔ returning a submitted inspection makes it editable again (7.912166ms)
✔ concurrent approvals: exactly one wins (24.908ms)
✔ unknown actions are 404 (3.1375ms)
✔ the issues list contains only issues from visible buildings (566.227959ms)
✔ a filter for another tenant's building returns nothing (3.766625ms)
✔ the inspections list is scoped too (10.701333ms)
✔ organisations are listed for their members only (8.463125ms)
✔ the dashboard counts only visible data (7.016334ms)
✔ view issue 101 (building 10) (490.914875ms)
✔ open the edit form for issue 101 (25.988708ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (24.07075ms)
✔ view issue 105 (building 30) and 106 (building 40) (44.654666ms)
✔ report an issue at building 20 (26.416792ms)
✔ a reporter cannot edit their own issue once it is closed (10.181833ms)
✔ only building admins may delete; refusals change nothing (16.050209ms)
✔ the edit form cannot move an issue to another building (4.029458ms)
✔ the list pages 10 at a time and reports the total (301.137667ms)
✔ pages do not overlap (26.066708ms)
✔ filters combine with AND (7.586042ms)
✔ sorting by priority puts critical first when descending (7.588833ms)
✔ unknown sort keys and SQL in the query string are ignored (42.043542ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (364.317042ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (6.700333ms)
✔ dave cannot move issue 101: he may not update it where it is (4.710875ms)
✔ carol moves 101 to building 20, but never to another organisation (11.209917ms)
✔ a forged building id on create is refused and creates nothing (25.118083ms)
✔ GET /issues lists issues from the database (301.2225ms)
✔ GET /issues/101 shows one issue with its building (9.1405ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (15.265166ms)
✔ POST /issues re-renders the form with errors (5.045292ms)
✔ POST /issues stores the issue and redirects to it (10.304083ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.978917ms)
✔ the stored row has the cleaned values and ignores a client-sent status (5.152833ms)
✔ an issue time in the future is rejected (4.864166ms)
✔ GET /issues/101/edit shows the current values (6.128458ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.061083ms)
✔ POST /issues/:id/delete removes the issue (9.43475ms)
✔ the issues list contains exactly the issues Cedar lets each user view (339.281542ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (21.513125ms)
✔ only organisation admins can open the members page (425.555125ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (17.731333ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.953917ms)
✔ nobody changes their own membership (6.2815ms)
✔ unknown emails and roles are form errors (12.019042ms)
✔ a member cannot add members, even with a well-formed request (4.416ms)
✔ GET /organisations lists organisations with building counts (280.719708ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (13.531875ms)
✔ POST /organisations validates and creates (15.420166ms)
✔ POST /organisations/:id/edit renames the organisation (10.400584ms)
✔ unknown organisations are 404 (5.98925ms)
✔ every policy is valid against the schema (32.744458ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.623625ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (338.953958ms)
✔ anonymous requests are redirected to the login page (214.94575ms)
✔ anonymous writes are refused and change nothing (10.928875ms)
✔ login and register pages stay public (6.774541ms)
✔ login issues a new session id (no session fixation) (34.329791ms)
✔ returnTo only follows local paths (27.053125ms)
✔ new issues and transitions record the logged-in user (79.299083ms)
✔ the session cookie has the attributes we chose (25.92575ms)
✔ organisation 1: view and update (501.54525ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (8.125708ms)
✔ building 10: view, update, delete (62.406625ms)
✔ creating buildings needs org_admin (18.549208ms)
✔ creating an organisation makes the creator its admin (9.88125ms)
✔ inspections: view 201, open the edit form for draft 203 (47.187708ms)
✔ approve inspection 201 (dave's): only building admins (19.915167ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (14.571625ms)
✔ bob gets 404 for every Liffey route, and nothing changes (463.579292ms)
✔ ravi gets 404 for every Liffey route, and nothing changes (110.404083ms)
✔ nora gets 404 for every Liffey route, and nothing changes (87.122458ms)
✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (67.186416ms)
✔ add a work order to issue 101, assigned to dave (411.245792ms)
✔ nobody assigns a work order to themselves (16.498083ms)
✔ mark done: the assignee, building admins and organisation admins (30.222833ms)
✔ delete: building admins only (12.920083ms)
✔ the assignee must be able to view the issue (9.275083ms)
✔ a work order id from another issue is not found (10.775167ms)
ℹ tests 137
ℹ suites 0
ℹ pass 137
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15628.1545
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
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


Add a work order as Alice with curl, and read Cedar's decision with its context in the log:
rm -f /tmp/alice.txt
TOKEN=$(curl -s -c /tmp/alice.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/alice.txt -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=password123
TOKEN=$(curl -s -b /tmp/alice.txt http://localhost:3000/account | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/alice.txt http://localhost:3000/issues/101/actions -d _csrf=$TOKEN -d title="Check the lift door sensor after one week" -d assignee_id=4 -d due_on=2026-12-22
303
authz user=1 action=ViewIssue resource=Issue::101 decision=allow reasons=building-read
authz user=1 action=CreateWorkOrder resource=Issue::101 decision=allow reasons=building-admin
d443deb4 POST /issues/101/actions -> 303 (13 ms)
Experiment
forbid-self-assignment policy. Which tests fail?mv src/authz/policies/forbid-self-assignment.cedar /tmp/forbid-self-assignment.cedar.disabled
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) (502.326875ms)
✔ edit issue 101 (26.211125ms)
✔ view issue 103 (building 20) (26.438ms)
✔ edit issue 103 (reported by dave) (22.80675ms)
✔ report an issue at building 20 (29.427083ms)
✔ view issue 105 (building 30) (18.822792ms)
✔ view issue 106 (building 40, reported by bob) (20.091791ms)
✔ approve inspection 201 (created by dave) (17.464042ms)
✔ approve inspection 202 (created by alice) (21.464125ms)
✔ update organisation 1 (17.441583ms)
✔ change own role at building 10 (5.452875ms)
✔ grant building_admin at building 10 to dave (22.659959ms)
✔ grant viewer at building 10 to dave (15.920167ms)
✔ issues in each user's list come only from the expected buildings (116.139ms)
✔ the scenario loads exactly as specified (208.256667ms)
✔ only one active assignment per user, building and role (0.812041ms)
✔ a revoked role can be granted again (1.60725ms)
✔ the My access page shows what the server loaded (71.325084ms)
✔ a correct login creates a session and shows the user (267.68925ms)
✔ a wrong password or unknown email gets the same 401 (53.338958ms)
✔ registration validates, creates a user, and logs them in (37.519792ms)
✔ registering an existing email is a field error (29.096792ms)
✔ logout destroys the session (47.200708ms)
✔ allow: a permit matched and nothing forbade it (215.489166ms)
✔ explicit deny: a forbid overrides a matching permit (2.802417ms)
✔ implicit deny: no permit matched (2.199709ms)
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.073416ms)
Show 145 more lines
✔ unknown actions throw instead of deciding (1.354125ms)
✔ unknown callers are refused (206.594333ms)
✔ decisions match the app (28.40025ms)
✔ attributes sent by the caller are ignored (4.169208ms)
✔ context is validated and used (11.989875ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (428.899209ms)
✔ a revoked assignment cannot be revoked again (4.4055ms)
✔ an assignment id from another building is not found here (5.449208ms)
✔ alice cannot revoke her own building_admin role; carol can (12.870833ms)
✔ grants are limited to members of the building's organisation (6.275417ms)
✔ a building can be created inside an organisation (298.010084ms)
✔ a duplicate building name in the same organisation is a field error (5.174459ms)
✔ the same building name is allowed in another organisation (9.659ms)
✔ a building with issues cannot be deleted (13.948542ms)
✔ an empty building can be deleted (10.480791ms)
✔ an organisation with buildings cannot be deleted, an empty one can (25.134083ms)
✔ a logged-in POST without a token is refused with 403 (269.395625ms)
✔ a token from another session is refused (33.546ms)
✔ the right token in the form field works (23.585291ms)
✔ every POST form on every page carries the token (62.291584ms)
✔ the dashboard counts match the database (263.537042ms)
✔ only the buildings carol can see appear (5.3555ms)
✔ headers that claim another identity are ignored (5329.00975ms)
✔ query strings and form fields that claim roles are ignored (13.96975ms)
✔ a forged reporter or status in an edit form does not reach the database (7.136541ms)
✔ a forged grant context cannot make dave a building admin (5.423625ms)
✔ responses carry security headers and a request id, and no framework banner (224.103292ms)
✔ error pages show the request id as a reference (82.721042ms)
✔ unsafe production settings are reported (0.375292ms)
✔ create a draft, edit it, submit it, approve it (348.961208ms)
✔ invalid transitions are refused with 409 and change nothing (12.411875ms)
✔ only drafts can be edited (6.08425ms)
✔ returning a submitted inspection makes it editable again (8.889542ms)
✔ concurrent approvals: exactly one wins (32.846125ms)
✔ unknown actions are 404 (2.7105ms)
✔ the issues list contains only issues from visible buildings (600.528209ms)
✔ a filter for another tenant's building returns nothing (4.102458ms)
✔ the inspections list is scoped too (9.484584ms)
✔ organisations are listed for their members only (8.052042ms)
✔ the dashboard counts only visible data (8.315958ms)
✔ view issue 101 (building 10) (493.724958ms)
✔ open the edit form for issue 101 (26.31675ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (27.827667ms)
✔ view issue 105 (building 30) and 106 (building 40) (46.170125ms)
✔ report an issue at building 20 (25.540625ms)
✔ a reporter cannot edit their own issue once it is closed (8.392166ms)
✔ only building admins may delete; refusals change nothing (18.129875ms)
✔ the edit form cannot move an issue to another building (4.531417ms)
✔ the list pages 10 at a time and reports the total (305.104167ms)
✔ pages do not overlap (23.126542ms)
✔ filters combine with AND (7.481584ms)
✔ sorting by priority puts critical first when descending (7.730333ms)
✔ unknown sort keys and SQL in the query string are ignored (41.747459ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (343.59775ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (6.503875ms)
✔ dave cannot move issue 101: he may not update it where it is (5.553375ms)
✔ carol moves 101 to building 20, but never to another organisation (10.039333ms)
✔ a forged building id on create is refused and creates nothing (25.502875ms)
✔ GET /issues lists issues from the database (290.200125ms)
✔ GET /issues/101 shows one issue with its building (8.577958ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (15.932917ms)
✔ POST /issues re-renders the form with errors (4.873375ms)
✔ POST /issues stores the issue and redirects to it (12.397541ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.667625ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.331833ms)
✔ an issue time in the future is rejected (4.69925ms)
✔ GET /issues/101/edit shows the current values (6.630208ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.149ms)
✔ POST /issues/:id/delete removes the issue (9.46425ms)
✔ the issues list contains exactly the issues Cedar lets each user view (347.075583ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (21.4255ms)
✔ only organisation admins can open the members page (436.749667ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (16.935ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.93325ms)
✔ nobody changes their own membership (4.111375ms)
✔ unknown emails and roles are form errors (9.747208ms)
✔ a member cannot add members, even with a well-formed request (3.596625ms)
✔ GET /organisations lists organisations with building counts (274.616166ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (13.645459ms)
✔ POST /organisations validates and creates (15.295291ms)
✔ POST /organisations/:id/edit renames the organisation (10.624292ms)
✔ unknown organisations are 404 (6.029667ms)
✔ every policy is valid against the schema (33.268375ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.783375ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (359.640625ms)
✔ anonymous requests are redirected to the login page (214.860416ms)
✔ anonymous writes are refused and change nothing (10.55325ms)
✔ login and register pages stay public (6.169458ms)
✔ login issues a new session id (no session fixation) (32.720125ms)
✔ returnTo only follows local paths (26.80975ms)
✔ new issues and transitions record the logged-in user (82.457041ms)
✔ the session cookie has the attributes we chose (28.312666ms)
✔ organisation 1: view and update (513.911083ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (12.403792ms)
✔ building 10: view, update, delete (60.9105ms)
✔ creating buildings needs org_admin (16.86ms)
✔ creating an organisation makes the creator its admin (9.933291ms)
✔ inspections: view 201, open the edit form for draft 203 (44.476166ms)
✔ approve inspection 201 (dave's): only building admins (18.555334ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (14.3605ms)
✔ bob gets 404 for every Liffey route, and nothing changes (444.615333ms)
✔ ravi gets 404 for every Liffey route, and nothing changes (95.7065ms)
✔ nora gets 404 for every Liffey route, and nothing changes (90.022208ms)
✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (69.35375ms)
✔ add a work order to issue 101, assigned to dave (405.007167ms)
✖ nobody assigns a work order to themselves (16.154416ms)
✔ mark done: the assignee, building admins and organisation admins (28.653542ms)
✔ delete: building admins only (12.058125ms)
✔ the assignee must be able to view the issue (13.053958ms)
✔ a work order id from another issue is not found (8.275375ms)
ℹ tests 137
ℹ suites 0
ℹ pass 136
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 20677.139917
✖ failing tests:
test at test/work-orders.test.js:23:1
✖ nobody assigns a work order to themselves (16.154416ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
+ alice: 303,
+ carol: 303,
- alice: 403,
- carol: 403,
dave: 403
}
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/work-orders.test.js:26:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: { alice: 303, carol: 303, dave: 403 },
expected: { alice: 403, carol: 403, dave: 403 },
operator: 'deepStrictEqual',
diff: 'simple'
}
Reveal Answer
"nobody assigns a work order to themselves" fails: Alice and Carol now get 303 (the building-admin group permits CreateWorkOrder), while Dave still gets 403 because no permit covers him. Exactly the pattern of lessons 6.6 and 7.4: exceptions are forbids, and tests pin them.
Put the policy back:
mv /tmp/forbid-self-assignment.cedar.disabled src/authz/policies/forbid-self-assignment.cedar
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) (481.8075ms)
✔ edit issue 101 (26.649834ms)
✔ view issue 103 (building 20) (24.127042ms)
✔ edit issue 103 (reported by dave) (23.119875ms)
✔ report an issue at building 20 (22.877583ms)
✔ view issue 105 (building 30) (25.574292ms)
✔ view issue 106 (building 40, reported by bob) (18.438583ms)
✔ approve inspection 201 (created by dave) (21.75875ms)
✔ approve inspection 202 (created by alice) (22.487166ms)
✔ update organisation 1 (17.859541ms)
✔ change own role at building 10 (4.864167ms)
✔ grant building_admin at building 10 to dave (24.352ms)
✔ grant viewer at building 10 to dave (18.06625ms)
✔ issues in each user's list come only from the expected buildings (130.244333ms)
✔ the scenario loads exactly as specified (213.29775ms)
✔ only one active assignment per user, building and role (0.873917ms)
✔ a revoked role can be granted again (1.225333ms)
✔ the My access page shows what the server loaded (76.936041ms)
✔ a correct login creates a session and shows the user (270.863083ms)
✔ a wrong password or unknown email gets the same 401 (53.651542ms)
✔ registration validates, creates a user, and logs them in (39.525625ms)
✔ registering an existing email is a field error (29.216334ms)
✔ logout destroys the session (50.499209ms)
✔ allow: a permit matched and nothing forbade it (214.999042ms)
✔ explicit deny: a forbid overrides a matching permit (3.009916ms)
✔ implicit deny: no permit matched (2.135375ms)
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.029083ms)
Show 118 more lines
✔ unknown actions throw instead of deciding (1.337875ms)
✔ unknown callers are refused (213.202792ms)
✔ decisions match the app (25.292291ms)
✔ attributes sent by the caller are ignored (3.298125ms)
✔ context is validated and used (9.997083ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (408.295ms)
✔ a revoked assignment cannot be revoked again (4.5145ms)
✔ an assignment id from another building is not found here (3.973667ms)
✔ alice cannot revoke her own building_admin role; carol can (14.024166ms)
✔ grants are limited to members of the building's organisation (6.927667ms)
✔ a building can be created inside an organisation (289.135375ms)
✔ a duplicate building name in the same organisation is a field error (5.6135ms)
✔ the same building name is allowed in another organisation (9.061208ms)
✔ a building with issues cannot be deleted (15.046625ms)
✔ an empty building can be deleted (11.701625ms)
✔ an organisation with buildings cannot be deleted, an empty one can (24.383292ms)
✔ a logged-in POST without a token is refused with 403 (282.746167ms)
✔ a token from another session is refused (36.969875ms)
✔ the right token in the form field works (20.790625ms)
✔ every POST form on every page carries the token (63.738791ms)
✔ the dashboard counts match the database (275.323583ms)
✔ only the buildings carol can see appear (5.212875ms)
✔ headers that claim another identity are ignored (287.892958ms)
✔ query strings and form fields that claim roles are ignored (13.060833ms)
✔ a forged reporter or status in an edit form does not reach the database (5.564458ms)
✔ a forged grant context cannot make dave a building admin (4.503375ms)
✔ responses carry security headers and a request id, and no framework banner (252.570792ms)
✔ error pages show the request id as a reference (76.291042ms)
✔ unsafe production settings are reported (0.342625ms)
✔ create a draft, edit it, submit it, approve it (336.358958ms)
✔ invalid transitions are refused with 409 and change nothing (11.986459ms)
✔ only drafts can be edited (6.195875ms)
✔ returning a submitted inspection makes it editable again (9.943084ms)
✔ concurrent approvals: exactly one wins (27.503417ms)
✔ unknown actions are 404 (3.138458ms)
✔ the issues list contains only issues from visible buildings (583.778917ms)
✔ a filter for another tenant's building returns nothing (3.815875ms)
✔ the inspections list is scoped too (10.514292ms)
✔ organisations are listed for their members only (10.767542ms)
✔ the dashboard counts only visible data (6.845458ms)
✔ view issue 101 (building 10) (519.429209ms)
✔ open the edit form for issue 101 (27.873416ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (24.359333ms)
✔ view issue 105 (building 30) and 106 (building 40) (48.621292ms)
✔ report an issue at building 20 (23.234833ms)
✔ a reporter cannot edit their own issue once it is closed (7.731417ms)
✔ only building admins may delete; refusals change nothing (14.914208ms)
✔ the edit form cannot move an issue to another building (5.191708ms)
✔ the list pages 10 at a time and reports the total (304.943125ms)
✔ pages do not overlap (24.8755ms)
✔ filters combine with AND (7.630875ms)
✔ sorting by priority puts critical first when descending (8.063ms)
✔ unknown sort keys and SQL in the query string are ignored (43.704834ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (351.182458ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (6.540792ms)
✔ dave cannot move issue 101: he may not update it where it is (4.97ms)
✔ carol moves 101 to building 20, but never to another organisation (9.918916ms)
✔ a forged building id on create is refused and creates nothing (25.568125ms)
✔ GET /issues lists issues from the database (294.428125ms)
✔ GET /issues/101 shows one issue with its building (9.868333ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.043958ms)
✔ POST /issues re-renders the form with errors (5.445583ms)
✔ POST /issues stores the issue and redirects to it (9.971959ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.826959ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.866167ms)
✔ an issue time in the future is rejected (4.949708ms)
✔ GET /issues/101/edit shows the current values (6.077375ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.297333ms)
✔ POST /issues/:id/delete removes the issue (10.053625ms)
✔ the issues list contains exactly the issues Cedar lets each user view (320.921084ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (20.909791ms)
✔ only organisation admins can open the members page (449.661125ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (18.262083ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (13.289167ms)
✔ nobody changes their own membership (4.750625ms)
✔ unknown emails and roles are form errors (12.337667ms)
✔ a member cannot add members, even with a well-formed request (4.554875ms)
✔ GET /organisations lists organisations with building counts (269.973792ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (14.764791ms)
✔ POST /organisations validates and creates (14.233708ms)
✔ POST /organisations/:id/edit renames the organisation (11.38025ms)
✔ unknown organisations are 404 (6.240208ms)
✔ every policy is valid against the schema (33.240083ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.276208ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (354.219292ms)
✔ anonymous requests are redirected to the login page (220.015958ms)
✔ anonymous writes are refused and change nothing (10.835416ms)
✔ login and register pages stay public (5.63425ms)
✔ login issues a new session id (no session fixation) (32.5995ms)
✔ returnTo only follows local paths (27.872083ms)
✔ new issues and transitions record the logged-in user (81.46975ms)
✔ the session cookie has the attributes we chose (25.733625ms)
✔ organisation 1: view and update (479.179917ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (8.955292ms)
✔ building 10: view, update, delete (61.2855ms)
✔ creating buildings needs org_admin (21.014584ms)
✔ creating an organisation makes the creator its admin (10.350417ms)
✔ inspections: view 201, open the edit form for draft 203 (48.633833ms)
✔ approve inspection 201 (dave's): only building admins (20.161375ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (12.773958ms)
✔ bob gets 404 for every Liffey route, and nothing changes (454.534292ms)
✔ ravi gets 404 for every Liffey route, and nothing changes (91.338834ms)
✔ nora gets 404 for every Liffey route, and nothing changes (86.502208ms)
✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (68.881458ms)
✔ add a work order to issue 101, assigned to dave (406.281458ms)
✔ nobody assigns a work order to themselves (16.403875ms)
✔ mark done: the assignee, building admins and organisation admins (28.923166ms)
✔ delete: building admins only (13.305083ms)
✔ the assignee must be able to view the issue (10.5375ms)
✔ a work order id from another issue is not found (9.263333ms)
ℹ tests 137
ℹ suites 0
ℹ pass 137
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15732.124708
git add -A
git commit -m "Capstone: work orders"
[main ebd2e89] Capstone: work orders
13 files changed, 314 insertions(+), 4 deletions(-)
create mode 100644 migrations/007_create_work_orders.sql
create mode 100644 src/authz/policies/assignee-completes-work-order.cedar
create mode 100644 src/authz/policies/forbid-self-assignment.cedar
create mode 100644 src/authz/policies/reporter-creates-work-orders.cedar
create mode 100644 src/models/work-orders.js
create mode 100644 test/work-orders.test.js
Symptom Unknown resource type WorkOrder or missing issue
Routes must pass the work order with its issue attached ({ ...action, issue }), because the request needs the issue, building and organisation entities.
Symptom Due dates show one day off
A date column parsed into a JavaScript Date is midnight local time. Format it in SQL (to_char), as the model does.
Recap and next step
The feature needed one table, one model, one entity type, four actions in existing groups, two permits and one forbid. The parent chain and the action groups gave viewing and administration for free; the context carried the proposed assignee; a data rule reused the list condition; and the tests, including the isolation suite, pinned every cell.
That is the end of the course. You built Caretaker from an empty folder, and you can explain every step from a cookie to a Cedar decision. Keep npm run check green, read decision logs, and remember the boundary: Cedar decides correctly about the facts you give it; making those facts true is your code's job.
Open the checkpoint files for lesson 10.5 (separate page; only files from this lesson and earlier)