Module 7 · RBAC, ABAC, scoped roles and policy management
7.3 Members and controlled onboarding
Let organisation admins add registered users as members or admins, authorize the change with a Cedar context, forbid changes to your own membership, and record every change in an audit log.
Starting point
Users can register, but nothing in the app can give them access: memberships only come from the seed. Nora registered and stays outside every organisation.
Outcome
migrations/006_create_permission_changes.sqlsrc/models/members.jsviews/organisations/members.ejssrc/authz/policies/forbid-self-membership-change.cedartest/members.test.js- Organisation admins open Members, add a registered user by email as
memberororg_admin, or change a member's role. - Cedar decides with a context: who the change is for, and which role.
- Nobody can change their own membership, whatever other policies say.
- Every change is written to
permission_changes, in the same transaction as the change itself.
The problem
Registration is open; access is not. That combination is called controlled onboarding: anyone can create an account, and an administrator decides what it can reach. To make it work, an administrator needs a way to grant membership, and granting is itself an action that must be authorized.
Granting access has a feature our other actions lack: the decision depends on more than the resource. "May Carol change a membership in organisation 1?" is incomplete. "May Carol make Nora a member of organisation 1?" can be answered. The extra facts (target user, role) are not attributes of the organisation; they describe this request. Cedar's place for them is the context.
Build it
1. An audit log for permission changes
-- Every change to who may do what. Written in the same transaction as the change.CREATE TABLE permission_changes ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, actor_id integer REFERENCES users (id) ON DELETE SET NULL, target_user_id integer REFERENCES users (id) ON DELETE SET NULL, organisation_id integer NOT NULL REFERENCES organisations (id) ON DELETE CASCADE, building_id integer REFERENCES buildings (id) ON DELETE CASCADE, change text NOT NULL CHECK (change IN ('add_member', 'change_member_role', 'grant_role', 'revoke_role')), role text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()); CREATE INDEX permission_changes_organisation_id_idx ON permission_changes (organisation_id);npm run db:migrate
> caretaker@1.0.0 db:migrate
> node --env-file=.env scripts/migrate.js
applied 006_create_permission_changes.sql
migrations are up to date
The log is append-only by convention: the app inserts rows and never updates or deletes them. Lesson 9.3 shows how database permissions can enforce that.
2. Two new actions, one with a context
Add them to the schema, inside the Caretaker namespace, after DeleteBuilding:
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 }, };
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 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 UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] };
action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo {
principal: [User],
resource: [Inspection],
};
}
context: { targetUser: User, role: String } declares the context's shape. A request for ManageMembers without a targetUser, or with a role that is not a string, is now a failure. Because both actions are in AdministerOrganisation, the existing org-admin policy already permits them for organisation admins. No new permit is needed.
The exception needs a forbid:
// Nobody changes their own membership: no self-promotion, and no admin// removing their own rights by accident.forbid (principal, action == Caretaker::Action::"ManageMembers", resource)when { context.targetUser == principal };npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
10 policies are valid against the schema
3. Pass a context through can()
Extend the three layers. The resource types:
CreateBuilding: 'Organisation', ViewMembers: 'Organisation', ManageMembers: 'Organisation',
export function buildAuthorizationCall(user, action, row) {export function buildAuthorizationCall(user, action, row, context = {}) {
resource: resource.uid, context: {}, context,
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', 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',
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],
};
}
export function authorize(user, action, row) { const call = buildAuthorizationCall(user, action, row);export function authorize(user, action, row, context = {}) { const call = buildAuthorizationCall(user, action, row, context);
Show the whole src/authz/authorize.js after this change
import { config } from '../config.js';import { buildAuthorizationCall } from './request.js';import { evaluate } from './cedar.js'; // Builds the Cedar call for this user, action and database row, evaluates it, and logs.export function authorize(user, action, row, context = {}) { const call = buildAuthorizationCall(user, action, row, context); const result = evaluate(call); const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`; if (result.decision === 'failure' || result.errors.length > 0) { console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors }); } if (config.authzLog) { console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`); } return result;}import { config } from '../config.js';
import { buildAuthorizationCall } from './request.js';
import { evaluate } from './cedar.js';
// Builds the Cedar call for this user, action and database row, evaluates it, and logs.
export function authorize(user, action, row, context = {}) {
const call = buildAuthorizationCall(user, action, row, context);
const result = evaluate(call);
const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`;
if (result.decision === 'failure' || result.errors.length > 0) {
console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors });
}
if (config.authzLog) {
console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`);
}
return result;
}
export function can(user, action, resource) { return authorize(user, action, resource).allowed;export function can(user, action, resource, context = {}) { return authorize(user, action, resource, context).allowed;}
Show the whole src/authz/rules.js after this change
// Authorization: every route and template asks can(user, action, resource).// Since Module 6 every answer comes from the Cedar policies in src/authz/policies.import { authorize } from './authorize.js'; export function can(user, action, resource, context = {}) { return authorize(user, action, resource, context).allowed;}// Authorization: every route and template asks can(user, action, resource).
// Since Module 6 every answer comes from the Cedar policies in src/authz/policies.
import { authorize } from './authorize.js';
export function can(user, action, resource, context = {}) {
return authorize(user, action, resource, context).allowed;
}
4. Data access
Add a lookup by email to src/models/users.js:
export async function findUserByEmail(email) { const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE email = $1`, [normaliseEmail(email)]); return rows[0] ?? null;} export async function findUserById(id) {
Show the whole src/models/users.js after this change
import argon2 from 'argon2';import { query } from '../db.js'; const PUBLIC_COLUMNS = 'id, email, name, created_at'; export function normaliseEmail(email) { return typeof email === 'string' ? email.trim().toLowerCase() : '';} export async function hashPassword(password) { return argon2.hash(password, { type: argon2.argon2id });} export async function createUser({ email, name, password }) { const passwordHash = await hashPassword(password); const { rows } = await query( `INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING ${PUBLIC_COLUMNS}`, [normaliseEmail(email), name, passwordHash], ); return rows[0];} export async function findUserByEmail(email) { const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE email = $1`, [normaliseEmail(email)]); return rows[0] ?? null;} export async function findUserById(id) { const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE id = $1`, [id]); return rows[0] ?? null;} // A real hash of a random string. Used so that "unknown email" takes as long as "wrong password".const DUMMY_HASH = await hashPassword(`dummy-${Math.random()}`); // Returns the user (without the hash) if the email and password match, otherwise null.export async function verifyCredentials(email, password) { const { rows } = await query('SELECT id, password_hash FROM users WHERE email = $1', [normaliseEmail(email)]); const row = rows[0]; const ok = await argon2.verify(row ? row.password_hash : DUMMY_HASH, typeof password === 'string' ? password : ''); return row && ok ? findUserById(row.id) : null;}import argon2 from 'argon2';
import { query } from '../db.js';
const PUBLIC_COLUMNS = 'id, email, name, created_at';
export function normaliseEmail(email) {
return typeof email === 'string' ? email.trim().toLowerCase() : '';
}
export async function hashPassword(password) {
return argon2.hash(password, { type: argon2.argon2id });
}
export async function createUser({ email, name, password }) {
const passwordHash = await hashPassword(password);
const { rows } = await query(
`INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING ${PUBLIC_COLUMNS}`,
[normaliseEmail(email), name, passwordHash],
);
return rows[0];
}
export async function findUserByEmail(email) {
const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE email = $1`, [normaliseEmail(email)]);
return rows[0] ?? null;
}
export async function findUserById(id) {
const { rows } = await query(`SELECT ${PUBLIC_COLUMNS} FROM users WHERE id = $1`, [id]);
return rows[0] ?? null;
}
// A real hash of a random string. Used so that "unknown email" takes as long as "wrong password".
const DUMMY_HASH = await hashPassword(`dummy-${Math.random()}`);
// Returns the user (without the hash) if the email and password match, otherwise null.
export async function verifyCredentials(email, password) {
const { rows } = await query('SELECT id, password_hash FROM users WHERE email = $1', [normaliseEmail(email)]);
const row = rows[0];
const ok = await argon2.verify(row ? row.password_hash : DUMMY_HASH, typeof password === 'string' ? password : '');
return row && ok ? findUserById(row.id) : null;
}
Create src/models/members.js:
import { query, withTransaction } from '../db.js'; export const MEMBER_ROLES = ['member', 'org_admin']; export async function listMembers(organisationId) { const { rows } = await query( `SELECT u.id, u.name, u.email, m.role FROM memberships m JOIN users u ON u.id = m.user_id WHERE m.organisation_id = $1 ORDER BY u.name`, [organisationId], ); return rows;} // Adds a membership or changes its role, and records the change, in one transaction.// Returns 'add_member' or 'change_member_role'.export async function setMembership({ organisationId, userId, role, actorId }) { return withTransaction(async (client) => { const existing = await client.query( 'SELECT role FROM memberships WHERE user_id = $1 AND organisation_id = $2 FOR UPDATE', [userId, organisationId], ); let change; if (existing.rowCount === 0) { await client.query('INSERT INTO memberships (user_id, organisation_id, role) VALUES ($1, $2, $3)', [userId, organisationId, role]); change = 'add_member'; } else { await client.query('UPDATE memberships SET role = $3 WHERE user_id = $1 AND organisation_id = $2', [userId, organisationId, role]); change = 'change_member_role'; } await client.query( 'INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, change, role) VALUES ($1, $2, $3, $4, $5)', [actorId, userId, organisationId, change, role], ); return change; });} export async function listPermissionChanges(organisationId, limit = 20) { const { rows } = await query( `SELECT pc.change, pc.role, pc.created_at, actor.name AS actor_name, target.name AS target_name, s.name AS building_name FROM permission_changes pc LEFT JOIN users actor ON actor.id = pc.actor_id LEFT JOIN users target ON target.id = pc.target_user_id LEFT JOIN buildings s ON s.id = pc.building_id WHERE pc.organisation_id = $1 ORDER BY pc.created_at DESC, pc.id DESC LIMIT $2`, [organisationId, limit], ); return rows;}SELECT ... FOR UPDATE locks the membership row, if it exists, until the transaction ends, so two administrators changing the same membership at once are serialized. If neither finds a row and both insert, the primary key rejects the second insert; the route turns that into a message.
5. Routes
Add the imports and two routes to src/routes/organisations.js:
import { notFound, forbidden } from '../lib/http.js';import { listMembers, setMembership, listPermissionChanges, MEMBER_ROLES } from '../models/members.js';import { findUserByEmail, normaliseEmail } from '../models/users.js';import { ref } from '../authz/entities.js';
async function renderMembers(res, status, organisation, { values = {}, error = null } = {}) { res.status(status).render('organisations/members', { title: `Members of ${organisation.name}`, organisation, members: await listMembers(organisation.id), changes: await listPermissionChanges(organisation.id), roles: MEMBER_ROLES, values, error, });} organisationsRouter.get('/:id/members', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res); await renderMembers(res, 200, organisation);}); organisationsRouter.post('/:id/members', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res); // The context comes from the form, so validate it and load the real user first. const email = normaliseEmail(req.body?.email); const role = MEMBER_ROLES.includes(req.body?.role) ? req.body.role : null; const target = email ? await findUserByEmail(email) : null; if (!target || !role) { const error = !target ? 'No account uses that email. Ask the person to register first.' : 'Choose a role.'; return renderMembers(res, 400, organisation, { values: { email, role }, error }); } if (!can(req.user, 'ManageMembers', organisation, { targetUser: ref('User', target.id), role })) { return forbidden(res, 'You cannot make this membership change.'); } try { const change = await setMembership({ organisationId: organisation.id, userId: target.id, role, actorId: req.user.id }); req.flash('success', change === 'add_member' ? `${target.name} is now a ${role} of ${organisation.name}.` : `${target.name} is now ${role}.`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderMembers(res, 409, organisation, { values: { email, role }, error: 'Someone else changed this membership at the same time. Try again.' }); } throw err; } res.redirect(303, `/organisations/${organisation.id}/members`);}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) {
Show the whole src/routes/organisations.js after this change
import express from 'express';import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { validateName } from '../lib/validation.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';import { listMembers, setMembership, listPermissionChanges, MEMBER_ROLES } from '../models/members.js';import { findUserByEmail, normaliseEmail } from '../models/users.js';import { ref } from '../authz/entities.js'; export const organisationsRouter = express.Router(); const validateOrganisation = validateName; function renderForm(res, status, { organisation = null, values = {}, errors = {} }) { res.status(status).render('organisations/form', { title: organisation ? `Edit ${organisation.name}` : 'New organisation', action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations', organisation, values, errors, });} // Loads the organisation named by :id, or answers 404. Returns null when it answered.async function loadOrganisation(req, res) { const id = parseId(req.params.id); const organisation = id === null ? null : await findOrganisation(id); if (!organisation || !can(req.user, 'ViewOrganisation', organisation)) { notFound(req, res); return null; } return organisation;} organisationsRouter.get('/', async (req, res) => { res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });}); organisationsRouter.get('/new', (req, res) => { renderForm(res, 200, {});}); organisationsRouter.post('/', async (req, res) => { const { errors, values } = validateOrganisation(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderForm(res, 400, { values, errors }); } const created = await createOrganisation(values, req.user.id); res.redirect(303, `/organisations/${created.id}`);}); organisationsRouter.get('/:id', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; const buildings = await listBuildingsForOrganisation(organisation.id); res.render('organisations/show', { title: organisation.name, organisation, buildings });}); organisationsRouter.get('/:id/edit', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res); renderForm(res, 200, { organisation, values: organisation });}); organisationsRouter.post('/:id/edit', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res); const { errors, values } = validateOrganisation(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderForm(res, 400, { organisation, values, errors }); } await updateOrganisation(organisation.id, values); res.redirect(303, `/organisations/${organisation.id}`);}); organisationsRouter.post('/:id/delete', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res); try { await deleteOrganisation(organisation.id); } catch (err) { if (err.code === PG_ERRORS.RESTRICT_VIOLATION) { const buildings = await listBuildingsForOrganisation(organisation.id); return res.status(409).render('organisations/show', { title: organisation.name, organisation, buildings, error: 'This organisation still has buildings. Delete its buildings first.', }); } throw err; } res.redirect(303, '/organisations');}); async function renderMembers(res, status, organisation, { values = {}, error = null } = {}) { res.status(status).render('organisations/members', { title: `Members of ${organisation.name}`, organisation, members: await listMembers(organisation.id), changes: await listPermissionChanges(organisation.id), roles: MEMBER_ROLES, values, error, });} organisationsRouter.get('/:id/members', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res); await renderMembers(res, 200, organisation);}); organisationsRouter.post('/:id/members', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res); // The context comes from the form, so validate it and load the real user first. const email = normaliseEmail(req.body?.email); const role = MEMBER_ROLES.includes(req.body?.role) ? req.body.role : null; const target = email ? await findUserByEmail(email) : null; if (!target || !role) { const error = !target ? 'No account uses that email. Ask the person to register first.' : 'Choose a role.'; return renderMembers(res, 400, organisation, { values: { email, role }, error }); } if (!can(req.user, 'ManageMembers', organisation, { targetUser: ref('User', target.id), role })) { return forbidden(res, 'You cannot make this membership change.'); } try { const change = await setMembership({ organisationId: organisation.id, userId: target.id, role, actorId: req.user.id }); req.flash('success', change === 'add_member' ? `${target.name} is now a ${role} of ${organisation.name}.` : `${target.name} is now ${role}.`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderMembers(res, 409, organisation, { values: { email, role }, error: 'Someone else changed this membership at the same time. Try again.' }); } throw err; } res.redirect(303, `/organisations/${organisation.id}/members`);}); function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) { res.status(status).render('buildings/form', { title: `New building in ${organisation.name}`, action: `/organisations/${organisation.id}/buildings`, cancelUrl: `/organisations/${organisation.id}`, building: null, values, errors, });} organisationsRouter.get('/:id/buildings/new', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res); renderBuildingForm(res, 200, { organisation });}); organisationsRouter.post('/:id/buildings', async (req, res) => { const organisation = await loadOrganisation(req, res); if (!organisation) return; if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res); const { errors, values } = validateName(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderBuildingForm(res, 400, { organisation, values, errors }); } try { const building = await createBuilding({ organisation_id: organisation.id, name: values.name }); res.redirect(303, `/buildings/${building.id}`); } catch (err) { if (err.code === PG_ERRORS.UNIQUE_VIOLATION) { return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } }); } throw err; }});import express from 'express';
import { listOrganisations, findOrganisation, createOrganisation, updateOrganisation, deleteOrganisation } from '../models/organisations.js';
import { listBuildingsForOrganisation, createBuilding } from '../models/buildings.js';
import { PG_ERRORS } from '../db.js';
import { parseId } from '../lib/ids.js';
import { validateName } from '../lib/validation.js';
import { can } from '../authz/rules.js';
import { notFound, forbidden } from '../lib/http.js';
import { listMembers, setMembership, listPermissionChanges, MEMBER_ROLES } from '../models/members.js';
import { findUserByEmail, normaliseEmail } from '../models/users.js';
import { ref } from '../authz/entities.js';
export const organisationsRouter = express.Router();
const validateOrganisation = validateName;
function renderForm(res, status, { organisation = null, values = {}, errors = {} }) {
res.status(status).render('organisations/form', {
title: organisation ? `Edit ${organisation.name}` : 'New organisation',
action: organisation ? `/organisations/${organisation.id}/edit` : '/organisations',
organisation,
values,
errors,
});
}
// Loads the organisation named by :id, or answers 404. Returns null when it answered.
async function loadOrganisation(req, res) {
const id = parseId(req.params.id);
const organisation = id === null ? null : await findOrganisation(id);
if (!organisation || !can(req.user, 'ViewOrganisation', organisation)) {
notFound(req, res);
return null;
}
return organisation;
}
organisationsRouter.get('/', async (req, res) => {
res.render('organisations/index', { title: 'Organisations', organisations: await listOrganisations(req.user.id) });
});
organisationsRouter.get('/new', (req, res) => {
renderForm(res, 200, {});
});
organisationsRouter.post('/', async (req, res) => {
const { errors, values } = validateOrganisation(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderForm(res, 400, { values, errors });
}
const created = await createOrganisation(values, req.user.id);
res.redirect(303, `/organisations/${created.id}`);
});
organisationsRouter.get('/:id', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
const buildings = await listBuildingsForOrganisation(organisation.id);
res.render('organisations/show', { title: organisation.name, organisation, buildings });
});
organisationsRouter.get('/:id/edit', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
renderForm(res, 200, { organisation, values: organisation });
});
organisationsRouter.post('/:id/edit', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'UpdateOrganisation', organisation)) return forbidden(res);
const { errors, values } = validateOrganisation(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderForm(res, 400, { organisation, values, errors });
}
await updateOrganisation(organisation.id, values);
res.redirect(303, `/organisations/${organisation.id}`);
});
organisationsRouter.post('/:id/delete', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'DeleteOrganisation', organisation)) return forbidden(res);
try {
await deleteOrganisation(organisation.id);
} catch (err) {
if (err.code === PG_ERRORS.RESTRICT_VIOLATION) {
const buildings = await listBuildingsForOrganisation(organisation.id);
return res.status(409).render('organisations/show', {
title: organisation.name,
organisation,
buildings,
error: 'This organisation still has buildings. Delete its buildings first.',
});
}
throw err;
}
res.redirect(303, '/organisations');
});
async function renderMembers(res, status, organisation, { values = {}, error = null } = {}) {
res.status(status).render('organisations/members', {
title: `Members of ${organisation.name}`,
organisation,
members: await listMembers(organisation.id),
changes: await listPermissionChanges(organisation.id),
roles: MEMBER_ROLES,
values,
error,
});
}
organisationsRouter.get('/:id/members', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res);
await renderMembers(res, 200, organisation);
});
organisationsRouter.post('/:id/members', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'ViewMembers', organisation)) return forbidden(res);
// The context comes from the form, so validate it and load the real user first.
const email = normaliseEmail(req.body?.email);
const role = MEMBER_ROLES.includes(req.body?.role) ? req.body.role : null;
const target = email ? await findUserByEmail(email) : null;
if (!target || !role) {
const error = !target ? 'No account uses that email. Ask the person to register first.' : 'Choose a role.';
return renderMembers(res, 400, organisation, { values: { email, role }, error });
}
if (!can(req.user, 'ManageMembers', organisation, { targetUser: ref('User', target.id), role })) {
return forbidden(res, 'You cannot make this membership change.');
}
try {
const change = await setMembership({ organisationId: organisation.id, userId: target.id, role, actorId: req.user.id });
req.flash('success', change === 'add_member' ? `${target.name} is now a ${role} of ${organisation.name}.` : `${target.name} is now ${role}.`);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderMembers(res, 409, organisation, { values: { email, role }, error: 'Someone else changed this membership at the same time. Try again.' });
}
throw err;
}
res.redirect(303, `/organisations/${organisation.id}/members`);
});
function renderBuildingForm(res, status, { organisation, values = {}, errors = {} }) {
res.status(status).render('buildings/form', {
title: `New building in ${organisation.name}`,
action: `/organisations/${organisation.id}/buildings`,
cancelUrl: `/organisations/${organisation.id}`,
building: null,
values,
errors,
});
}
organisationsRouter.get('/:id/buildings/new', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
renderBuildingForm(res, 200, { organisation });
});
organisationsRouter.post('/:id/buildings', async (req, res) => {
const organisation = await loadOrganisation(req, res);
if (!organisation) return;
if (!can(req.user, 'CreateBuilding', organisation)) return forbidden(res);
const { errors, values } = validateName(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderBuildingForm(res, 400, { organisation, values, errors });
}
try {
const building = await createBuilding({ organisation_id: organisation.id, name: values.name });
res.redirect(303, `/buildings/${building.id}`);
} catch (err) {
if (err.code === PG_ERRORS.UNIQUE_VIOLATION) {
return renderBuildingForm(res, 400, { organisation, values, errors: { name: 'This organisation already has a building with that name.' } });
}
throw err;
}
});
Look at the order in POST /:id/members:
- Load and view. The organisation exists and the user may see its members.
- Validate the request's claims. The email must belong to a real account, loaded from our database; the role must be in our allowlist. The context is built only from those checked values:
targetUseris a reference to a user that exists, not an ID copied from the form. - Authorize with the context. Cedar sees principal, action, resource and who and what the change is about.
- Act and log in one transaction.
The context is input from the request, and that is fine because we validated it and because the policies only use it to describe the request ("which user is this change for"), never as a statement of the requester's own rights.
6. The page
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations/<%= organisation.id %>"><%= organisation.name %></a> / Members</p><h1>Members of <%= organisation.name %></h1><% if (error) { %><div class="flash flash-error" role="alert"><%= error %></div><% } %> <table class="data"> <thead><tr><th>Name</th><th>Email</th><th>Role</th></tr></thead> <tbody> <% for (const m of members) { %> <tr><td><%= m.name %></td><td><%= m.email %></td><td><span class="badge role-badge"><%= m.role %></span></td></tr> <% } %> </tbody></table> <h2>Add a member or change a role</h2><form method="post" action="/organisations/<%= organisation.id %>/members" class="form" novalidate><input type="hidden" name="_csrf" value="<%= csrfToken %>"> <div class="field"> <label for="email">Email of a registered user</label> <input id="email" name="email" type="email" value="<%= values.email ?? '' %>"> </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> </div> <div class="form-actions"><button type="submit" class="btn btn-primary">Save membership</button></div></form> <h2>Recent permission changes</h2><% if (changes.length === 0) { %> <p class="muted">No changes recorded yet.</p><% } else { %> <table class="data"> <thead><tr><th>When (UTC)</th><th>By</th><th>Change</th><th>For</th><th>Role</th><th>Building</th></tr></thead> <tbody> <% for (const c of changes) { %> <tr><td><%= formatDate(c.created_at) %></td><td><%= c.actor_name ?? 'unknown' %></td><td><%= c.change %></td><td><%= c.target_name ?? 'unknown' %></td><td><%= c.role %></td><td><%= c.building_name ?? '' %></td></tr> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %>Link to it from the organisation page:
<% if (can('ViewMembers', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/members">Members</a> <% } %> <% if (can('CreateBuilding', organisation)) { %>
Show the whole views/organisations/show.ejs after this change
<%- include('../partials/head') %><p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p><div class="page-header"> <h1><%= organisation.name %></h1> <div class="actions"> <% if (can('UpdateOrganisation', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a> <% } %> <% if (can('ViewMembers', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/members">Members</a> <% } %> <% if (can('CreateBuilding', organisation)) { %> <a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a> <% } %> <% if (can('DeleteOrganisation', organisation)) { %> <form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.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 (typeof error !== 'undefined' && error) { %> <div class="flash flash-error" role="alert"><%= error %></div><% } %> <h2>Buildings</h2><% if (buildings.length === 0) { %> <p class="empty">This organisation has no buildings yet.</p><% } else { %> <table class="data"> <thead><tr><th>Building</th><th>Issues</th></tr></thead> <tbody> <% for (const building of buildings) { %> <% const buildingRef = { id: building.id, organisation_id: organisation.id }; %> <% if (can('ViewBuilding', buildingRef)) { %> <tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr> <% } else { %> <tr><td><%= building.name %></td><td class="muted">no access</td></tr> <% } %> <% } %> </tbody> </table><% } %><%- include('../partials/foot') %><%- include('../partials/head') %>
<p class="breadcrumbs"><a href="/organisations">Organisations</a> / #<%= organisation.id %></p>
<div class="page-header">
<h1><%= organisation.name %></h1>
<div class="actions">
<% if (can('UpdateOrganisation', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/edit">Edit</a>
<% } %>
<% if (can('ViewMembers', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/members">Members</a>
<% } %>
<% if (can('CreateBuilding', organisation)) { %>
<a class="btn" href="/organisations/<%= organisation.id %>/buildings/new">Add building</a>
<% } %>
<% if (can('DeleteOrganisation', organisation)) { %>
<form method="post" action="/organisations/<%= organisation.id %>/delete" data-confirm="Delete <%= organisation.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 (typeof error !== 'undefined' && error) { %>
<div class="flash flash-error" role="alert"><%= error %></div>
<% } %>
<h2>Buildings</h2>
<% if (buildings.length === 0) { %>
<p class="empty">This organisation has no buildings yet.</p>
<% } else { %>
<table class="data">
<thead><tr><th>Building</th><th>Issues</th></tr></thead>
<tbody>
<% for (const building of buildings) { %>
<% const buildingRef = { id: building.id, organisation_id: organisation.id }; %>
<% if (can('ViewBuilding', buildingRef)) { %>
<tr><td><a href="/buildings/<%= building.id %>"><%= building.name %></a></td><td><%= building.issue_count %></td></tr>
<% } else { %>
<tr><td><%= building.name %></td><td class="muted">no access</td></tr>
<% } %>
<% } %>
</tbody>
</table>
<% } %>
<%- include('../partials/foot') %>
7. Tests
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { resetDatabase, loginAs } from './helpers.js'; const agents = {};before(async () => { await resetDatabase(); for (const name of ['alice', 'bob', 'carol', 'dave', 'nora']) agents[name] = await loginAs(name);});after(() => pool.end()); test('only organisation admins can open the members page', async () => { const statuses = {}; for (const name of ['alice', 'bob', 'carol', 'nora']) statuses[name] = (await agents[name].get('/organisations/1/members')).status; assert.deepEqual(statuses, { alice: 403, bob: 404, carol: 200, nora: 404 });}); test('controlled onboarding: carol adds nora; nora sees the organisation but no building', async () => { const res = await agents.carol.post('/organisations/1/members').type('form').send({ email: 'NORA@example.test', role: 'member' }); assert.equal(res.status, 303); assert.equal((await agents.nora.get('/organisations/1')).status, 200); assert.equal((await agents.nora.get('/buildings/10')).status, 404); const { rows } = await pool.query("SELECT actor_id, target_user_id, change, role FROM permission_changes WHERE target_user_id = 5"); assert.deepEqual(rows, [{ actor_id: 3, target_user_id: 5, change: 'add_member', role: 'member' }]);}); test('promoting dave to org_admin gives him the organisation\'s admin rights on his next request', async () => { assert.equal((await agents.dave.get('/organisations/1/edit')).status, 403); await agents.carol.post('/organisations/1/members').type('form').send({ email: 'dave@example.test', role: 'org_admin' }); assert.equal((await agents.dave.get('/organisations/1/edit')).status, 200);}); test('nobody changes their own membership', async () => { const res = await agents.carol.post('/organisations/1/members').type('form').send({ email: 'carol@example.test', role: 'member' }); assert.equal(res.status, 403); const { rows } = await pool.query('SELECT role FROM memberships WHERE user_id = 3 AND organisation_id = 1'); assert.equal(rows[0].role, 'org_admin');}); test('unknown emails and roles are form errors', async () => { assert.equal((await agents.carol.post('/organisations/1/members').type('form').send({ email: 'ghost@example.test', role: 'member' })).status, 400); assert.equal((await agents.carol.post('/organisations/1/members').type('form').send({ email: 'nora@example.test', role: 'owner' })).status, 400);}); test('a member cannot add members, even with a well-formed request', async () => { const res = await agents.alice.post('/organisations/1/members').type('form').send({ email: 'nora@example.test', role: 'org_admin' }); assert.equal(res.status, 403);});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) (536.775209ms)
✔ edit issue 101 (89.916083ms)
✔ view issue 103 (building 20) (70.521959ms)
✔ edit issue 103 (reported by dave) (87.843125ms)
✔ report an issue at building 20 (104.550292ms)
✔ view issue 105 (building 30) (45.95575ms)
✔ view issue 106 (building 40, reported by bob) (40.8155ms)
✔ approve inspection 201 (created by dave) (41.993042ms)
✔ approve inspection 202 (created by alice) (52.60975ms)
✔ update organisation 1 (53.674708ms)
✔ issues in each user's list come only from the expected buildings (100.465458ms)
✔ the scenario loads exactly as specified (198.073333ms)
✔ only one active assignment per user, building and role (0.872917ms)
✔ a revoked role can be granted again (1.4975ms)
✔ the My access page shows what the server loaded (72.605ms)
✔ a correct login creates a session and shows the user (268.181875ms)
✔ a wrong password or unknown email gets the same 401 (53.366875ms)
✔ registration validates, creates a user, and logs them in (48.433958ms)
✔ registering an existing email is a field error (31.694083ms)
✔ logout destroys the session (50.524541ms)
✔ allow: a permit matched and nothing forbade it (215.976791ms)
✔ explicit deny: a forbid overrides a matching permit (5.896042ms)
✔ implicit deny: no permit matched (6.068208ms)
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 (6.402125ms)
✔ unknown actions throw instead of deciding (2.003458ms)
✔ a building can be created inside an organisation (335.246417ms)
✔ a duplicate building name in the same organisation is a field error (12.209041ms)
Show 82 more lines
✔ the same building name is allowed in another organisation (17.023ms)
✔ a building with issues cannot be deleted (33.778916ms)
✔ an empty building can be deleted (22.300458ms)
✔ an organisation with buildings cannot be deleted, an empty one can (61.383625ms)
✔ a logged-in POST without a token is refused with 403 (262.32525ms)
✔ a token from another session is refused (36.269375ms)
✔ the right token in the form field works (35.489042ms)
✔ every POST form on every page carries the token (167.248625ms)
✔ the dashboard counts match the database (274.016ms)
✔ only the buildings carol can see appear (5.110666ms)
✔ create a draft, edit it, submit it, approve it (383.203459ms)
✔ invalid transitions are refused with 409 and change nothing (46.004583ms)
✔ only drafts can be edited (23.402291ms)
✔ returning a submitted inspection makes it editable again (31.74725ms)
✔ concurrent approvals: exactly one wins (71.781ms)
✔ unknown actions are 404 (5.765083ms)
✔ the issues list contains only issues from visible buildings (534.853541ms)
✔ a filter for another tenant's building returns nothing (3.706375ms)
✔ the inspections list is scoped too (10.853ms)
✔ organisations are listed for their members only (9.634167ms)
✔ the dashboard counts only visible data (7.228375ms)
✔ view issue 101 (building 10) (537.083417ms)
✔ open the edit form for issue 101 (95.786292ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (87.410625ms)
✔ view issue 105 (building 30) and 106 (building 40) (95.619916ms)
✔ report an issue at building 20 (105.000834ms)
✔ a reporter cannot edit their own issue once it is closed (33.749583ms)
✔ only building admins may delete; refusals change nothing (46.26125ms)
✔ the edit form cannot move an issue to another building (12.058167ms)
✔ the list pages 10 at a time and reports the total (280.47275ms)
✔ pages do not overlap (16.052209ms)
✔ filters combine with AND (5.703541ms)
✔ sorting by priority puts critical first when descending (10.059375ms)
✔ unknown sort keys and SQL in the query string are ignored (27.408708ms)
✔ GET /issues lists issues from the database (273.196958ms)
✔ GET /issues/101 shows one issue with its building (23.171875ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (15.75725ms)
✔ POST /issues re-renders the form with errors (18.725709ms)
✔ POST /issues stores the issue and redirects to it (20.32275ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (17.362833ms)
✔ the stored row has the cleaned values and ignores a client-sent status (9.269792ms)
✔ an issue time in the future is rejected (20.325ms)
✔ GET /issues/101/edit shows the current values (24.892625ms)
✔ POST /issues/:id/edit changes the status and updated_at (15.656416ms)
✔ POST /issues/:id/delete removes the issue (26.728167ms)
✔ only organisation admins can open the members page (455.296458ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (47.783041ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (31.794708ms)
✔ nobody changes their own membership (12.476708ms)
✔ unknown emails and roles are form errors (20.492125ms)
✔ a member cannot add members, even with a well-formed request (8.728083ms)
✔ GET /organisations lists organisations with building counts (267.33075ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (36.2955ms)
✔ POST /organisations validates and creates (30.232541ms)
✔ POST /organisations/:id/edit renames the organisation (35.627125ms)
✔ unknown organisations are 404 (6.90725ms)
✔ every policy is valid against the schema (30.966042ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (8.718667ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (354.059ms)
✔ anonymous requests are redirected to the login page (217.877459ms)
✔ anonymous writes are refused and change nothing (10.649667ms)
✔ login and register pages stay public (5.356666ms)
✔ login issues a new session id (no session fixation) (32.029917ms)
✔ returnTo only follows local paths (28.028584ms)
✔ new issues and transitions record the logged-in user (105.26625ms)
✔ the session cookie has the attributes we chose (30.385834ms)
✔ organisation 1: view and update (611.50875ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (35.743542ms)
✔ building 10: view, update, delete (167.447708ms)
✔ creating buildings needs org_admin (52.981167ms)
✔ creating an organisation makes the creator its admin (21.057209ms)
✔ inspections: view 201, open the edit form for draft 203 (132.884708ms)
✔ approve inspection 201 (dave's): only building admins (42.520917ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (46.791417ms)
ℹ tests 101
ℹ suites 0
ℹ pass 101
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12553.329042
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
Carol makes Nora a member, and we read Cedar's decision in the log:
rm -f /tmp/carol.txt
TOKEN=$(curl -s -c /tmp/carol.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/carol.txt -c /tmp/carol.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=carol@example.test -d password=password123
TOKEN=$(curl -s -b /tmp/carol.txt http://localhost:3000/account | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/carol.txt http://localhost:3000/organisations/1/members -d _csrf=$TOKEN -d email=nora@example.test -d role=member
303
authz user=3 action=ViewOrganisation resource=Organisation::1 decision=allow reasons=org-member
authz user=3 action=ViewMembers resource=Organisation::1 decision=allow reasons=org-admin
authz user=3 action=ManageMembers resource=Organisation::1 decision=allow reasons=org-admin
POST /organisations/1/members -> 303 (33 ms)

Experiment
member. org-admin permits ManageMembers for her. Which policies appear in the decision?TOKEN=$(curl -s -b /tmp/carol.txt http://localhost:3000/account | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/carol.txt http://localhost:3000/organisations/1/members -d _csrf=$TOKEN -d email=carol@example.test -d role=member
403
authz user=3 action=ViewMembers resource=Organisation::1 decision=allow reasons=org-admin
authz user=3 action=ManageMembers resource=Organisation::1 decision=deny reasons=forbid-self-membership-change
POST /organisations/1/members -> 403 (15 ms)
Reveal Answer
deny, with the reason forbid-self-membership-change: the forbid compared context.targetUser (Carol, loaded from the email in the form) with the principal (Carol, from the session) and matched. The route answered 403. The permit still matched, but a forbid always wins.
Return the development data to the scenario:
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) (532.292584ms)
✔ edit issue 101 (84.950208ms)
✔ view issue 103 (building 20) (55.020791ms)
✔ edit issue 103 (reported by dave) (82.048292ms)
✔ report an issue at building 20 (99.274375ms)
✔ view issue 105 (building 30) (47.735208ms)
✔ view issue 106 (building 40, reported by bob) (38.458334ms)
✔ approve inspection 201 (created by dave) (40.810917ms)
✔ approve inspection 202 (created by alice) (51.493042ms)
✔ update organisation 1 (52.219333ms)
✔ issues in each user's list come only from the expected buildings (94.469042ms)
✔ the scenario loads exactly as specified (208.294208ms)
✔ only one active assignment per user, building and role (0.978125ms)
✔ a revoked role can be granted again (1.069375ms)
✔ the My access page shows what the server loaded (71.961583ms)
✔ a correct login creates a session and shows the user (349.950292ms)
✔ a wrong password or unknown email gets the same 401 (52.913041ms)
✔ registration validates, creates a user, and logs them in (42.707542ms)
✔ registering an existing email is a field error (30.64275ms)
✔ logout destroys the session (55.254583ms)
✔ allow: a permit matched and nothing forbade it (210.162833ms)
✔ explicit deny: a forbid overrides a matching permit (6.469083ms)
✔ implicit deny: no permit matched (5.8055ms)
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 (6.798208ms)
✔ unknown actions throw instead of deciding (1.922875ms)
✔ a building can be created inside an organisation (313.637666ms)
✔ a duplicate building name in the same organisation is a field error (12.646917ms)
Show 82 more lines
✔ the same building name is allowed in another organisation (17.267875ms)
✔ a building with issues cannot be deleted (33.796917ms)
✔ an empty building can be deleted (27.463166ms)
✔ an organisation with buildings cannot be deleted, an empty one can (64.44625ms)
✔ a logged-in POST without a token is refused with 403 (271.043125ms)
✔ a token from another session is refused (35.052042ms)
✔ the right token in the form field works (35.90625ms)
✔ every POST form on every page carries the token (176.055ms)
✔ the dashboard counts match the database (274.259041ms)
✔ only the buildings carol can see appear (4.984667ms)
✔ create a draft, edit it, submit it, approve it (387.232666ms)
✔ invalid transitions are refused with 409 and change nothing (38.935125ms)
✔ only drafts can be edited (21.93025ms)
✔ returning a submitted inspection makes it editable again (24.397291ms)
✔ concurrent approvals: exactly one wins (66.207625ms)
✔ unknown actions are 404 (3.212041ms)
✔ the issues list contains only issues from visible buildings (533.329167ms)
✔ a filter for another tenant's building returns nothing (3.867083ms)
✔ the inspections list is scoped too (9.29975ms)
✔ organisations are listed for their members only (10.434ms)
✔ the dashboard counts only visible data (7.3395ms)
✔ view issue 101 (building 10) (504.351667ms)
✔ open the edit form for issue 101 (85.5245ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (89.169625ms)
✔ view issue 105 (building 30) and 106 (building 40) (97.755584ms)
✔ report an issue at building 20 (103.631334ms)
✔ a reporter cannot edit their own issue once it is closed (42.597917ms)
✔ only building admins may delete; refusals change nothing (53.601833ms)
✔ the edit form cannot move an issue to another building (14.006792ms)
✔ the list pages 10 at a time and reports the total (286.099042ms)
✔ pages do not overlap (17.437541ms)
✔ filters combine with AND (5.689834ms)
✔ sorting by priority puts critical first when descending (6.061083ms)
✔ unknown sort keys and SQL in the query string are ignored (30.05275ms)
✔ GET /issues lists issues from the database (277.943666ms)
✔ GET /issues/101 shows one issue with its building (23.951875ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (17.095208ms)
✔ POST /issues re-renders the form with errors (17.616875ms)
✔ POST /issues stores the issue and redirects to it (21.326208ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (19.679ms)
✔ the stored row has the cleaned values and ignores a client-sent status (12.636083ms)
✔ an issue time in the future is rejected (18.010833ms)
✔ GET /issues/101/edit shows the current values (30.049875ms)
✔ POST /issues/:id/edit changes the status and updated_at (16.380375ms)
✔ POST /issues/:id/delete removes the issue (27.900875ms)
✔ only organisation admins can open the members page (520.893583ms)
✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (51.278834ms)
✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (31.855167ms)
✔ nobody changes their own membership (12.208625ms)
✔ unknown emails and roles are form errors (20.86775ms)
✔ a member cannot add members, even with a well-formed request (8.827291ms)
✔ GET /organisations lists organisations with building counts (272.453958ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (35.88925ms)
✔ POST /organisations validates and creates (37.069416ms)
✔ POST /organisations/:id/edit renames the organisation (36.802333ms)
✔ unknown organisations are 404 (9.02ms)
✔ every policy is valid against the schema (31.198ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (8.784208ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (352.847125ms)
✔ anonymous requests are redirected to the login page (198.160792ms)
✔ anonymous writes are refused and change nothing (10.63ms)
✔ login and register pages stay public (6.048958ms)
✔ login issues a new session id (no session fixation) (40.512833ms)
✔ returnTo only follows local paths (29.68475ms)
✔ new issues and transitions record the logged-in user (101.197292ms)
✔ the session cookie has the attributes we chose (27.047375ms)
✔ organisation 1: view and update (623.678583ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (35.677584ms)
✔ building 10: view, update, delete (173.467625ms)
✔ creating buildings needs org_admin (53.552333ms)
✔ creating an organisation makes the creator its admin (19.408292ms)
✔ inspections: view 201, open the edit form for draft 203 (120.327334ms)
✔ approve inspection 201 (dave's): only building admins (44.69725ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (49.713667ms)
ℹ tests 101
ℹ suites 0
ℹ pass 101
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 12571.300625
git add -A
git commit -m "Organisation members and onboarding"
[main 431ca93] Organisation members and onboarding
12 files changed, 235 insertions(+), 6 deletions(-)
create mode 100644 migrations/006_create_permission_changes.sql
create mode 100644 src/authz/policies/forbid-self-membership-change.cedar
create mode 100644 src/models/members.js
create mode 100644 test/members.test.js
create mode 100644 views/organisations/members.ejs
Symptom while parsing context, expected the record to have an attribute targetUser
ManageMembers was asked without a context, for example from a template. Only the POST route can ask it, because only it knows who the change is for. Templates use ViewMembers.
Symptom The new member still sees nothing
Membership alone grants ViewOrganisation only (lesson 5.1). Building access needs a building role; that is the next lesson.
Recap and next step
Organisation admins can onboard registered users and change their roles. The decision uses a context that describes the request (target user, role), built only from validated, database-backed values. A forbid stops self-changes. Each change and its log row commit together.
Members still have no building roles. Next lesson: granting and revoking building roles, with two forbids that make delegation safe, and revocation that takes effect on the very next request.
Open the checkpoint files for lesson 7.3 (separate page; only files from this lesson and earlier)