Module 6 · Introduce Cedar
6.5 Every route on Cedar
Grow the schema and the entity mapper to cover organisations, buildings, issues and inspections, write twelve small policies, and replace the whole JavaScript switch with one line, keeping all 89 tests green.
Starting point
Cedar decides ViewIssue; the other sixteen actions still run through the JavaScript switch in src/authz/rules.js.
Outcome
src/authz/├── schema.cedarschema (all entity types and all 17 actions)├── policies/ (12 policies, one per file)├── entities.js (users, organisations, buildings, issues, inspections)├── request.js (resource type for every action)└── rules.js (one line: ask Cedar)can() no longer contains a single rule. Every authorization decision in Caretaker is made by a Cedar policy you can read on its own.
The problem
Moving the remaining actions one by one would repeat lesson 6.4 sixteen times. Instead, we look at the matrix as Cedar sees it: what does each policy need to know about the principal and the resource? The answer determines the schema, and the schema determines what the mapper must build.
| Policy needs | From | Attribute |
|---|---|---|
| buildings where the user may view things | assignments (any role) + organisations they administer | readableBuildings |
| buildings where the user may report | reporter + admin buildings |
reportingBuildings |
| buildings where the user may inspect | inspector + admin buildings |
inspectingBuildings |
| buildings the user administers | building_admin + organisations they administer |
adminBuildings |
| organisations the user belongs to, or administers | memberships | memberOrganisations, adminOrganisations |
| which building an issue or inspection belongs to | the row's building_id |
building |
| who reported an issue, who created an inspection | reported_by, created_by |
reportedBy, createdBy |
| issue status | status |
status |
issueViewerBuildings becomes readableBuildings: it now governs buildings and inspections too, and a name should say what it means. In this first version the mapper computes inherited rights (an organisation admin's buildings appear in adminBuildings; a building admin's buildings appear in reportingBuildings). Keep an eye on that decision; we revisit it in Module 7.
Build it
1. The complete schema
Replace src/authz/schema.cedarschema:
// What Cedar may see in Caretaker, and in what shape. Version 1.namespace Caretaker { entity Organisation; entity Building in [Organisation] = { organisation: Organisation, }; // Version 1: every set is computed by the entity mapper, including inherited rights. entity User = { readableBuildings: Set<Building>, reportingBuildings: Set<Building>, inspectingBuildings: 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 ViewOrganisation, UpdateOrganisation, DeleteOrganisation, CreateBuilding appliesTo { principal: [User], resource: [Organisation], }; action ViewBuilding, UpdateBuilding, DeleteBuilding, CreateIssue, CreateInspection appliesTo { principal: [User], resource: [Building], }; action ViewIssue, UpdateIssue, DeleteIssue appliesTo { principal: [User], resource: [Issue], }; action ViewInspection, UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection appliesTo { principal: [User], resource: [Inspection], };}Several actions can share one declaration when they apply to the same types. Note again: creating an issue or an inspection is an action on its building, because the issue does not exist yet.
2. Twelve policies
The single view-issue.cedar is replaced by a policy that covers issues and inspections. Remove it:
git rm -q src/authz/policies/view-issue.cedar
Now create the policies. Each is short, has a comment saying what it means, and has a file name that will appear in every decision log. Reading them in order is reading the access matrix.
Viewing:
// Anyone with any role at a building may view its issues and inspections.permit ( principal, action in [Caretaker::Action::"ViewIssue", Caretaker::Action::"ViewInspection"], resource)when { principal.readableBuildings.contains(resource.building) };// Anyone with any role at a building may view the building itself.permit (principal, action == Caretaker::Action::"ViewBuilding", resource)when { principal.readableBuildings.contains(resource) };// Members may view their organisation.permit (principal, action == Caretaker::Action::"ViewOrganisation", resource)when { principal.memberOrganisations.contains(resource) };action in [A, B] matches either action. The validator checks the condition for both resource types, so resource.building must exist on issues and on inspections, and it does.
Reporting and inspecting:
// Reporters (and building admins) may report issues at their buildings.permit (principal, action == Caretaker::Action::"CreateIssue", resource)when { principal.reportingBuildings.contains(resource) };// Reporters may edit issues they reported, while the issue is not closed.permit (principal, action == Caretaker::Action::"UpdateIssue", resource)when { principal.reportingBuildings.contains(resource.building) && resource has reportedBy && resource.reportedBy == principal && resource.status != "closed"};// Inspectors (and building admins) may create inspections at their buildings.permit (principal, action == Caretaker::Action::"CreateInspection", resource)when { principal.inspectingBuildings.contains(resource) };// Inspectors may edit and submit inspections they created.permit ( principal, action in [Caretaker::Action::"UpdateInspection", Caretaker::Action::"SubmitInspection"], resource)when { principal.inspectingBuildings.contains(resource.building) && resource has createdBy && resource.createdBy == principal};resource has reportedBytests whether the optional attribute is present. Readingresource.reportedBywithout it would be an evaluation error on issues with no reporter. The validator insists on it: try removing it later and runnpm run authz:validate.resource.reportedBy == principalcompares two entity references. It is the ownership check from lesson 5.2, now written as data.&&short-circuits in Cedar as in JavaScript, sohasprotects the comparison that follows it.
Administration:
// Building admins may change any issue or inspection at their buildings.permit ( principal, action in [ Caretaker::Action::"UpdateIssue", Caretaker::Action::"DeleteIssue", Caretaker::Action::"UpdateInspection", Caretaker::Action::"SubmitInspection", Caretaker::Action::"ReturnInspection" ], resource)when { principal.adminBuildings.contains(resource.building) };// Building admins may approve inspections, but not inspections they created (separation of duties).permit (principal, action == Caretaker::Action::"ApproveInspection", resource)when { principal.adminBuildings.contains(resource.building) && !(resource has createdBy && resource.createdBy == principal)};// Building admins may update their buildings.permit (principal, action == Caretaker::Action::"UpdateBuilding", resource)when { principal.adminBuildings.contains(resource) };// Organisation admins may update and delete the organisation and create buildings in it.permit ( principal, action in [ Caretaker::Action::"UpdateOrganisation", Caretaker::Action::"DeleteOrganisation", Caretaker::Action::"CreateBuilding" ], resource)when { principal.adminOrganisations.contains(resource) };// Organisation admins may delete buildings of their organisation.permit (principal, action == Caretaker::Action::"DeleteBuilding", resource)when { principal.adminOrganisations.contains(resource.organisation) };approve-inspection copies the separation-of-duties condition from lesson 5.5 into a permit. It works, but it is the same weaving we criticised in JavaScript. The next lesson replaces it with a forbid policy.
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
12 policies are valid against the schema
3. The mapper, version 1
Replace src/authz/entities.js:
// The entity mapper: turns rows the application already loaded into Cedar entities.// Every value comes from the database (through loadAccess and the models) or from// the session (the user id). Nothing comes from the HTTP request. const NAMESPACE = 'Caretaker'; export function ref(type, id) { return { type: `${NAMESPACE}::${type}`, id: String(id) };} function refs(type, ids) { return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));} function buildingsWithRole(user, roles) { return user.access.assignments.filter((a) => roles.includes(a.role)).map((a) => a.building_id);} // Version 1: the mapper computes effective rights, including inheritance:// org_admin counts as building_admin at every building of the organisation, and// building_admin counts as reporter and inspector at that building.export function userEntity(user) { const orgAdminBuildings = user.access.orgAdminBuildings.map((s) => s.building_id); const adminBuildings = [...buildingsWithRole(user, ['building_admin']), ...orgAdminBuildings]; return { uid: ref('User', user.id), attrs: { readableBuildings: refs('Building', [...buildingsWithRole(user, ['viewer', 'reporter', 'inspector', 'building_admin']), ...orgAdminBuildings]), reportingBuildings: refs('Building', [...buildingsWithRole(user, ['reporter']), ...adminBuildings]), inspectingBuildings: refs('Building', [...buildingsWithRole(user, ['inspector']), ...adminBuildings]), adminBuildings: refs('Building', adminBuildings), memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)), adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)), }, parents: [], };} export function organisationEntity(organisationId) { return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };} export function buildingEntity({ id, organisation_id }) { return { uid: ref('Building', id), attrs: { organisation: ref('Organisation', organisation_id) }, parents: [ref('Organisation', organisation_id)], };} export function issueEntity(issue) { const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority }; if (issue.reported_by !== null) { attrs.reportedBy = ref('User', issue.reported_by); } return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };} export function inspectionEntity(inspection) { const attrs = { building: ref('Building', inspection.building_id), status: inspection.status }; if (inspection.created_by !== null) { attrs.createdBy = ref('User', inspection.created_by); } return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };}4. A resource type for every action
Replace src/authz/request.js:
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', 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) { 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], };}The rows passed to can() already carry what the mappers read: findBuilding and listBuildings return organisation_id, findIssue and findInspection join buildings for organisation_id, and the organisation page builds { id, organisation_id } for each building link.
5. The switch disappears
Replace src/authz/rules.js:
// 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) { return authorize(user, action, resource).allowed;}An unknown action still fails loudly: buildAuthorizationCall throws when an action has no resource type.
6. Let the explain command load any resource
// Usage: npm run authz:explain -- <user> <action> <issueId>// Usage: npm run authz:explain -- <user> <action> <resourceId>// Example: npm run authz:explain -- alice ViewIssue 101
import { findIssue } from '../src/models/issues.js';import { findInspection } from '../src/models/inspections.js';import { findBuilding } from '../src/models/buildings.js';import { findOrganisation } from '../src/models/organisations.js';import { RESOURCE_TYPES } from '../src/authz/request.js';
const [name, action, issueId] = process.argv.slice(2);const [name, action, resourceId] = process.argv.slice(2);const FINDERS = { Issue: findIssue, Inspection: findInspection, Building: findBuilding, Organisation: findOrganisation };
const issue = await findIssue(Number(issueId)); if (!issue) throw new Error(`no issue ${issueId}`); show('3. issue row', { id: issue.id, building_id: issue.building_id, organisation_id: issue.organisation_id, reported_by: issue.reported_by, status: issue.status, priority: issue.priority }); const type = RESOURCE_TYPES[action]; const row = type ? await FINDERS[type](Number(resourceId)) : null; if (!row) throw new Error(`no resource ${resourceId} for action ${action}`); show(`3. ${type} row`, row); const call = buildAuthorizationCall(user, action, issue); const call = buildAuthorizationCall(user, action, row);
Show the whole scripts/authz-explain.js after this change
// Usage: npm run authz:explain -- <user> <action> <resourceId>// Example: npm run authz:explain -- alice ViewIssue 101import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { pool, query } from '../src/db.js';import { findUserById } from '../src/models/users.js';import { loadAccess } from '../src/models/access.js';import { findIssue } from '../src/models/issues.js';import { findInspection } from '../src/models/inspections.js';import { findBuilding } from '../src/models/buildings.js';import { findOrganisation } from '../src/models/organisations.js';import { RESOURCE_TYPES } from '../src/authz/request.js';import { loadPolicyStore } from '../src/authz/policy-store.js';import { buildAuthorizationCall } from '../src/authz/request.js'; const [name, action, resourceId] = process.argv.slice(2);const FINDERS = { Issue: findIssue, Inspection: findInspection, Building: findBuilding, Organisation: findOrganisation };const show = (title, value) => console.log(`\n== ${title}\n${JSON.stringify(value, null, 2)}`); try { const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]); if (rows.length === 0) throw new Error(`no user ${name}@example.test`); const user = await findUserById(rows[0].id); user.access = await loadAccess(user.id); show('1. users row (the session holds only this id)', { id: user.id, email: user.email }); show('2. access rows loaded for this request', user.access); const type = RESOURCE_TYPES[action]; const row = type ? await FINDERS[type](Number(resourceId)) : null; if (!row) throw new Error(`no resource ${resourceId} for action ${action}`); show(`3. ${type} row`, row); const call = buildAuthorizationCall(user, action, row); show('4. entities built by the mapper', call.entities); show('5. request', { principal: call.principal, action: call.action, resource: call.resource, context: call.context }); const { schema, policies } = loadPolicyStore(); const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } }); show('6. Cedar answer', answer);} finally { await pool.end();}// Usage: npm run authz:explain -- <user> <action> <resourceId>
// Example: npm run authz:explain -- alice ViewIssue 101
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { pool, query } from '../src/db.js';
import { findUserById } from '../src/models/users.js';
import { loadAccess } from '../src/models/access.js';
import { findIssue } from '../src/models/issues.js';
import { findInspection } from '../src/models/inspections.js';
import { findBuilding } from '../src/models/buildings.js';
import { findOrganisation } from '../src/models/organisations.js';
import { RESOURCE_TYPES } from '../src/authz/request.js';
import { loadPolicyStore } from '../src/authz/policy-store.js';
import { buildAuthorizationCall } from '../src/authz/request.js';
const [name, action, resourceId] = process.argv.slice(2);
const FINDERS = { Issue: findIssue, Inspection: findInspection, Building: findBuilding, Organisation: findOrganisation };
const show = (title, value) => console.log(`\n== ${title}\n${JSON.stringify(value, null, 2)}`);
try {
const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]);
if (rows.length === 0) throw new Error(`no user ${name}@example.test`);
const user = await findUserById(rows[0].id);
user.access = await loadAccess(user.id);
show('1. users row (the session holds only this id)', { id: user.id, email: user.email });
show('2. access rows loaded for this request', user.access);
const type = RESOURCE_TYPES[action];
const row = type ? await FINDERS[type](Number(resourceId)) : null;
if (!row) throw new Error(`no resource ${resourceId} for action ${action}`);
show(`3. ${type} row`, row);
const call = buildAuthorizationCall(user, action, row);
show('4. entities built by the mapper', call.entities);
show('5. request', { principal: call.principal, action: call.action, resource: call.resource, context: call.context });
const { schema, policies } = loadPolicyStore();
const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } });
show('6. Cedar answer', answer);
} finally {
await pool.end();
}
And make the policy test check that every action has at least one policy:
import { loadPolicyStore } from '../src/authz/policy-store.js';import { RESOURCE_TYPES } from '../src/authz/request.js';
assert.deepEqual(result.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`), []);}); test('every action used by the app is mentioned by at least one policy', () => { const text = Object.values(loadPolicyStore().policies).join('\n'); const missing = Object.keys(RESOURCE_TYPES).filter((action) => !text.includes(`Action::"${action}"`)); assert.deepEqual(missing, []);});
Show the whole test/policies.test.js after this change
import { test } from 'node:test';import assert from 'node:assert/strict';import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { loadPolicyStore } from '../src/authz/policy-store.js';import { RESOURCE_TYPES } from '../src/authz/request.js'; test('every policy is valid against the schema', () => { const { schema, policies } = loadPolicyStore(); assert.ok(Object.keys(policies).length > 0, 'there are policies'); const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } }); assert.equal(result.type, 'success', JSON.stringify(result.errors)); assert.deepEqual(result.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`), []);}); test('every action used by the app is mentioned by at least one policy', () => { const text = Object.values(loadPolicyStore().policies).join('\n'); const missing = Object.keys(RESOURCE_TYPES).filter((action) => !text.includes(`Action::"${action}"`)); assert.deepEqual(missing, []);});import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { loadPolicyStore } from '../src/authz/policy-store.js';
import { RESOURCE_TYPES } from '../src/authz/request.js';
test('every policy is valid against the schema', () => {
const { schema, policies } = loadPolicyStore();
assert.ok(Object.keys(policies).length > 0, 'there are policies');
const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });
assert.equal(result.type, 'success', JSON.stringify(result.errors));
assert.deepEqual(result.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`), []);
});
test('every action used by the app is mentioned by at least one policy', () => {
const text = Object.values(loadPolicyStore().policies).join('\n');
const missing = Object.keys(RESOURCE_TYPES).filter((action) => !text.includes(`Action::"${action}"`));
assert.deepEqual(missing, []);
});
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) (522.893042ms)
✔ edit issue 101 (66.531125ms)
✔ view issue 103 (building 20) (58.484541ms)
✔ edit issue 103 (reported by dave) (76.17275ms)
✔ report an issue at building 20 (95.555709ms)
✔ view issue 105 (building 30) (43.930333ms)
✔ view issue 106 (building 40, reported by bob) (36.926125ms)
✔ approve inspection 201 (created by dave) (42.534042ms)
✔ approve inspection 202 (created by alice) (47.764458ms)
✔ update organisation 1 (45.576917ms)
✔ issues in each user's list come only from the expected buildings (99.0495ms)
✔ the scenario loads exactly as specified (208.969792ms)
✔ only one active assignment per user, building and role (0.9715ms)
✔ a revoked role can be granted again (1.293417ms)
✔ the My access page shows what the server loaded (74.469125ms)
✔ a correct login creates a session and shows the user (270.018041ms)
✔ a wrong password or unknown email gets the same 401 (53.057166ms)
✔ registration validates, creates a user, and logs them in (48.129375ms)
✔ registering an existing email is a field error (34.357417ms)
✔ logout destroys the session (50.177208ms)
✔ a building can be created inside an organisation (301.343875ms)
✔ a duplicate building name in the same organisation is a field error (12.187417ms)
✔ the same building name is allowed in another organisation (16.899125ms)
✔ a building with issues cannot be deleted (39.203917ms)
✔ an empty building can be deleted (21.341791ms)
✔ an organisation with buildings cannot be deleted, an empty one can (51.057ms)
✔ a logged-in POST without a token is refused with 403 (275.5595ms)
✔ a token from another session is refused (36.53ms)
✔ the right token in the form field works (34.532792ms)
✔ every POST form on every page carries the token (168.186292ms)
✔ the dashboard counts match the database (276.81075ms)
✔ only the buildings carol can see appear (5.663875ms)
✔ create a draft, edit it, submit it, approve it (379.380333ms)
✔ invalid transitions are refused with 409 and change nothing (35.87ms)
✔ only drafts can be edited (15.7445ms)
✔ returning a submitted inspection makes it editable again (18.571875ms)
Show 62 more lines
✔ concurrent approvals: exactly one wins (60.299583ms)
✔ unknown actions are 404 (3.296583ms)
✔ the issues list contains only issues from visible buildings (544.980083ms)
✔ a filter for another tenant's building returns nothing (4.446792ms)
✔ the inspections list is scoped too (9.83575ms)
✔ organisations are listed for their members only (8.368125ms)
✔ the dashboard counts only visible data (6.76825ms)
✔ view issue 101 (building 10) (525.7525ms)
✔ open the edit form for issue 101 (77.097542ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (84.739917ms)
✔ view issue 105 (building 30) and 106 (building 40) (86.870792ms)
✔ report an issue at building 20 (80.457042ms)
✔ a reporter cannot edit their own issue once it is closed (32.678ms)
✔ only building admins may delete; refusals change nothing (41.878208ms)
✔ the edit form cannot move an issue to another building (9.525208ms)
✔ the list pages 10 at a time and reports the total (286.351584ms)
✔ pages do not overlap (16.093334ms)
✔ filters combine with AND (5.471458ms)
✔ sorting by priority puts critical first when descending (5.0905ms)
✔ unknown sort keys and SQL in the query string are ignored (27.7335ms)
✔ GET /issues lists issues from the database (268.86825ms)
✔ GET /issues/101 shows one issue with its building (21.62325ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (20.538667ms)
✔ POST /issues re-renders the form with errors (16.496291ms)
✔ POST /issues stores the issue and redirects to it (35.2755ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (17.290791ms)
✔ the stored row has the cleaned values and ignores a client-sent status (9.490833ms)
✔ an issue time in the future is rejected (15.291084ms)
✔ GET /issues/101/edit shows the current values (20.758666ms)
✔ POST /issues/:id/edit changes the status and updated_at (10.028458ms)
✔ POST /issues/:id/delete removes the issue (19.468833ms)
✔ GET /organisations lists organisations with building counts (272.487583ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (31.428833ms)
✔ POST /organisations validates and creates (26.383041ms)
✔ POST /organisations/:id/edit renames the organisation (28.881958ms)
✔ unknown organisations are 404 (6.46625ms)
✔ every policy is valid against the schema (30.24175ms)
✔ every action used by the app is mentioned by at least one policy (0.575625ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (351.936375ms)
✔ anonymous requests are redirected to the login page (215.915917ms)
✔ anonymous writes are refused and change nothing (10.745541ms)
✔ login and register pages stay public (6.0285ms)
✔ login issues a new session id (no session fixation) (31.275ms)
✔ returnTo only follows local paths (29.582542ms)
✔ new issues and transitions record the logged-in user (96.709291ms)
✔ the session cookie has the attributes we chose (29.1115ms)
✔ organisation 1: view and update (556.92325ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (27.144916ms)
✔ building 10: view, update, delete (143.741167ms)
✔ creating buildings needs org_admin (46.233625ms)
✔ creating an organisation makes the creator its admin (17.328334ms)
✔ inspections: view 201, open the edit form for draft 203 (115.851667ms)
✔ approve inspection 201 (dave's): only building admins (37.424ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (42.853083ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10884.257833
89 tests from before, plus the new policy check, pass. Every cell of the access matrix, every isolation test, every issue, building, organisation and inspection test: same behaviour, new engine.
Watch a page that asks several questions. Dave opens issue 101, where he is an inspector:
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
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
authz user=4 action=ViewIssue resource=Issue::101 decision=allow reasons=view-building-data
authz user=4 action=UpdateIssue resource=Issue::101 decision=deny reasons=-
authz user=4 action=DeleteIssue resource=Issue::101 decision=deny reasons=-
GET /issues/101 -> 200 (49 ms)
Three decisions for one page: the route asked ViewIssue (allowed by view-building-data), then the template asked UpdateIssue and DeleteIssue to decide which buttons to show (both denied, no reason). The log makes the template's questions visible too.
Explain two UpdateIssue decisions on Dave's own issue 103:
npm run authz:explain -- dave UpdateIssue 103 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"update-own-issue"
],
"errors": []
}
},
"warnings": []
}
npm run authz:explain -- carol UpdateIssue 103 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"administer-building-data"
],
"errors": []
}
},
"warnings": []
}
Same action, same resource, different reasons: Dave is allowed by ownership, Carol by administration (through her organisation, computed into adminBuildings by the mapper).
Experiment
Alice is building admin at building 10, and she reported issue 101 herself.
npm run authz:explain -- alice UpdateIssue 101 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"administer-building-data",
"update-own-issue"
],
"errors": []
}
},
"warnings": []
}
Reveal Answer
Two: administer-building-data and update-own-issue. The reason lists every permit policy that was satisfied, not just the first one. Cedar policies are not evaluated in order and do not "stop at the first match"; adding a policy can never change which other policies match. That property is what makes policies safe to add and remove one file at a time.
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) (517.918875ms)
✔ edit issue 101 (90.649458ms)
✔ view issue 103 (building 20) (60.65525ms)
✔ edit issue 103 (reported by dave) (79.177291ms)
✔ report an issue at building 20 (119.984792ms)
✔ view issue 105 (building 30) (40.877959ms)
✔ view issue 106 (building 40, reported by bob) (35.23875ms)
✔ approve inspection 201 (created by dave) (34.548875ms)
✔ approve inspection 202 (created by alice) (42.664292ms)
✔ update organisation 1 (38.012375ms)
✔ issues in each user's list come only from the expected buildings (101.583416ms)
✔ the scenario loads exactly as specified (215.056708ms)
✔ only one active assignment per user, building and role (1.125583ms)
✔ a revoked role can be granted again (1.50625ms)
✔ the My access page shows what the server loaded (75.126375ms)
✔ a correct login creates a session and shows the user (243.80275ms)
✔ a wrong password or unknown email gets the same 401 (53.281833ms)
✔ registration validates, creates a user, and logs them in (36.126917ms)
✔ registering an existing email is a field error (33.681791ms)
✔ logout destroys the session (55.923709ms)
✔ a building can be created inside an organisation (304.72025ms)
✔ a duplicate building name in the same organisation is a field error (11.371625ms)
✔ the same building name is allowed in another organisation (16.43675ms)
✔ a building with issues cannot be deleted (36.940833ms)
✔ an empty building can be deleted (21.418875ms)
✔ an organisation with buildings cannot be deleted, an empty one can (50.657917ms)
✔ a logged-in POST without a token is refused with 403 (275.099916ms)
✔ a token from another session is refused (39.074833ms)
✔ the right token in the form field works (34.78175ms)
✔ every POST form on every page carries the token (173.141083ms)
✔ the dashboard counts match the database (265.133708ms)
✔ only the buildings carol can see appear (5.741417ms)
✔ create a draft, edit it, submit it, approve it (365.264375ms)
✔ invalid transitions are refused with 409 and change nothing (32.716542ms)
✔ only drafts can be edited (17.104708ms)
✔ returning a submitted inspection makes it editable again (22.291666ms)
Show 62 more lines
✔ concurrent approvals: exactly one wins (62.960166ms)
✔ unknown actions are 404 (3.462291ms)
✔ the issues list contains only issues from visible buildings (519.223042ms)
✔ a filter for another tenant's building returns nothing (3.722875ms)
✔ the inspections list is scoped too (10.221542ms)
✔ organisations are listed for their members only (8.324125ms)
✔ the dashboard counts only visible data (6.534917ms)
✔ view issue 101 (building 10) (516.358375ms)
✔ open the edit form for issue 101 (87.029ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (72.913916ms)
✔ view issue 105 (building 30) and 106 (building 40) (89.000917ms)
✔ report an issue at building 20 (80.947959ms)
✔ a reporter cannot edit their own issue once it is closed (31.140042ms)
✔ only building admins may delete; refusals change nothing (46.850375ms)
✔ the edit form cannot move an issue to another building (9.583458ms)
✔ the list pages 10 at a time and reports the total (290.157333ms)
✔ pages do not overlap (15.8195ms)
✔ filters combine with AND (5.452625ms)
✔ sorting by priority puts critical first when descending (5.776875ms)
✔ unknown sort keys and SQL in the query string are ignored (27.842ms)
✔ GET /issues lists issues from the database (268.253959ms)
✔ GET /issues/101 shows one issue with its building (23.83025ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (16.884209ms)
✔ POST /issues re-renders the form with errors (15.960833ms)
✔ POST /issues stores the issue and redirects to it (19.227375ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (15.467667ms)
✔ the stored row has the cleaned values and ignores a client-sent status (9.97775ms)
✔ an issue time in the future is rejected (14.71025ms)
✔ GET /issues/101/edit shows the current values (22.170584ms)
✔ POST /issues/:id/edit changes the status and updated_at (12.482292ms)
✔ POST /issues/:id/delete removes the issue (22.02875ms)
✔ GET /organisations lists organisations with building counts (268.36125ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (31.341084ms)
✔ POST /organisations validates and creates (25.599791ms)
✔ POST /organisations/:id/edit renames the organisation (29.923375ms)
✔ unknown organisations are 404 (8.533584ms)
✔ every policy is valid against the schema (30.237917ms)
✔ every action used by the app is mentioned by at least one policy (0.663208ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (349.74275ms)
✔ anonymous requests are redirected to the login page (215.477292ms)
✔ anonymous writes are refused and change nothing (10.834416ms)
✔ login and register pages stay public (5.767583ms)
✔ login issues a new session id (no session fixation) (32.430542ms)
✔ returnTo only follows local paths (27.087292ms)
✔ new issues and transitions record the logged-in user (102.74875ms)
✔ the session cookie has the attributes we chose (27.979167ms)
✔ organisation 1: view and update (592.806791ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (32.776958ms)
✔ building 10: view, update, delete (134.185708ms)
✔ creating buildings needs org_admin (45.920166ms)
✔ creating an organisation makes the creator its admin (20.510833ms)
✔ inspections: view 201, open the edit form for draft 203 (111.235791ms)
✔ approve inspection 201 (dave's): only building admins (42.099666ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (41.306375ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10930.044458
git add -A
git commit -m "Every route on Cedar"
[main 720cc33] Every route on Cedar
19 files changed, 191 insertions(+), 126 deletions(-)
create mode 100644 src/authz/policies/administer-building-data.cedar
create mode 100644 src/authz/policies/administer-organisation.cedar
create mode 100644 src/authz/policies/approve-inspection.cedar
create mode 100644 src/authz/policies/create-inspection.cedar
create mode 100644 src/authz/policies/create-issue.cedar
create mode 100644 src/authz/policies/delete-building.cedar
create mode 100644 src/authz/policies/own-inspections.cedar
create mode 100644 src/authz/policies/update-building.cedar
create mode 100644 src/authz/policies/update-own-issue.cedar
create mode 100644 src/authz/policies/view-building-data.cedar
create mode 100644 src/authz/policies/view-building.cedar
delete mode 100644 src/authz/policies/view-issue.cedar
create mode 100644 src/authz/policies/view-organisation.cedar
Symptom entity type ... is not valid for ... failures in the log
The row passed to can() does not fit the action's resource type, for example a building row passed with an issue action. Check RESOURCE_TYPES and the call building.
Symptom duplicate entity entry failure
buildAuthorizationCall added the same entity twice, for example when a building is both the resource and the related building. Each entity UID may appear only once in the list.
Recap and next step
The schema now describes organisations, buildings, users, issues and inspections and all 17 actions. Twelve short policies express the access matrix. The mapper computes six sets for each user, and can() is one line. The test suite, unchanged, proved the behaviour identical. Decision logs and the explain command show which policies decided, including several at once.
Two pieces are still not right. Separation of duties is woven into a permit, and our app does not yet distinguish the three ways a Cedar call can go wrong. Next: forbid, precedence, and failure modes.
Open the checkpoint files for lesson 6.5 (separate page; only files from this lesson and earlier)