Module 7 · RBAC, ABAC, scoped roles and policy management
7.4 Grant and revoke building roles
Build the building access page, authorize every grant and revoke with Cedar and a context, limit who may hand out building_admin, keep history, and watch a revocation take effect on the next request.
Starting point
Organisation admins can add members. Building roles still come only from the seed: nobody can grant Nora a viewer role at building 10, and nobody can revoke Dave's.
Outcome
src/models/assignments.jsviews/buildings/access.ejssrc/authz/policies/forbid-self-role-change.cedarsrc/authz/policies/forbid-building-admin-grants.cedartest/building-access.test.js/buildings/10/accesslists active and revoked roles and lets building admins grant and revoke.- Building admins may hand out
viewer,reporterandinspector; only organisation admins may grant or revokebuilding_admin. - Nobody may change their own building roles.
- Revocation sets
revoked_at, writes the log, and takes effect on the target's very next request. - The access matrix gains its grant rows.
The problem
Delegation needs limits that are easy to state and easy to get wrong:
- If building admins could grant
building_admin, Alice could make anyone an admin of her building, and they could do the same. Rights would spread without the organisation deciding. - If anyone could change their own roles, a single compromised account could promote itself.
- Granting is only meaningful for people inside the organisation. That is a data rule (the target must be a member), not a permission rule.
The first two are Cedar policies. The third is checked by our code before we ask Cedar.
Build it
1. Actions and forbids
Add two building-level actions to the schema, after UpdateBuilding:
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 }, };
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 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], };}// 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 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],
};
}
Both are in AdministerBuilding, so building-admin already permits them for building admins and, through the parent chain, for organisation admins. The limits are forbids:
// Nobody grants or revokes their own building roles.forbid (principal, action == Caretaker::Action::"ManageBuildingRoles", resource)when { context.targetUser == principal };// Only organisation admins may grant or revoke the building_admin role.forbid (principal, action == Caretaker::Action::"ManageBuildingRoles", resource)when { context.role == "building_admin" }unless { resource in principal.adminOrganisations };unless { ... } is the opposite of when: the policy applies only if the condition is false. Read it aloud: forbid managing the building_admin role, unless you administer the building's organisation. Carol is exempt because building 10 is in her organisation; Alice is not.
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
12 policies are valid against the schema
Map the actions to their resource type:
CreateInspection: 'Building', ViewBuildingAccess: 'Building', ManageBuildingRoles: 'Building',
Show the whole src/authz/request.js after this change
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity, inspectionEntity } 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',}; // 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)]; 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 } 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',
};
// 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)];
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],
};
}
2. Data access
Create src/models/assignments.js:
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; });}findActiveAssignment(id, buildingId)requires the assignment to belong to the building in the URL. Without thebuilding_idcondition, an admin of building 10 could post to/buildings/10/access/3/revokeand revoke Bob's assignment 3 at building 30: the authorization check would be about building 10, while the change hit building 30. This is the identifier-substitution problem; Module 8 tests it everywhere.- Revoke is a conditional update, the same pattern as inspection transitions: if two admins revoke at once, one gets
false. - The log row shares the transaction with the change.
3. Routes
Add to src/routes/buildings.js:
import { notFound, forbidden } from '../lib/http.js';import { listBuildingAssignments, findActiveAssignment, isMember, grantBuildingRole, revokeBuildingRole, BUILDING_ROLES } from '../models/assignments.js';import { listMembers } from '../models/members.js';import { findUserById } from '../models/users.js';import { ref } from '../authz/entities.js';
res.redirect(303, `/organisations/${building.organisation_id}`);}); async function renderAccess(res, status, building, { values = {}, error = null } = {}) { res.status(status).render('buildings/access', { title: `Access to ${building.name}`, building, assignments: await listBuildingAssignments(building.id), members: await listMembers(building.organisation_id), roles: BUILDING_ROLES, values, error, });} buildingsRouter.get('/:id/access', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res); await renderAccess(res, 200, building);}); buildingsRouter.post('/:id/access', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res); // Validate the request's claims against our own data before building the context. const userId = parseId(req.body?.user_id); const role = BUILDING_ROLES.includes(req.body?.role) ? req.body.role : null; const target = userId === null ? null : await findUserById(userId); if (!target || !role || !(await isMember(target.id, building.organisation_id))) { return renderAccess(res, 400, building, { values: { user_id: userId, role }, error: 'Choose a member of this organisation and a role.' }); } if (!can(req.user, 'ManageBuildingRoles', building, { targetUser: ref('User', target.id), role })) { return forbidden(res, 'You cannot grant that role to that person.'); } try { await grantBuildingRole({ building, userId: target.id, role, actorId: req.user.id }); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderAccess(res, 400, building, { values: { user_id: userId, role }, error: `${target.name} already has that role here.` }); } throw err; } req.flash('success', `${target.name} is now ${role} at ${building.name}.`); res.redirect(303, `/buildings/${building.id}/access`);}); buildingsRouter.post('/:id/access/:assignmentId/revoke', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res); const assignmentId = parseId(req.params.assignmentId); const assignment = assignmentId === null ? null : await findActiveAssignment(assignmentId, building.id); if (!assignment) return notFound(req, res); // The context describes the assignment as stored, not anything from the form. if (!can(req.user, 'ManageBuildingRoles', building, { targetUser: ref('User', assignment.user_id), role: assignment.role })) { return forbidden(res, 'You cannot revoke that role.'); } const revoked = await revokeBuildingRole({ assignment, building, actorId: req.user.id }); req.flash(revoked ? 'success' : 'error', revoked ? 'Role revoked.' : 'That role was already revoked.'); res.redirect(303, `/buildings/${building.id}/access`);});
Show the whole src/routes/buildings.js after this change
import express from 'express';import { findBuilding, updateBuilding, deleteBuilding } from '../models/buildings.js';import { listRecentIssuesForBuilding } from '../models/issues.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';import { listBuildingAssignments, findActiveAssignment, isMember, grantBuildingRole, revokeBuildingRole, BUILDING_ROLES } from '../models/assignments.js';import { listMembers } from '../models/members.js';import { findUserById } from '../models/users.js';import { ref } from '../authz/entities.js'; export const buildingsRouter = express.Router(); async function loadBuilding(req, res) { const id = parseId(req.params.id); const building = id === null ? null : await findBuilding(id); if (!building || !can(req.user, 'ViewBuilding', building)) { notFound(req, res); return null; } return building;} async function renderBuildingPage(res, status, building, error = null) { const issues = await listRecentIssuesForBuilding(building.id); res.status(status).render('buildings/show', { title: building.name, building, issues, error });} function renderEditForm(res, status, { building, values, errors = {} }) { res.status(status).render('buildings/form', { title: `Edit ${building.name}`, action: `/buildings/${building.id}/edit`, cancelUrl: `/buildings/${building.id}`, building, values, errors, });} buildingsRouter.get('/:id', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; await renderBuildingPage(res, 200, building);}); buildingsRouter.get('/:id/edit', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res); renderEditForm(res, 200, { building, values: building });}); buildingsRouter.post('/:id/edit', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res); const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderEditForm(res, 400, { building, values, errors }); } try { await updateBuilding(building.id, values); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderEditForm(res, 400, { building, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; } res.redirect(303, `/buildings/${building.id}`);}); buildingsRouter.post('/:id/delete', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'DeleteBuilding', building)) return forbidden(res); try { await deleteBuilding(building.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { return renderBuildingPage(res, 409, building, 'This building still has maintenance issues, so it cannot be deleted.'); } throw err; } res.redirect(303, `/organisations/${building.organisation_id}`);}); async function renderAccess(res, status, building, { values = {}, error = null } = {}) { res.status(status).render('buildings/access', { title: `Access to ${building.name}`, building, assignments: await listBuildingAssignments(building.id), members: await listMembers(building.organisation_id), roles: BUILDING_ROLES, values, error, });} buildingsRouter.get('/:id/access', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res); await renderAccess(res, 200, building);}); buildingsRouter.post('/:id/access', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res); // Validate the request's claims against our own data before building the context. const userId = parseId(req.body?.user_id); const role = BUILDING_ROLES.includes(req.body?.role) ? req.body.role : null; const target = userId === null ? null : await findUserById(userId); if (!target || !role || !(await isMember(target.id, building.organisation_id))) { return renderAccess(res, 400, building, { values: { user_id: userId, role }, error: 'Choose a member of this organisation and a role.' }); } if (!can(req.user, 'ManageBuildingRoles', building, { targetUser: ref('User', target.id), role })) { return forbidden(res, 'You cannot grant that role to that person.'); } try { await grantBuildingRole({ building, userId: target.id, role, actorId: req.user.id }); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderAccess(res, 400, building, { values: { user_id: userId, role }, error: `${target.name} already has that role here.` }); } throw err; } req.flash('success', `${target.name} is now ${role} at ${building.name}.`); res.redirect(303, `/buildings/${building.id}/access`);}); buildingsRouter.post('/:id/access/:assignmentId/revoke', async (req, res) => { const building = await loadBuilding(req, res); if (!building) return; if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res); const assignmentId = parseId(req.params.assignmentId); const assignment = assignmentId === null ? null : await findActiveAssignment(assignmentId, building.id); if (!assignment) return notFound(req, res); // The context describes the assignment as stored, not anything from the form. if (!can(req.user, 'ManageBuildingRoles', building, { targetUser: ref('User', assignment.user_id), role: assignment.role })) { return forbidden(res, 'You cannot revoke that role.'); } const revoked = await revokeBuildingRole({ assignment, building, actorId: req.user.id }); req.flash(revoked ? 'success' : 'error', revoked ? 'Role revoked.' : 'That role was already revoked.'); res.redirect(303, `/buildings/${building.id}/access`);});import express from 'express';
import { findBuilding, updateBuilding, deleteBuilding } from '../models/buildings.js';
import { listRecentIssuesForBuilding } from '../models/issues.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { validateName } from '../lib/validation.js';
import { can } from '../authz/rules.js';
import { notFound, forbidden } from '../lib/http.js';
import { listBuildingAssignments, findActiveAssignment, isMember, grantBuildingRole, revokeBuildingRole, BUILDING_ROLES } from '../models/assignments.js';
import { listMembers } from '../models/members.js';
import { findUserById } from '../models/users.js';
import { ref } from '../authz/entities.js';
export const buildingsRouter = express.Router();
async function loadBuilding(req, res) {
const id = parseId(req.params.id);
const building = id === null ? null : await findBuilding(id);
if (!building || !can(req.user, 'ViewBuilding', building)) {
notFound(req, res);
return null;
}
return building;
}
async function renderBuildingPage(res, status, building, error = null) {
const issues = await listRecentIssuesForBuilding(building.id);
res.status(status).render('buildings/show', { title: building.name, building, issues, error });
}
function renderEditForm(res, status, { building, values, errors = {} }) {
res.status(status).render('buildings/form', {
title: `Edit ${building.name}`,
action: `/buildings/${building.id}/edit`,
cancelUrl: `/buildings/${building.id}`,
building,
values,
errors,
});
}
buildingsRouter.get('/:id', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
await renderBuildingPage(res, 200, building);
});
buildingsRouter.get('/:id/edit', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);
renderEditForm(res, 200, { building, values: building });
});
buildingsRouter.post('/:id/edit', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'UpdateBuilding', building)) return forbidden(res);
const { errors, values } = validateName(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderEditForm(res, 400, { building, values, errors });
}
try {
await updateBuilding(building.id, values);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderEditForm(res, 400, { building, values, errors: { name: 'This organisation already has a building with that name.' } });
}
throw err;
}
res.redirect(303, `/buildings/${building.id}`);
});
buildingsRouter.post('/:id/delete', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'DeleteBuilding', building)) return forbidden(res);
try {
await deleteBuilding(building.id);
} catch (err) {
if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {
return renderBuildingPage(res, 409, building, 'This building still has maintenance issues, so it cannot be deleted.');
}
throw err;
}
res.redirect(303, `/organisations/${building.organisation_id}`);
});
async function renderAccess(res, status, building, { values = {}, error = null } = {}) {
res.status(status).render('buildings/access', {
title: `Access to ${building.name}`,
building,
assignments: await listBuildingAssignments(building.id),
members: await listMembers(building.organisation_id),
roles: BUILDING_ROLES,
values,
error,
});
}
buildingsRouter.get('/:id/access', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res);
await renderAccess(res, 200, building);
});
buildingsRouter.post('/:id/access', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res);
// Validate the request's claims against our own data before building the context.
const userId = parseId(req.body?.user_id);
const role = BUILDING_ROLES.includes(req.body?.role) ? req.body.role : null;
const target = userId === null ? null : await findUserById(userId);
if (!target || !role || !(await isMember(target.id, building.organisation_id))) {
return renderAccess(res, 400, building, { values: { user_id: userId, role }, error: 'Choose a member of this organisation and a role.' });
}
if (!can(req.user, 'ManageBuildingRoles', building, { targetUser: ref('User', target.id), role })) {
return forbidden(res, 'You cannot grant that role to that person.');
}
try {
await grantBuildingRole({ building, userId: target.id, role, actorId: req.user.id });
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderAccess(res, 400, building, { values: { user_id: userId, role }, error: `${target.name} already has that role here.` });
}
throw err;
}
req.flash('success', `${target.name} is now ${role} at ${building.name}.`);
res.redirect(303, `/buildings/${building.id}/access`);
});
buildingsRouter.post('/:id/access/:assignmentId/revoke', async (req, res) => {
const building = await loadBuilding(req, res);
if (!building) return;
if (!can(req.user, 'ViewBuildingAccess', building)) return forbidden(res);
const assignmentId = parseId(req.params.assignmentId);
const assignment = assignmentId === null ? null : await findActiveAssignment(assignmentId, building.id);
if (!assignment) return notFound(req, res);
// The context describes the assignment as stored, not anything from the form.
if (!can(req.user, 'ManageBuildingRoles', building, { targetUser: ref('User', assignment.user_id), role: assignment.role })) {
return forbidden(res, 'You cannot revoke that role.');
}
const revoked = await revokeBuildingRole({ assignment, building, actorId: req.user.id });
req.flash(revoked ? 'success' : 'error', revoked ? 'Role revoked.' : 'That role was already revoked.');
res.redirect(303, `/buildings/${building.id}/access`);
});
For a grant, the context comes from the form, validated: a real user (by ID, from our database), a role from our allowlist, and a member of the building's organisation. For a revoke, the context comes entirely from the stored assignment; the form only names which assignment, and that assignment must belong to this building.
4. The page
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/buildings/<%= building.id %>"><%= building.name %></a> / Access</p><h1>Access to <%= building.name %></h1><% if (error) { %><div class="flash flash-error" role="alert"><%= error %></div><% } %> <table class="data"> <thead><tr><th>Person</th><th>Role</th><th>Granted</th><th>Status</th><th></th></tr></thead> <tbody> <% for (const a of assignments) { %> <tr<%- a.revoked_at ? ' class="muted"' : '' %>> <td><%= a.name %><br><span class="muted"><%= a.email %></span></td> <td><span class="badge role-badge"><%= a.role %></span></td> <td><%= formatDate(a.granted_at) %><% if (a.granted_by_name) { %> by <%= a.granted_by_name %><% } %></td> <td><%= a.revoked_at ? `revoked ${formatDate(a.revoked_at)}${a.revoked_by_name ? ` by ${a.revoked_by_name}` : ''}` : 'active' %></td> <td> <% if (!a.revoked_at) { %> <form method="post" action="/buildings/<%= building.id %>/access/<%= a.id %>/revoke" data-confirm="Revoke <%= a.role %> from <%= a.name %>?"><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-small btn-danger">Revoke</button> </form> <% } %> </td> </tr> <% } %> </tbody></table> <h2>Grant a role</h2><form method="post" action="/buildings/<%= building.id %>/access" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field"> <label for="user_id">Member of <%= building.organisation_name %></label> <select id="user_id" name="user_id"> <% for (const m of members) { %><option value="<%= m.id %>"<%= values.user_id === m.id ? ' selected' : '' %>><%= m.name %> (<%= m.email %>)</option><% } %> </select> </div> <div class="field"> <label for="role">Role</label> <select id="role" name="role"> <% for (const r of roles) { %><option value="<%= r %>"<%= values.role === r ? ' selected' : '' %>><%= r %></option><% } %> </select> <p class="hint">Only organisation admins can grant or revoke building_admin.</p> </div> <div class="form-actions"><button type="submit" class="btn btn-primary">Grant role</button></div></form><%- include('../partials/foot') %>Revoke buttons are shown for every active row. The server decides each one; Alice will see a Revoke button next to her own building_admin row, and pressing it gets 403. A template could ask Cedar per row to hide those buttons; we leave them visible here so that you can try the forbids from the browser.
Link to the page from the building:
<% if (can('UpdateBuilding', building)) { %> <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a> <% } %> <% if (can('ViewBuildingAccess', building)) { %> <a class="btn" href="/buildings/<%= building.id %>/access">Access</a> <% } %>
Show the whole views/buildings/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p><div class="page-header"> <h1><%= building.name %></h1> <div class="actions"> <% if (can('UpdateBuilding', building)) { %> <a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a> <% } %> <% if (can('ViewBuildingAccess', building)) { %> <a class="btn" href="/buildings/<%= building.id %>/access">Access</a> <% } %> <% if (can('DeleteBuilding', building)) { %> <form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <button type="submit" class="btn btn-danger">Delete</button> </form> <% } %> </div></div><% if (error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Latest issues</h2><% if (issues.length === 0) { %> <p class="empty">No issues at this building.</p><% } else { %> <table class="data"> <thead><tr><th>Title</th><th>Priority</th><th>Status</th><th>Occurred</th></tr></thead> <tbody> <% for (const issue of issues) { %> <tr> <td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td> <td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td> <td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td> <td><%= formatDate(issue.occurred_at) %></td> </tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %><%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/organisations/<%= building.organisation_id %>"><%= building.organisation_name %></a> / Building #<%= building.id %></p>
<div class="page-header">
<h1><%= building.name %></h1>
<div class="actions">
<% if (can('UpdateBuilding', building)) { %>
<a class="btn" href="/buildings/<%= building.id %>/edit">Edit</a>
<% } %>
<% if (can('ViewBuildingAccess', building)) { %>
<a class="btn" href="/buildings/<%= building.id %>/access">Access</a>
<% } %>
<% if (can('DeleteBuilding', building)) { %>
<form method="post" action="/buildings/<%= building.id %>/delete" data-confirm="Delete <%= building.name %>? This cannot be undone."><input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
<% } %>
</div>
</div>
<% if (error) { %>
<div class="flash flash-error" role="alert"><%= error %></div>
<% } %>
<h2>Latest issues</h2>
<% if (issues.length === 0) { %>
<p class="empty">No issues at this building.</p>
<% } else { %>
<table class="data">
<thead><tr><th>Title</th><th>Priority</th><th>Status</th><th>Occurred</th></tr></thead>
<tbody>
<% for (const issue of issues) { %>
<tr>
<td><a href="/issues/<%= issue.id %>"><%= issue.title %></a></td>
<td><span class="badge sev-<%= issue.priority %>"><%= issue.priority %></span></td>
<td><span class="badge status-<%= issue.status %>"><%= issue.status %></span></td>
<td><%= formatDate(issue.occurred_at) %></td>
</tr>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
5. Grant rows in the access matrix
Add the three grant rows from lesson 5.1 to MATRIX in test/access-matrix.test.js:
{ name: 'update organisation 1', send: (a) => a.get('/organisations/1/edit'), expect: { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } }, { name: 'change own role at building 10', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '1', role: 'inspector' }), expect: { alice: 403 } }, { name: 'grant building_admin at building 10 to dave', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '4', role: 'building_admin' }), expect: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 } }, { name: 'grant viewer at building 10 to dave', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '4', role: 'viewer' }), expect: { bob: 404, dave: 403, nora: 404, ravi: 404, alice: 303 } },];
Show the whole test/access-matrix.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 USERS = ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi'];const agents = {}; before(async () => { await resetDatabase(); for (const name of USERS) agents[name] = await loginAs(name);});after(() => pool.end()); const reportAtBuilding20 = { title: 'Bins left by the back door', building_id: '20', priority: 'medium', occurred_at: '2026-11-22T09:00' }; // The access matrix from lesson 5.1, one row per request.export const MATRIX = [ { name: 'view issue 101 (building 10)', send: (a) => a.get('/issues/101'), expect: { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } }, { name: 'edit issue 101', send: (a) => a.get('/issues/101/edit'), expect: { alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } }, { name: 'view issue 103 (building 20)', send: (a) => a.get('/issues/103'), expect: { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } }, { name: 'edit issue 103 (reported by dave)', send: (a) => a.get('/issues/103/edit'), expect: { alice: 403, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } }, { name: 'report an issue at building 20', send: (a) => a.post('/issues').type('form').send(reportAtBuilding20), expect: { alice: 400, bob: 400, nora: 400, ravi: 400, carol: 303, dave: 303 } }, { name: 'view issue 105 (building 30)', send: (a) => a.get('/issues/105'), expect: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 } }, { name: 'view issue 106 (building 40, reported by bob)', send: (a) => a.get('/issues/106'), expect: { alice: 404, bob: 404, carol: 404, dave: 404, nora: 404, ravi: 404 } }, { name: 'approve inspection 201 (created by dave)', send: (a) => a.post('/inspections/201/approve'), expect: { bob: 404, dave: 403, nora: 404, ravi: 404, alice: 303 } }, { name: 'approve inspection 202 (created by alice)', send: (a) => a.post('/inspections/202/approve'), expect: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 } }, { name: 'update organisation 1', send: (a) => a.get('/organisations/1/edit'), expect: { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } }, { name: 'change own role at building 10', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '1', role: 'inspector' }), expect: { alice: 403 } }, { name: 'grant building_admin at building 10 to dave', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '4', role: 'building_admin' }), expect: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 } }, { name: 'grant viewer at building 10 to dave', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '4', role: 'viewer' }), expect: { bob: 404, dave: 403, nora: 404, ravi: 404, alice: 303 } },]; for (const row of MATRIX) { test(row.name, async () => { const actual = {}; for (const name of Object.keys(row.expect)) { actual[name] = (await row.send(agents[name])).status; } assert.deepEqual(actual, row.expect); });} test('issues in each user\'s list come only from the expected buildings', async () => { const expected = { alice: [10, 20], bob: [30], carol: [10, 20], dave: [10, 20], nora: [], ravi: [] }; for (const [name, buildings] of Object.entries(expected)) { const ids = []; for (let page = 1; page <= 4; page++) { const html = (await agents[name].get(`/issues?page=${page}`)).text; ids.push(...[...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1]))); } const { rows } = await pool.query('SELECT DISTINCT building_id FROM issues WHERE id = ANY($1) ORDER BY building_id', [ids]); assert.deepEqual(rows.map((r) => r.building_id), buildings, name); }});import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { pool } from '../src/db.js';
import { resetDatabase, loginAs } from './helpers.js';
const USERS = ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi'];
const agents = {};
before(async () => {
await resetDatabase();
for (const name of USERS) agents[name] = await loginAs(name);
});
after(() => pool.end());
const reportAtBuilding20 = { title: 'Bins left by the back door', building_id: '20', priority: 'medium', occurred_at: '2026-11-22T09:00' };
// The access matrix from lesson 5.1, one row per request.
export const MATRIX = [
{ name: 'view issue 101 (building 10)', send: (a) => a.get('/issues/101'),
expect: { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } },
{ name: 'edit issue 101', send: (a) => a.get('/issues/101/edit'),
expect: { alice: 200, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } },
{ name: 'view issue 103 (building 20)', send: (a) => a.get('/issues/103'),
expect: { alice: 200, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } },
{ name: 'edit issue 103 (reported by dave)', send: (a) => a.get('/issues/103/edit'),
expect: { alice: 403, bob: 404, carol: 200, dave: 200, nora: 404, ravi: 404 } },
{ name: 'report an issue at building 20', send: (a) => a.post('/issues').type('form').send(reportAtBuilding20),
expect: { alice: 400, bob: 400, nora: 400, ravi: 400, carol: 303, dave: 303 } },
{ name: 'view issue 105 (building 30)', send: (a) => a.get('/issues/105'),
expect: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 } },
{ name: 'view issue 106 (building 40, reported by bob)', send: (a) => a.get('/issues/106'),
expect: { alice: 404, bob: 404, carol: 404, dave: 404, nora: 404, ravi: 404 } },
{ name: 'approve inspection 201 (created by dave)', send: (a) => a.post('/inspections/201/approve'),
expect: { bob: 404, dave: 403, nora: 404, ravi: 404, alice: 303 } },
{ name: 'approve inspection 202 (created by alice)', send: (a) => a.post('/inspections/202/approve'),
expect: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 } },
{ name: 'update organisation 1', send: (a) => a.get('/organisations/1/edit'),
expect: { alice: 403, bob: 404, carol: 200, dave: 403, nora: 404, ravi: 404 } },
{ name: 'change own role at building 10', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '1', role: 'inspector' }),
expect: { alice: 403 } },
{ name: 'grant building_admin at building 10 to dave', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '4', role: 'building_admin' }),
expect: { alice: 403, bob: 404, dave: 403, nora: 404, ravi: 404, carol: 303 } },
{ name: 'grant viewer at building 10 to dave', send: (a) => a.post('/buildings/10/access').type('form').send({ user_id: '4', role: 'viewer' }),
expect: { bob: 404, dave: 403, nora: 404, ravi: 404, alice: 303 } },
];
for (const row of MATRIX) {
test(row.name, async () => {
const actual = {};
for (const name of Object.keys(row.expect)) {
actual[name] = (await row.send(agents[name])).status;
}
assert.deepEqual(actual, row.expect);
});
}
test('issues in each user\'s list come only from the expected buildings', async () => {
const expected = { alice: [10, 20], bob: [30], carol: [10, 20], dave: [10, 20], nora: [], ravi: [] };
for (const [name, buildings] of Object.entries(expected)) {
const ids = [];
for (let page = 1; page <= 4; page++) {
const html = (await agents[name].get(`/issues?page=${page}`)).text;
ids.push(...[...html.matchAll(/<td><a href="\/issues\/(\d+)">/g)].map((m) => Number(m[1])));
}
const { rows } = await pool.query('SELECT DISTINCT building_id FROM issues WHERE id = ANY($1) ORDER BY building_id', [ids]);
assert.deepEqual(rows.map((r) => r.building_id), buildings, name);
}
});
And a test file for revocation:
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()); test('revoking dave\'s inspector role at building 10 takes effect on his next request', async () => { assert.equal((await agents.dave.get('/issues/101')).status, 200); const res = await agents.alice.post('/buildings/10/access/4/revoke'); assert.equal(res.status, 303); assert.equal((await agents.dave.get('/issues/101')).status, 404, 'same session, no new login'); const { rows } = await pool.query('SELECT revoked_by, revoked_at IS NOT NULL AS revoked FROM building_role_assignments WHERE id = 4'); assert.deepEqual(rows, [{ revoked_by: 1, revoked: true }]); const log = await pool.query("SELECT actor_id, target_user_id, building_id, role FROM permission_changes WHERE change = 'revoke_role'"); assert.deepEqual(log.rows, [{ actor_id: 1, target_user_id: 4, building_id: 10, role: 'inspector' }]);}); test('a revoked assignment cannot be revoked again', async () => { assert.equal((await agents.alice.post('/buildings/10/access/4/revoke')).status, 404);}); test('an assignment id from another building is not found here', async () => { // Assignment 3 is bob's building_admin role at building 30. assert.equal((await agents.alice.post('/buildings/10/access/3/revoke')).status, 404); const { rows } = await pool.query('SELECT revoked_at FROM building_role_assignments WHERE id = 3'); assert.equal(rows[0].revoked_at, null);}); test('alice cannot revoke her own building_admin role; carol can', async () => { assert.equal((await agents.alice.post('/buildings/10/access/1/revoke')).status, 403); assert.equal((await agents.carol.post('/buildings/10/access/1/revoke')).status, 303); assert.equal((await agents.alice.get('/issues/101/edit')).status, 404, 'alice lost all access to building 10');}); test('grants are limited to members of the building\'s organisation', async () => { const res = await agents.carol.post('/buildings/20/access').type('form').send({ user_id: '2', role: 'viewer' }); assert.equal(res.status, 400, 'bob is not a member of Liffey');});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) (506.527625ms)
✔ edit issue 101 (90.792125ms)
✔ view issue 103 (building 20) (71.93125ms)
✔ edit issue 103 (reported by dave) (98.886708ms)
✔ report an issue at building 20 (101.262583ms)
✔ view issue 105 (building 30) (42.942292ms)
✔ view issue 106 (building 40, reported by bob) (36.489667ms)
✔ approve inspection 201 (created by dave) (45.141958ms)
✔ approve inspection 202 (created by alice) (58.522583ms)
✔ update organisation 1 (57.512541ms)
✔ change own role at building 10 (17.227584ms)
✔ grant building_admin at building 10 to dave (64.040041ms)
✔ grant viewer at building 10 to dave (49.50825ms)
✔ issues in each user's list come only from the expected buildings (104.330917ms)
✔ the scenario loads exactly as specified (205.220417ms)
✔ only one active assignment per user, building and role (0.818ms)
✔ a revoked role can be granted again (1.604708ms)
✔ the My access page shows what the server loaded (71.796583ms)
✔ a correct login creates a session and shows the user (273.227166ms)
✔ a wrong password or unknown email gets the same 401 (53.018583ms)
✔ registration validates, creates a user, and logs them in (35.450666ms)
✔ registering an existing email is a field error (30.597416ms)
✔ logout destroys the session (54.539375ms)
✔ allow: a permit matched and nothing forbade it (217.145708ms)
✔ explicit deny: a forbid overrides a matching permit (6.353834ms)
✔ implicit deny: no permit matched (6.007875ms)
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 (8.234708ms)
Show 90 more lines
✔ unknown actions throw instead of deciding (1.953875ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (417.773708ms)
✔ a revoked assignment cannot be revoked again (14.112834ms)
✔ an assignment id from another building is not found here (16.03675ms)
✔ alice cannot revoke her own building_admin role; carol can (43.241667ms)
✔ grants are limited to members of the building's organisation (15.616458ms)
✔ a building can be created inside an organisation (313.980958ms)
✔ a duplicate building name in the same organisation is a field error (12.288792ms)
✔ the same building name is allowed in another organisation (15.736125ms)
✔ a building with issues cannot be deleted (43.634917ms)
✔ an empty building can be deleted (30.654625ms)
✔ an organisation with buildings cannot be deleted, an empty one can (66.452916ms)
✔ a logged-in POST without a token is refused with 403 (274.373208ms)
✔ a token from another session is refused (37.613875ms)
✔ the right token in the form field works (39.914208ms)
✔ every POST form on every page carries the token (194.107ms)
✔ the dashboard counts match the database (267.882833ms)
✔ only the buildings carol can see appear (4.827709ms)
✔ create a draft, edit it, submit it, approve it (396.9705ms)
✔ invalid transitions are refused with 409 and change nothing (47.794833ms)
✔ only drafts can be edited (21.542625ms)
✔ returning a submitted inspection makes it editable again (26.410625ms)
✔ concurrent approvals: exactly one wins (76.461417ms)
✔ unknown actions are 404 (3.500625ms)
✔ the issues list contains only issues from visible buildings (532.862417ms)
✔ a filter for another tenant's building returns nothing (4.089833ms)
✔ the inspections list is scoped too (9.600792ms)
✔ organisations are listed for their members only (12.142ms)
✔ the dashboard counts only visible data (7.805375ms)
✔ view issue 101 (building 10) (537.567ms)
✔ open the edit form for issue 101 (96.946541ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (94.075875ms)
✔ view issue 105 (building 30) and 106 (building 40) (103.079833ms)
✔ report an issue at building 20 (111.046959ms)
✔ a reporter cannot edit their own issue once it is closed (43.035417ms)
✔ only building admins may delete; refusals change nothing (43.298458ms)
✔ the edit form cannot move an issue to another building (16.280959ms)
✔ the list pages 10 at a time and reports the total (294.911042ms)
✔ pages do not overlap (16.418958ms)
✔ filters combine with AND (5.827ms)
✔ sorting by priority puts critical first when descending (4.86025ms)
✔ unknown sort keys and SQL in the query string are ignored (28.605083ms)
✔ GET /issues lists issues from the database (262.2515ms)
✔ GET /issues/101 shows one issue with its building (24.867542ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (48.562666ms)
✔ POST /issues re-renders the form with errors (20.562167ms)
✔ POST /issues stores the issue and redirects to it (21.882667ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (18.124875ms)
✔ the stored row has the cleaned values and ignores a client-sent status (12.596916ms)
✔ an issue time in the future is rejected (18.411917ms)
✔ GET /issues/101/edit shows the current values (28.28225ms)
✔ POST /issues/:id/edit changes the status and updated_at (17.927167ms)
✔ POST /issues/:id/delete removes the issue (30.949125ms)
✔ only organisation admins can open the members page (456.853708ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (65.1035ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (41.238209ms)
✔ nobody changes their own membership (15.49225ms)
✔ unknown emails and roles are form errors (27.425542ms)
✔ a member cannot add members, even with a well-formed request (11.341458ms)
✔ GET /organisations lists organisations with building counts (251.182958ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (36.438542ms)
✔ POST /organisations validates and creates (30.500958ms)
✔ POST /organisations/:id/edit renames the organisation (41.880625ms)
✔ unknown organisations are 404 (9.661583ms)
✔ every policy is valid against the schema (32.34ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.316292ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (332.044917ms)
✔ anonymous requests are redirected to the login page (213.187417ms)
✔ anonymous writes are refused and change nothing (10.542541ms)
✔ login and register pages stay public (5.601875ms)
✔ login issues a new session id (no session fixation) (31.358875ms)
✔ returnTo only follows local paths (28.852292ms)
✔ new issues and transitions record the logged-in user (106.765875ms)
✔ the session cookie has the attributes we chose (31.199125ms)
✔ organisation 1: view and update (642.025083ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (39.428916ms)
✔ building 10: view, update, delete (183.758959ms)
✔ creating buildings needs org_admin (47.903583ms)
✔ creating an organisation makes the creator its admin (18.136417ms)
✔ inspections: view 201, open the edit form for draft 203 (112.760625ms)
✔ approve inspection 201 (dave's): only building admins (53.211916ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (101.195042ms)
ℹ tests 109
ℹ suites 0
ℹ pass 109
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13491.475
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

Now revoke a role while its holder is logged in. Dave logs in and views issue 101 (he is an inspector at building 10):
rm -f /tmp/dave.txt
TOKEN=$(curl -s -c /tmp/dave.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/dave.txt -c /tmp/dave.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=dave@example.test -d password=password123
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/dave.txt http://localhost:3000/issues/101
200
Alice revokes assignment 4 (Dave's inspector role at building 10):
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 -X POST http://localhost:3000/buildings/10/access/4/revoke -d _csrf=$TOKEN
303
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/dave.txt http://localhost:3000/issues/101
404
authz user=4 action=ViewIssue resource=Issue::101 decision=deny reasons=-
GET /issues/101 -> 404 (7 ms)
404. The chain: revoked_at set → loadAccess no longer returns the row → inspectorBuildings no longer contains building 10 → building-read does not match → implicit deny. Nothing about Dave's session or cookie changed, and no policy changed either: one row in the database did.
Experiment
building_admin of building 10. Which policy decides, and what does the unless clause check?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/buildings/10/access -d _csrf=$TOKEN -d user_id=4 -d role=building_admin
403
authz user=1 action=ManageBuildingRoles resource=Building::10 decision=deny reasons=forbid-building-admin-grants
POST /buildings/10/access -> 403 (24 ms)
Reveal Answer
forbid-building-admin-grants: the context's role is "building_admin", and the unless condition resource in principal.adminOrganisations is false for Alice (her adminOrganisations set is empty). The building-admin permit also matched, but a forbid wins. For Carol, the unless is true (building 10 is in organisation 1), so the forbid does not apply.
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ view issue 101 (building 10) (540.641458ms)
✔ edit issue 101 (95.164583ms)
✔ view issue 103 (building 20) (83.421375ms)
✔ edit issue 103 (reported by dave) (97.790584ms)
✔ report an issue at building 20 (122.474208ms)
✔ view issue 105 (building 30) (59.774584ms)
✔ view issue 106 (building 40, reported by bob) (42.568958ms)
✔ approve inspection 201 (created by dave) (45.345083ms)
✔ approve inspection 202 (created by alice) (56.226792ms)
✔ update organisation 1 (58.104167ms)
✔ change own role at building 10 (16.521792ms)
✔ grant building_admin at building 10 to dave (71.571667ms)
✔ grant viewer at building 10 to dave (57.680375ms)
✔ issues in each user's list come only from the expected buildings (98.272458ms)
✔ the scenario loads exactly as specified (205.953833ms)
✔ only one active assignment per user, building and role (0.921791ms)
✔ a revoked role can be granted again (1.315917ms)
✔ the My access page shows what the server loaded (71.619792ms)
✔ a correct login creates a session and shows the user (275.190875ms)
✔ a wrong password or unknown email gets the same 401 (52.8495ms)
✔ registration validates, creates a user, and logs them in (40.678125ms)
✔ registering an existing email is a field error (31.030166ms)
✔ logout destroys the session (53.3245ms)
✔ allow: a permit matched and nothing forbade it (217.56525ms)
✔ explicit deny: a forbid overrides a matching permit (6.821792ms)
✔ implicit deny: no permit matched (5.787541ms)
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 (7.277542ms)
Show 90 more lines
✔ unknown actions throw instead of deciding (1.981875ms)
✔ revoking dave's inspector role at building 10 takes effect on his next request (438.271333ms)
✔ a revoked assignment cannot be revoked again (22.652875ms)
✔ an assignment id from another building is not found here (16.928125ms)
✔ alice cannot revoke her own building_admin role; carol can (50.428667ms)
✔ grants are limited to members of the building's organisation (17.751458ms)
✔ a building can be created inside an organisation (315.9ms)
✔ a duplicate building name in the same organisation is a field error (12.62475ms)
✔ the same building name is allowed in another organisation (17.277208ms)
✔ a building with issues cannot be deleted (48.856167ms)
✔ an empty building can be deleted (32.2015ms)
✔ an organisation with buildings cannot be deleted, an empty one can (59.490333ms)
✔ a logged-in POST without a token is refused with 403 (279.608792ms)
✔ a token from another session is refused (38.656084ms)
✔ the right token in the form field works (37.220042ms)
✔ every POST form on every page carries the token (185.823375ms)
✔ the dashboard counts match the database (271.79225ms)
✔ only the buildings carol can see appear (5.412959ms)
✔ create a draft, edit it, submit it, approve it (387.891666ms)
✔ invalid transitions are refused with 409 and change nothing (49.876334ms)
✔ only drafts can be edited (25.0655ms)
✔ returning a submitted inspection makes it editable again (28.65025ms)
✔ concurrent approvals: exactly one wins (75.532542ms)
✔ unknown actions are 404 (2.814ms)
✔ the issues list contains only issues from visible buildings (583.93725ms)
✔ a filter for another tenant's building returns nothing (4.549875ms)
✔ the inspections list is scoped too (11.273125ms)
✔ organisations are listed for their members only (10.165375ms)
✔ the dashboard counts only visible data (9.363458ms)
✔ view issue 101 (building 10) (534.184458ms)
✔ open the edit form for issue 101 (99.4885ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (98.053167ms)
✔ view issue 105 (building 30) and 106 (building 40) (100.26175ms)
✔ report an issue at building 20 (116.105ms)
✔ a reporter cannot edit their own issue once it is closed (38.70575ms)
✔ only building admins may delete; refusals change nothing (48.625459ms)
✔ the edit form cannot move an issue to another building (13.076292ms)
✔ the list pages 10 at a time and reports the total (311.770375ms)
✔ pages do not overlap (19.637291ms)
✔ filters combine with AND (7.105584ms)
✔ sorting by priority puts critical first when descending (5.420792ms)
✔ unknown sort keys and SQL in the query string are ignored (29.889916ms)
✔ GET /issues lists issues from the database (274.8885ms)
✔ GET /issues/101 shows one issue with its building (24.512ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (16.525542ms)
✔ POST /issues re-renders the form with errors (19.577708ms)
✔ POST /issues stores the issue and redirects to it (21.557208ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (16.644333ms)
✔ the stored row has the cleaned values and ignores a client-sent status (7.684167ms)
✔ an issue time in the future is rejected (16.565917ms)
✔ GET /issues/101/edit shows the current values (24.31875ms)
✔ POST /issues/:id/edit changes the status and updated_at (11.625334ms)
✔ POST /issues/:id/delete removes the issue (20.227875ms)
✔ only organisation admins can open the members page (471.7125ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (63.099625ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (49.694583ms)
✔ nobody changes their own membership (17.405917ms)
✔ unknown emails and roles are form errors (29.177125ms)
✔ a member cannot add members, even with a well-formed request (10.343333ms)
✔ GET /organisations lists organisations with building counts (273.222083ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (37.331375ms)
✔ POST /organisations validates and creates (31.893958ms)
✔ POST /organisations/:id/edit renames the organisation (40.881ms)
✔ unknown organisations are 404 (9.928208ms)
✔ every policy is valid against the schema (33.054541ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (9.188042ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (349.443375ms)
✔ anonymous requests are redirected to the login page (221.9955ms)
✔ anonymous writes are refused and change nothing (10.945458ms)
✔ login and register pages stay public (6.577792ms)
✔ login issues a new session id (no session fixation) (32.501166ms)
✔ returnTo only follows local paths (31.263292ms)
✔ new issues and transitions record the logged-in user (103.278333ms)
✔ the session cookie has the attributes we chose (30.49575ms)
✔ organisation 1: view and update (638.732667ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (38.143417ms)
✔ building 10: view, update, delete (153.804833ms)
✔ creating buildings needs org_admin (51.743584ms)
✔ creating an organisation makes the creator its admin (24.621958ms)
✔ inspections: view 201, open the edit form for draft 203 (135.28025ms)
✔ approve inspection 201 (dave's): only building admins (41.574375ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (53.859958ms)
ℹ tests 109
ℹ suites 0
ℹ pass 109
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13798.539375
git add -A
git commit -m "Grant and revoke building roles"
[main 94668d9] Grant and revoke building roles
10 files changed, 238 insertions(+)
create mode 100644 src/authz/policies/forbid-building-admin-grants.cedar
create mode 100644 src/authz/policies/forbid-self-role-change.cedar
create mode 100644 src/models/assignments.js
create mode 100644 test/building-access.test.js
create mode 100644 views/buildings/access.ejs
Symptom A grant returns 400 "Choose a member of this organisation"
The target must be a member of the building's organisation first (lesson 7.3). This is a data rule, checked before Cedar is asked.
Symptom Revoked users keep access
Check that loadAccess still filters revoked_at IS NULL, and that nothing caches req.user.access between requests.
Recap and next step
Granting and revoking are actions like any other, decided by Cedar with a context that our code builds from validated, stored data. Two forbids bound delegation: no self-changes, and building_admin only from organisation admins. History is kept by revoking instead of deleting, with a log row in the same transaction. A revocation changed one row, and the next request was denied, with no change to the session or the policies.
Module 7 is complete. One problem remains from Module 5: lists. Cedar answers one question per resource, while /issues still filters with a hand-written SQL condition. Module 8 makes the two agree, and proves it.
Open the checkpoint files for lesson 7.4 (separate page; only files from this lesson and earlier)