Module 8 · Lists, writes and multi-tenant isolation
8.3 An isolation test suite
Attack every route with another tenant's identifiers, as two different users, and prove that every request is refused and that the database does not change by a single byte.
Starting point
Isolation is tested piece by piece: the access matrix, list parity, moves, members, building access. No single test tries every route with foreign identifiers.
Outcome
test/tenant-isolation.test.js (new)One suite sends every read and write route in Caretaker, with identifiers that belong to another tenant or to a building where the user lacks the role, and checks two things: the status code, and a fingerprint of every table before and after.
The problem
The most common multi-tenant bug is not a missing login. It is identifier substitution: a logged-in user changes an ID in a URL or a form field to one that belongs to someone else (often called IDOR, insecure direct object reference). Each route we wrote loads by ID and then authorizes, so each route is protected, if nobody forgets. A suite that tries all of them makes "nobody forgot" a fact you can rerun.
Checking the status code is not enough. A route could answer 404 and still have changed something before deciding. So we also fingerprint the data.
Build it
1. A fingerprint of the database
row::text turns a whole row into text; md5(string_agg(...)) hashes all rows of a table in a stable order. Two equal fingerprints mean no row changed.
2. The suite
Create test/tenant-isolation.test.js:
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const TABLES = ['organisations', 'buildings', 'users', 'memberships', 'building_role_assignments', 'issues', 'inspections', 'inspection_status_changes', 'permission_changes']; 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'], ['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);});- Three attackers. Bob belongs to the other tenant. Ravi belongs to the other tenant and was revoked. Nora belongs to no tenant. All three must get
404for every Liffey route: from their point of view, organisation 1 does not exist. - Creates answer
400, because the building comes from the form and is treated as a field error (lesson 8.2). - Inside one tenant, Alice can see building 20 but holds no change rights there, so the answers are
403. One line is404: assignment 5 belongs to building 20, so it does not exist under/buildings/10/access/.... That is the substitution check infindActiveAssignment. - The fingerprint compares nine tables, before and after all attempts.
Run and inspect
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (482.646916ms)
✔ edit issue 101 (21.728083ms)
✔ view issue 103 (building 20) (20.583416ms)
✔ edit issue 103 (reported by dave) (22.797084ms)
✔ report an issue at building 20 (24.817875ms)
✔ view issue 105 (building 30) (16.871375ms)
✔ view issue 106 (building 40, reported by bob) (16.361375ms)
✔ approve inspection 201 (created by dave) (15.228167ms)
✔ approve inspection 202 (created by alice) (18.347ms)
✔ update organisation 1 (16.352291ms)
✔ change own role at building 10 (4.170292ms)
✔ grant building_admin at building 10 to dave (19.484709ms)
✔ grant viewer at building 10 to dave (15.836583ms)
✔ issues in each user's list come only from the expected buildings (109.631625ms)
✔ the scenario loads exactly as specified (213.365583ms)
✔ only one active assignment per user, building and role (0.909208ms)
✔ a revoked role can be granted again (0.979209ms)
✔ the My access page shows what the server loaded (75.757709ms)
✔ a correct login creates a session and shows the user (264.951791ms)
✔ a wrong password or unknown email gets the same 401 (53.749042ms)
✔ registration validates, creates a user, and logs them in (47.517958ms)
✔ registering an existing email is a field error (29.563125ms)
✔ logout destroys the session (57.102583ms)
✔ allow: a permit matched and nothing forbade it (219.48225ms)
✔ explicit deny: a forbid overrides a matching permit (2.686417ms)
✔ implicit deny: no permit matched (2.473375ms)
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.190458ms)
Show 101 more lines
✔ unknown actions throw instead of deciding (1.430792ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (366.880541ms)
✔ a revoked assignment cannot be revoked again (4.859416ms)
✔ an assignment id from another building is not found here (3.966292ms)
✔ alice cannot revoke her own building_admin role; carol can (11.879334ms)
✔ grants are limited to members of the building's organisation (6.742458ms)
✔ a building can be created inside an organisation (290.074625ms)
✔ a duplicate building name in the same organisation is a field error (5.356625ms)
✔ the same building name is allowed in another organisation (10.233167ms)
✔ a building with issues cannot be deleted (14.146125ms)
✔ an empty building can be deleted (9.858042ms)
✔ an organisation with buildings cannot be deleted, an empty one can (25.760375ms)
✔ a logged-in POST without a token is refused with 403 (276.447125ms)
✔ a token from another session is refused (36.703459ms)
✔ the right token in the form field works (18.857208ms)
✔ every POST form on every page carries the token (52.282167ms)
✔ the dashboard counts match the database (276.58925ms)
✔ only the buildings carol can see appear (5.897167ms)
✔ create a draft, edit it, submit it, approve it (351.565125ms)
✔ invalid transitions are refused with 409 and change nothing (12.4265ms)
✔ only drafts can be edited (8.182583ms)
✔ returning a submitted inspection makes it editable again (8.182666ms)
✔ concurrent approvals: exactly one wins (27.551333ms)
✔ unknown actions are 404 (3.41975ms)
✔ the issues list contains only issues from visible buildings (583.592834ms)
✔ a filter for another tenant's building returns nothing (4.055375ms)
✔ the inspections list is scoped too (11.027417ms)
✔ organisations are listed for their members only (8.877292ms)
✔ the dashboard counts only visible data (9.469916ms)
✔ view issue 101 (building 10) (463.397958ms)
✔ open the edit form for issue 101 (25.499584ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (22.686ms)
✔ view issue 105 (building 30) and 106 (building 40) (37.998375ms)
✔ report an issue at building 20 (23.363458ms)
✔ a reporter cannot edit their own issue once it is closed (8.9195ms)
✔ only building admins may delete; refusals change nothing (14.914333ms)
✔ the edit form cannot move an issue to another building (3.842417ms)
✔ the list pages 10 at a time and reports the total (306.830708ms)
✔ pages do not overlap (27.142666ms)
✔ filters combine with AND (6.956583ms)
✔ sorting by priority puts critical first when descending (7.193875ms)
✔ unknown sort keys and SQL in the query string are ignored (40.573583ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (372.032208ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (7.122ms)
✔ dave cannot move issue 101: he may not update it where it is (4.893625ms)
✔ carol moves 101 to building 20, but never to another organisation (13.039917ms)
✔ a forged building id on create is refused and creates nothing (26.519042ms)
✔ GET /issues lists issues from the database (290.198ms)
✔ GET /issues/101 shows one issue with its building (7.199709ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.601417ms)
✔ POST /issues re-renders the form with errors (5.088875ms)
✔ POST /issues stores the issue and redirects to it (8.088084ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.225292ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.538083ms)
✔ an issue time in the future is rejected (5.749167ms)
✔ GET /issues/101/edit shows the current values (5.302375ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.756958ms)
✔ POST /issues/:id/delete removes the issue (11.180083ms)
✔ the issues list contains exactly the issues Cedar lets each user view (332.413917ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (21.02625ms)
✔ only organisation admins can open the members page (431.971459ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (17.863541ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (13.088333ms)
✔ nobody changes their own membership (4.167ms)
✔ unknown emails and roles are form errors (12.090209ms)
✔ a member cannot add members, even with a well-formed request (3.948792ms)
✔ GET /organisations lists organisations with building counts (264.387791ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (14.46125ms)
✔ POST /organisations validates and creates (14.068542ms)
✔ POST /organisations/:id/edit renames the organisation (11.183709ms)
✔ unknown organisations are 404 (6.094917ms)
✔ every policy is valid against the schema (31.697125ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.595959ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (340.549791ms)
✔ anonymous requests are redirected to the login page (216.4155ms)
✔ anonymous writes are refused and change nothing (10.640375ms)
✔ login and register pages stay public (5.777708ms)
✔ login issues a new session id (no session fixation) (32.701041ms)
✔ returnTo only follows local paths (31.85475ms)
✔ new issues and transitions record the logged-in user (97.241041ms)
✔ the session cookie has the attributes we chose (26.227958ms)
✔ organisation 1: view and update (498.138334ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (8.586792ms)
✔ building 10: view, update, delete (63.2525ms)
✔ creating buildings needs org_admin (18.434666ms)
✔ creating an organisation makes the creator its admin (9.842167ms)
✔ inspections: view 201, open the edit form for draft 203 (43.590542ms)
✔ approve inspection 201 (dave's): only building admins (19.32525ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (12.920125ms)
✔ bob gets 404 for every Liffey route, and nothing changes (436.865625ms)
✔ ravi gets 404 for every Liffey route, and nothing changes (85.831ms)
✔ nora gets 404 for every Liffey route, and nothing changes (84.684ms)
✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (66.503625ms)
ℹ tests 120
ℹ suites 0
ℹ pass 120
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13303.909917
95 attempts across four tests (29 for each outsider, 8 for Alice), every one refused, and the fingerprints are identical.
Experiment
Remove the building condition from findActiveAssignment, the way a hurried refactor might:
'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND building_id = $2 AND revoked_at IS NULL', [id, buildingId], 'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND revoked_at IS NULL', [id],
Show the whole src/models/assignments.js after this change
import { query, withTransaction } from '../db.js'; export const BUILDING_ROLES = ['viewer', 'reporter', 'inspector', 'building_admin']; // Active roles first, then history.export async function listBuildingAssignments(buildingId) { const { rows } = await query( `SELECT a.id, a.user_id, u.name, u.email, a.role, a.granted_at, a.revoked_at, g.name AS granted_by_name, r.name AS revoked_by_name FROM building_role_assignments a JOIN users u ON u.id = a.user_id LEFT JOIN users g ON g.id = a.granted_by LEFT JOIN users r ON r.id = a.revoked_by WHERE a.building_id = $1 ORDER BY a.revoked_at IS NOT NULL, u.name, a.role, a.id`, [buildingId], ); return rows;} export async function findActiveAssignment(id, buildingId) { const { rows } = await query( 'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND revoked_at IS NULL', [id], ); return rows[0] ?? null;} export async function isMember(userId, organisationId) { const { rowCount } = await query('SELECT 1 FROM memberships WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId]); return rowCount === 1;} export async function grantBuildingRole({ building, userId, role, actorId }) { await withTransaction(async (client) => { await client.query('INSERT INTO building_role_assignments (user_id, building_id, role, granted_by) VALUES ($1, $2, $3, $4)', [userId, building.id, role, actorId]); await client.query( "INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'grant_role', $5)", [actorId, userId, building.organisation_id, building.id, role], ); });} // Returns false if the assignment was already revoked by someone else.export async function revokeBuildingRole({ assignment, building, actorId }) { return withTransaction(async (client) => { const { rowCount } = await client.query( 'UPDATE building_role_assignments SET revoked_at = now(), revoked_by = $2 WHERE id = $1 AND revoked_at IS NULL', [assignment.id, actorId], ); if (rowCount === 0) { return false; } await client.query( "INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'revoke_role', $5)", [actorId, assignment.user_id, building.organisation_id, building.id, assignment.role], ); return true; });}import { query, withTransaction } from '../db.js';
export const BUILDING_ROLES = ['viewer', 'reporter', 'inspector', 'building_admin'];
// Active roles first, then history.
export async function listBuildingAssignments(buildingId) {
const { rows } = await query(
`SELECT a.id, a.user_id, u.name, u.email, a.role, a.granted_at, a.revoked_at,
g.name AS granted_by_name, r.name AS revoked_by_name
FROM building_role_assignments a
JOIN users u ON u.id = a.user_id
LEFT JOIN users g ON g.id = a.granted_by
LEFT JOIN users r ON r.id = a.revoked_by
WHERE a.building_id = $1
ORDER BY a.revoked_at IS NOT NULL, u.name, a.role, a.id`,
[buildingId],
);
return rows;
}
export async function findActiveAssignment(id, buildingId) {
const { rows } = await query(
'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND revoked_at IS NULL',
[id],
);
return rows[0] ?? null;
}
export async function isMember(userId, organisationId) {
const { rowCount } = await query('SELECT 1 FROM memberships WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId]);
return rowCount === 1;
}
export async function grantBuildingRole({ building, userId, role, actorId }) {
await withTransaction(async (client) => {
await client.query('INSERT INTO building_role_assignments (user_id, building_id, role, granted_by) VALUES ($1, $2, $3, $4)', [userId, building.id, role, actorId]);
await client.query(
"INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'grant_role', $5)",
[actorId, userId, building.organisation_id, building.id, role],
);
});
}
// Returns false if the assignment was already revoked by someone else.
export async function revokeBuildingRole({ assignment, building, actorId }) {
return withTransaction(async (client) => {
const { rowCount } = await client.query(
'UPDATE building_role_assignments SET revoked_at = now(), revoked_by = $2 WHERE id = $1 AND revoked_at IS NULL',
[assignment.id, actorId],
);
if (rowCount === 0) {
return false;
}
await client.query(
"INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'revoke_role', $5)",
[actorId, assignment.user_id, building.organisation_id, building.id, assignment.role],
);
return true;
});
}
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) (489.746166ms)
✔ edit issue 101 (25.227333ms)
✔ view issue 103 (building 20) (25.455167ms)
✔ edit issue 103 (reported by dave) (25.525833ms)
✔ report an issue at building 20 (28.5215ms)
✔ view issue 105 (building 30) (19.350333ms)
✔ view issue 106 (building 40, reported by bob) (20.315542ms)
✔ approve inspection 201 (created by dave) (17.533208ms)
✔ approve inspection 202 (created by alice) (23.933334ms)
✔ update organisation 1 (19.538084ms)
✔ change own role at building 10 (6.811667ms)
✔ grant building_admin at building 10 to dave (23.313083ms)
✔ grant viewer at building 10 to dave (22.770083ms)
✔ issues in each user's list come only from the expected buildings (118.877459ms)
✔ the scenario loads exactly as specified (202.316709ms)
✔ only one active assignment per user, building and role (0.8595ms)
✔ a revoked role can be granted again (1.326417ms)
✔ the My access page shows what the server loaded (72.197833ms)
✔ a correct login creates a session and shows the user (268.370208ms)
✔ a wrong password or unknown email gets the same 401 (53.134541ms)
✔ registration validates, creates a user, and logs them in (44.844833ms)
✔ registering an existing email is a field error (30.729291ms)
✔ logout destroys the session (55.656709ms)
✔ allow: a permit matched and nothing forbade it (212.559542ms)
✔ explicit deny: a forbid overrides a matching permit (3.030666ms)
✔ implicit deny: no permit matched (2.20025ms)
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.557875ms)
Show 143 more lines
✔ unknown actions throw instead of deciding (1.344208ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (390.348541ms)
✔ a revoked assignment cannot be revoked again (4.817792ms)
✖ an assignment id from another building is not found here (4.639542ms)
✔ alice cannot revoke her own building_admin role; carol can (13.263958ms)
✔ grants are limited to members of the building's organisation (6.21525ms)
✔ a building can be created inside an organisation (275.755417ms)
✔ a duplicate building name in the same organisation is a field error (5.3915ms)
✔ the same building name is allowed in another organisation (8.828792ms)
✔ a building with issues cannot be deleted (15.47875ms)
✔ an empty building can be deleted (10.976458ms)
✔ an organisation with buildings cannot be deleted, an empty one can (24.788875ms)
✔ a logged-in POST without a token is refused with 403 (276.564708ms)
✔ a token from another session is refused (37.090834ms)
✔ the right token in the form field works (18.535542ms)
✔ every POST form on every page carries the token (57.775042ms)
✔ the dashboard counts match the database (282.232625ms)
✔ only the buildings carol can see appear (5.1795ms)
✔ create a draft, edit it, submit it, approve it (345.500708ms)
✔ invalid transitions are refused with 409 and change nothing (12.030584ms)
✔ only drafts can be edited (5.518792ms)
✔ returning a submitted inspection makes it editable again (8.297917ms)
✔ concurrent approvals: exactly one wins (29.164166ms)
✔ unknown actions are 404 (3.062292ms)
✔ the issues list contains only issues from visible buildings (585.07275ms)
✔ a filter for another tenant's building returns nothing (3.7265ms)
✔ the inspections list is scoped too (10.191334ms)
✔ organisations are listed for their members only (8.142916ms)
✔ the dashboard counts only visible data (8.407667ms)
✔ view issue 101 (building 10) (462.436667ms)
✔ open the edit form for issue 101 (25.316709ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (26.969041ms)
✔ view issue 105 (building 30) and 106 (building 40) (41.208084ms)
✔ report an issue at building 20 (27.902125ms)
✔ a reporter cannot edit their own issue once it is closed (9.976833ms)
✔ only building admins may delete; refusals change nothing (14.144541ms)
✔ the edit form cannot move an issue to another building (3.767708ms)
✔ the list pages 10 at a time and reports the total (302.792833ms)
✔ pages do not overlap (24.021334ms)
✔ filters combine with AND (11.347958ms)
✔ sorting by priority puts critical first when descending (7.303208ms)
✔ unknown sort keys and SQL in the query string are ignored (41.679375ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (357.448625ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (9.517375ms)
✔ dave cannot move issue 101: he may not update it where it is (8.37425ms)
✔ carol moves 101 to building 20, but never to another organisation (11.761792ms)
✔ a forged building id on create is refused and creates nothing (25.311833ms)
✔ GET /issues lists issues from the database (285.9785ms)
✔ GET /issues/101 shows one issue with its building (6.967958ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.711125ms)
✔ POST /issues re-renders the form with errors (5.389625ms)
✔ POST /issues stores the issue and redirects to it (8.390917ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.748834ms)
✔ the stored row has the cleaned values and ignores a client-sent status (5.045791ms)
✔ an issue time in the future is rejected (4.201833ms)
✔ GET /issues/101/edit shows the current values (5.189167ms)
✔ POST /issues/:id/edit changes the status and updated_at (5.048458ms)
✔ POST /issues/:id/delete removes the issue (10.607708ms)
✔ the issues list contains exactly the issues Cedar lets each user view (337.268208ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (20.59075ms)
✔ only organisation admins can open the members page (420.77ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (17.43725ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (13.320541ms)
✔ nobody changes their own membership (4.117875ms)
✔ unknown emails and roles are form errors (9.707ms)
✔ a member cannot add members, even with a well-formed request (3.916417ms)
✔ GET /organisations lists organisations with building counts (274.642625ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (15.0995ms)
✔ POST /organisations validates and creates (14.414375ms)
✔ POST /organisations/:id/edit renames the organisation (11.3295ms)
✔ unknown organisations are 404 (6.393375ms)
✔ every policy is valid against the schema (32.661708ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.552125ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (358.011ms)
✔ anonymous requests are redirected to the login page (223.648292ms)
✔ anonymous writes are refused and change nothing (14.706333ms)
✔ login and register pages stay public (7.187375ms)
✔ login issues a new session id (no session fixation) (34.079459ms)
✔ returnTo only follows local paths (27.52575ms)
✔ new issues and transitions record the logged-in user (81.75475ms)
✔ the session cookie has the attributes we chose (26.596875ms)
✔ organisation 1: view and update (505.23325ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (8.25175ms)
✔ building 10: view, update, delete (60.767583ms)
✔ creating buildings needs org_admin (17.696375ms)
✔ creating an organisation makes the creator its admin (10.284292ms)
✔ inspections: view 201, open the edit form for draft 203 (49.036792ms)
✔ approve inspection 201 (dave's): only building admins (16.479209ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (16.91775ms)
✔ bob gets 404 for every Liffey route, and nothing changes (461.318625ms)
✔ ravi gets 404 for every Liffey route, and nothing changes (97.4095ms)
✔ nora gets 404 for every Liffey route, and nothing changes (91.730042ms)
✖ inside one tenant: alice, a viewer at building 20, cannot change anything there (61.914709ms)
ℹ tests 120
ℹ suites 0
ℹ pass 118
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13425.512542
✖ failing tests:
test at test/building-access.test.js:28:1
✖ an assignment id from another building is not found here (4.639542ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
403 !== 404
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/building-access.test.js:30: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: 403,
expected: 404,
operator: 'strictEqual',
diff: 'simple'
}
test at test/tenant-isolation.test.js:79:1
✖ inside one tenant: alice, a viewer at building 20, cannot change anything there (61.914709ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'POST /buildings/10/access/5/revoke -> 303, expected 404'
+ ]
- []
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/tenant-isolation.test.js:97: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: [ 'POST /buildings/10/access/5/revoke -> 303, expected 404' ],
expected: [],
operator: 'deepStrictEqual',
diff: 'simple'
}
Reveal Answer
Alice posts to /buildings/10/access/5/revoke. The route loads building 10 (she administers it), authorizes ManageBuildingRoles on building 10, then loads assignment 5 without checking which building it belongs to, and revokes Dave's reporter role at building 20. Cedar answered the question it was asked correctly; the route asked about the wrong resource. Two tests fail: the new suite reports POST /buildings/10/access/5/revoke -> 303, expected 404, and the older test from lesson 7.4, "an assignment id from another building is not found here", fails too. (The suite stops at the status check, so it never reaches the fingerprint; had the status been right, the fingerprint would have caught the changed building_role_assignments and permission_changes rows.) Authorization is only as good as the binding between the resource you authorize and the resource you change.
Restore the condition:
'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND revoked_at IS NULL', [id], 'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND building_id = $2 AND revoked_at IS NULL', [id, buildingId],
Show the whole src/models/assignments.js after this change
import { query, withTransaction } from '../db.js'; export const BUILDING_ROLES = ['viewer', 'reporter', 'inspector', 'building_admin']; // Active roles first, then history.export async function listBuildingAssignments(buildingId) { const { rows } = await query( `SELECT a.id, a.user_id, u.name, u.email, a.role, a.granted_at, a.revoked_at, g.name AS granted_by_name, r.name AS revoked_by_name FROM building_role_assignments a JOIN users u ON u.id = a.user_id LEFT JOIN users g ON g.id = a.granted_by LEFT JOIN users r ON r.id = a.revoked_by WHERE a.building_id = $1 ORDER BY a.revoked_at IS NOT NULL, u.name, a.role, a.id`, [buildingId], ); return rows;} export async function findActiveAssignment(id, buildingId) { const { rows } = await query( 'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND building_id = $2 AND revoked_at IS NULL', [id, buildingId], ); return rows[0] ?? null;} export async function isMember(userId, organisationId) { const { rowCount } = await query('SELECT 1 FROM memberships WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId]); return rowCount === 1;} export async function grantBuildingRole({ building, userId, role, actorId }) { await withTransaction(async (client) => { await client.query('INSERT INTO building_role_assignments (user_id, building_id, role, granted_by) VALUES ($1, $2, $3, $4)', [userId, building.id, role, actorId]); await client.query( "INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'grant_role', $5)", [actorId, userId, building.organisation_id, building.id, role], ); });} // Returns false if the assignment was already revoked by someone else.export async function revokeBuildingRole({ assignment, building, actorId }) { return withTransaction(async (client) => { const { rowCount } = await client.query( 'UPDATE building_role_assignments SET revoked_at = now(), revoked_by = $2 WHERE id = $1 AND revoked_at IS NULL', [assignment.id, actorId], ); if (rowCount === 0) { return false; } await client.query( "INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'revoke_role', $5)", [actorId, assignment.user_id, building.organisation_id, building.id, assignment.role], ); return true; });}import { query, withTransaction } from '../db.js';
export const BUILDING_ROLES = ['viewer', 'reporter', 'inspector', 'building_admin'];
// Active roles first, then history.
export async function listBuildingAssignments(buildingId) {
const { rows } = await query(
`SELECT a.id, a.user_id, u.name, u.email, a.role, a.granted_at, a.revoked_at,
g.name AS granted_by_name, r.name AS revoked_by_name
FROM building_role_assignments a
JOIN users u ON u.id = a.user_id
LEFT JOIN users g ON g.id = a.granted_by
LEFT JOIN users r ON r.id = a.revoked_by
WHERE a.building_id = $1
ORDER BY a.revoked_at IS NOT NULL, u.name, a.role, a.id`,
[buildingId],
);
return rows;
}
export async function findActiveAssignment(id, buildingId) {
const { rows } = await query(
'SELECT id, user_id, building_id, role FROM building_role_assignments WHERE id = $1 AND building_id = $2 AND revoked_at IS NULL',
[id, buildingId],
);
return rows[0] ?? null;
}
export async function isMember(userId, organisationId) {
const { rowCount } = await query('SELECT 1 FROM memberships WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId]);
return rowCount === 1;
}
export async function grantBuildingRole({ building, userId, role, actorId }) {
await withTransaction(async (client) => {
await client.query('INSERT INTO building_role_assignments (user_id, building_id, role, granted_by) VALUES ($1, $2, $3, $4)', [userId, building.id, role, actorId]);
await client.query(
"INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'grant_role', $5)",
[actorId, userId, building.organisation_id, building.id, role],
);
});
}
// Returns false if the assignment was already revoked by someone else.
export async function revokeBuildingRole({ assignment, building, actorId }) {
return withTransaction(async (client) => {
const { rowCount } = await client.query(
'UPDATE building_role_assignments SET revoked_at = now(), revoked_by = $2 WHERE id = $1 AND revoked_at IS NULL',
[assignment.id, actorId],
);
if (rowCount === 0) {
return false;
}
await client.query(
"INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, building_id, change, role) VALUES ($1, $2, $3, $4, 'revoke_role', $5)",
[actorId, assignment.user_id, building.organisation_id, building.id, assignment.role],
);
return true;
});
}
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.037375ms)
✔ edit issue 101 (26.788875ms)
✔ view issue 103 (building 20) (28.362083ms)
✔ edit issue 103 (reported by dave) (26.114375ms)
✔ report an issue at building 20 (27.008292ms)
✔ view issue 105 (building 30) (23.835875ms)
✔ view issue 106 (building 40, reported by bob) (17.530292ms)
✔ approve inspection 201 (created by dave) (19.269875ms)
✔ approve inspection 202 (created by alice) (24.590583ms)
✔ update organisation 1 (17.954083ms)
✔ change own role at building 10 (4.7755ms)
✔ grant building_admin at building 10 to dave (25.099375ms)
✔ grant viewer at building 10 to dave (19.574208ms)
✔ issues in each user's list come only from the expected buildings (128.27075ms)
✔ the scenario loads exactly as specified (215.333291ms)
✔ only one active assignment per user, building and role (0.866917ms)
✔ a revoked role can be granted again (0.825917ms)
✔ the My access page shows what the server loaded (73.306583ms)
✔ a correct login creates a session and shows the user (283.17125ms)
✔ a wrong password or unknown email gets the same 401 (52.987167ms)
✔ registration validates, creates a user, and logs them in (38.64575ms)
✔ registering an existing email is a field error (29.913083ms)
✔ logout destroys the session (50.5315ms)
✔ allow: a permit matched and nothing forbade it (216.649875ms)
✔ explicit deny: a forbid overrides a matching permit (2.556083ms)
✔ implicit deny: no permit matched (2.273834ms)
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.054375ms)
Show 101 more lines
✔ unknown actions throw instead of deciding (1.574625ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (403.297083ms)
✔ a revoked assignment cannot be revoked again (4.737208ms)
✔ an assignment id from another building is not found here (6.715667ms)
✔ alice cannot revoke her own building_admin role; carol can (15.965ms)
✔ grants are limited to members of the building's organisation (6.908083ms)
✔ a building can be created inside an organisation (289.007959ms)
✔ a duplicate building name in the same organisation is a field error (5.875ms)
✔ the same building name is allowed in another organisation (8.206417ms)
✔ a building with issues cannot be deleted (15.850959ms)
✔ an empty building can be deleted (10.256459ms)
✔ an organisation with buildings cannot be deleted, an empty one can (24.622875ms)
✔ a logged-in POST without a token is refused with 403 (262.785584ms)
✔ a token from another session is refused (35.870458ms)
✔ the right token in the form field works (18.551667ms)
✔ every POST form on every page carries the token (52.6105ms)
✔ the dashboard counts match the database (274.352625ms)
✔ only the buildings carol can see appear (5.317833ms)
✔ create a draft, edit it, submit it, approve it (347.962833ms)
✔ invalid transitions are refused with 409 and change nothing (12.365125ms)
✔ only drafts can be edited (5.74175ms)
✔ returning a submitted inspection makes it editable again (8.611875ms)
✔ concurrent approvals: exactly one wins (25.643125ms)
✔ unknown actions are 404 (2.929875ms)
✔ the issues list contains only issues from visible buildings (578.712375ms)
✔ a filter for another tenant's building returns nothing (4.125916ms)
✔ the inspections list is scoped too (10.986709ms)
✔ organisations are listed for their members only (8.598ms)
✔ the dashboard counts only visible data (7.468666ms)
✔ view issue 101 (building 10) (483.155083ms)
✔ open the edit form for issue 101 (25.45875ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (25.056ms)
✔ view issue 105 (building 30) and 106 (building 40) (37.757958ms)
✔ report an issue at building 20 (23.559209ms)
✔ a reporter cannot edit their own issue once it is closed (8.6735ms)
✔ only building admins may delete; refusals change nothing (14.796125ms)
✔ the edit form cannot move an issue to another building (3.8325ms)
✔ the list pages 10 at a time and reports the total (305.254208ms)
✔ pages do not overlap (24.416917ms)
✔ filters combine with AND (8.098708ms)
✔ sorting by priority puts critical first when descending (7.806084ms)
✔ unknown sort keys and SQL in the query string are ignored (47.596875ms)
✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (383.731916ms)
✔ dave may update his own issue 103 but is not a reporter at building 10 (7.047416ms)
✔ dave cannot move issue 101: he may not update it where it is (4.979666ms)
✔ carol moves 101 to building 20, but never to another organisation (11.064ms)
✔ a forged building id on create is refused and creates nothing (25.928167ms)
✔ GET /issues lists issues from the database (293.035625ms)
✔ GET /issues/101 shows one issue with its building (7.112084ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.834083ms)
✔ POST /issues re-renders the form with errors (5.401833ms)
✔ POST /issues stores the issue and redirects to it (8.550875ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.345083ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.435375ms)
✔ an issue time in the future is rejected (4.310166ms)
✔ GET /issues/101/edit shows the current values (5.410625ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.99925ms)
✔ POST /issues/:id/delete removes the issue (9.988583ms)
✔ the issues list contains exactly the issues Cedar lets each user view (329.459083ms)
✔ the inspections list contains exactly the inspections Cedar lets each user view (20.942625ms)
✔ only organisation admins can open the members page (412.369625ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (16.149458ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.728959ms)
✔ nobody changes their own membership (4.480209ms)
✔ unknown emails and roles are form errors (9.873459ms)
✔ a member cannot add members, even with a well-formed request (3.851792ms)
✔ GET /organisations lists organisations with building counts (292.214459ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (15.78ms)
✔ POST /organisations validates and creates (15.303458ms)
✔ POST /organisations/:id/edit renames the organisation (10.058042ms)
✔ unknown organisations are 404 (6.036333ms)
✔ every policy is valid against the schema (33.1285ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.257959ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (369.6565ms)
✔ anonymous requests are redirected to the login page (217.250292ms)
✔ anonymous writes are refused and change nothing (11.038666ms)
✔ login and register pages stay public (5.938333ms)
✔ login issues a new session id (no session fixation) (32.373125ms)
✔ returnTo only follows local paths (29.025625ms)
✔ new issues and transitions record the logged-in user (93.648792ms)
✔ the session cookie has the attributes we chose (26.003708ms)
✔ organisation 1: view and update (499.420042ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (10.1095ms)
✔ building 10: view, update, delete (72.075458ms)
✔ creating buildings needs org_admin (21.204208ms)
✔ creating an organisation makes the creator its admin (12.652708ms)
✔ inspections: view 201, open the edit form for draft 203 (51.985292ms)
✔ approve inspection 201 (dave's): only building admins (20.633583ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (13.222792ms)
✔ bob gets 404 for every Liffey route, and nothing changes (446.330875ms)
✔ ravi gets 404 for every Liffey route, and nothing changes (95.030875ms)
✔ nora gets 404 for every Liffey route, and nothing changes (94.160833ms)
✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (68.815416ms)
ℹ tests 120
ℹ suites 0
ℹ pass 120
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13532.187375
git add -A
git commit -m "Tenant isolation suite"
[main ce4cf8b] Tenant isolation suite
1 file changed, 99 insertions(+)
create mode 100644 test/tenant-isolation.test.js
Symptom A route answers 403 where the suite expects 404
The route authorized an action before it checked that the user may view the resource. Every load helper (loadIssue, loadBuilding, ...) must check the view action and answer 404 first.
Symptom The fingerprint differs but every status is right
A route changed data before it decided. Find it by running the attacks one at a time and fingerprinting after each.
Recap and next step
The isolation suite sends every route with foreign identifiers as three outsiders and one insider, and proves that nothing changed. The experiment showed the bug class that Cedar cannot catch by itself: authorizing one resource and acting on another.
Module 8 is complete. Module 9 steps back and asks the hardest question directly: which data in this system is trusted, and what happens when it is not?
Open the checkpoint files for lesson 8.3 (separate page; only files from this lesson and earlier)