Module 7 · RBAC, ABAC, scoped roles and policy management
7.1 Facts, parents and action groups
Stop computing inherited rights in JavaScript. Give Cedar raw role facts, let parent relationships carry organisation inheritance, group actions, and replace twelve policies with nine that read like the role table.
Starting point
Cedar makes every decision. The mapper builds six derived sets per user: readableBuildings, reportingBuildings, inspectingBuildings, adminBuildings (with organisation inheritance mixed in), memberOrganisations, adminOrganisations.
Outcome
- The mapper reports facts: one set per role, exactly as stored in
building_role_assignments, and the two organisation sets frommemberships. - Organisation inheritance comes from the entity hierarchy: issue → building → organisation, evaluated by Cedar's
inoperator. - Three action groups (
ReadBuildingData,AdministerBuilding,AdministerOrganisation) let one policy cover many actions. - Nine policies replace twelve, and each one is a line of the role table from lesson 5.1.
The problem
Read userEntity from lesson 6.5 again:
const adminBuildings = [...buildingsWithRole(user, ['building_admin']), ...orgAdminBuildings];reportingBuildings: refs('Building', [...buildingsWithRole(user, ['reporter']), ...adminBuildings]),Two authorization rules live in those lines: "an org admin is a building admin at every building of the organisation" and "a building admin can do what a reporter can do". Nobody reviewing the Cedar policies would see them. A change to either rule is a change to JavaScript, invisible in the decision log, and untestable with the policy validator. And loadAccess runs an extra query (orgAdminBuildings) only to support the first rule.
The principle we want: the mapper reports facts; the policies make decisions. A fact is something the database states directly: "Alice holds viewer at building 20", "building 20 belongs to organisation 1". A decision is "therefore Alice may ...".
Build it
1. Two ways to say "inside"
Cedar has two operators that look similar and mean different things:
set.contains(x)is plain set membership: is this exact reference in the set?[Building::"10"].contains(Building::"10")is true;[Organisation::"1"].contains(Building::"10")is false.x in yis hierarchy membership: isxequal toy, or isyone ofx's ancestors throughparents? With our entities,Issue::"101" in Building::"10"is true (the issue's parent is building 10), andIssue::"101" in Organisation::"1"is also true (building 10's parent is organisation 1). When the right side is a set,x in setis true ifxis in any member of the set.
So resource in principal.adminOrganisations asks: is this resource the organisation, or inside it, for any organisation this user administers? That one expression is Carol's whole inheritance rule, evaluated by Cedar from the parent links that the mapper has been building since lesson 6.3.
When should you use which?
| Use | When | Example in Caretaker |
|---|---|---|
| A set of references on the principal | The relationship is personal: it belongs to this user | adminBuildings, reporterBuildings |
| Parents on the resource | The relationship is structural: it is true for everyone | issue in building, building in organisation |
| Parents on the principal (groups) | Many users share a membership you want to name in policies | not used here; see the comparison below |
2. Schema version 2
Replace src/authz/schema.cedarschema:
// 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 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], };}action ReadBuildingData;declares an action that is only used as a group.action ViewIssue in [ReadBuildingData]makesViewIssuea member. A policy withaction in Caretaker::Action::"ReadBuildingData"then applies toViewBuilding,ViewIssueandViewInspection.DeleteBuildingmoved intoAdministerOrganisation: deleting a building is an organisation-level decision (lesson 5.1), even though the resource is a building.- The user's sets now have one name per role.
3. Nine policies
Remove the version 1 policies (keeping the forbid, which does not change):
cd src/authz/policies && git rm -q view-building-data.cedar view-building.cedar view-organisation.cedar create-issue.cedar update-own-issue.cedar create-inspection.cedar own-inspections.cedar administer-building-data.cedar update-building.cedar administer-organisation.cedar delete-building.cedar
Now the new set. Read each against the role table in lesson 5.1.
// Any role at a building (or administering its organisation) lets you read the building's data.// "resource in S" is true if the resource is S, or S is one of its ancestors:// an issue is in its building, and a building is in its organisation.permit (principal, action in Caretaker::Action::"ReadBuildingData", resource)when { resource in principal.viewerBuildings || resource in principal.reporterBuildings || resource in principal.inspectorBuildings || resource in principal.adminBuildings || resource in principal.adminOrganisations};// Building admins may do every administrative action at their buildings.// Organisation admins are building admins at every building of their organisation.permit (principal, action in Caretaker::Action::"AdministerBuilding", resource)when { resource in principal.adminBuildings || resource in principal.adminOrganisations };// Organisation admins may manage the organisation itself and its buildings.permit (principal, action in Caretaker::Action::"AdministerOrganisation", resource)when { resource in principal.adminOrganisations };// Members may view their organisation.permit (principal, action == Caretaker::Action::"ViewOrganisation", resource)when { resource in principal.memberOrganisations };// Reporters may report issues at their buildings.permit (principal, action == Caretaker::Action::"CreateIssue", resource)when { resource in principal.reporterBuildings };// Reporters may edit issues they reported, while the issue is not closed.permit (principal, action == Caretaker::Action::"UpdateIssue", resource)when { resource in principal.reporterBuildings && resource has reportedBy && resource.reportedBy == principal && resource.status != "closed"};// Inspectors may create inspections at their buildings.permit (principal, action == Caretaker::Action::"CreateInspection", resource)when { resource in principal.inspectorBuildings };// Inspectors may edit and submit inspections they created.permit ( principal, action in [Caretaker::Action::"UpdateInspection", Caretaker::Action::"SubmitInspection"], resource)when { resource in principal.inspectorBuildings && resource has createdBy && resource.createdBy == principal};Plus the unchanged forbid-self-approval.cedar. Where did the role ladder go ("building admins can do what reporters can do")? Into building-admin: CreateIssue, CreateInspection and every change action are in the AdministerBuilding group, so a building admin needs no reporter facts. The ladder is now visible as group membership in the schema, not hidden in a mapper.
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
9 policies are valid against the schema
4. The mapper reports facts
Replace userEntity in src/authz/entities.js:
function buildingsWithRole(user, roles) { return user.access.assignments.filter((a) => roles.includes(a.role)).map((a) => a.building_id);function buildingsWithRole(user, role) { return refs('Building', user.access.assignments.filter((a) => a.role === 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.// Version 2: facts only. Each set is exactly the active rows of one role.// Inheritance (organisation -> building) and the role ladder are decided by the policies.export function userEntity(user) { 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), viewerBuildings: buildingsWithRole(user, 'viewer'), reporterBuildings: buildingsWithRole(user, 'reporter'), inspectorBuildings: buildingsWithRole(user, 'inspector'), adminBuildings: buildingsWithRole(user, 'building_admin'), memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)), adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)), }, parents: [], };}
Show the whole src/authz/entities.js after this change
// The entity mapper: turns rows the application already loaded into Cedar entities.// Every value comes from the database (through loadAccess and the models) or from// the session (the user id). Nothing comes from the HTTP request. const NAMESPACE = 'Caretaker'; export function ref(type, id) { return { type: `${NAMESPACE}::${type}`, id: String(id) };} function refs(type, ids) { return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));} function buildingsWithRole(user, role) { return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));} // Version 2: facts only. Each set is exactly the active rows of one role.// Inheritance (organisation -> building) and the role ladder are decided by the policies.export function userEntity(user) { return { uid: ref('User', user.id), attrs: { viewerBuildings: buildingsWithRole(user, 'viewer'), reporterBuildings: buildingsWithRole(user, 'reporter'), inspectorBuildings: buildingsWithRole(user, 'inspector'), adminBuildings: buildingsWithRole(user, 'building_admin'), memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)), adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)), }, parents: [], };} export function organisationEntity(organisationId) { return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };} export function buildingEntity({ id, organisation_id }) { return { uid: ref('Building', id), attrs: { organisation: ref('Organisation', organisation_id) }, parents: [ref('Organisation', organisation_id)], };} export function issueEntity(issue) { const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority }; if (issue.reported_by !== null) { attrs.reportedBy = ref('User', issue.reported_by); } return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };} export function inspectionEntity(inspection) { const attrs = { building: ref('Building', inspection.building_id), status: inspection.status }; if (inspection.created_by !== null) { attrs.createdBy = ref('User', inspection.created_by); } return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };}// The entity mapper: turns rows the application already loaded into Cedar entities.
// Every value comes from the database (through loadAccess and the models) or from
// the session (the user id). Nothing comes from the HTTP request.
const NAMESPACE = 'Caretaker';
export function ref(type, id) {
return { type: `${NAMESPACE}::${type}`, id: String(id) };
}
function refs(type, ids) {
return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));
}
function buildingsWithRole(user, role) {
return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));
}
// Version 2: facts only. Each set is exactly the active rows of one role.
// Inheritance (organisation -> building) and the role ladder are decided by the policies.
export function userEntity(user) {
return {
uid: ref('User', user.id),
attrs: {
viewerBuildings: buildingsWithRole(user, 'viewer'),
reporterBuildings: buildingsWithRole(user, 'reporter'),
inspectorBuildings: buildingsWithRole(user, 'inspector'),
adminBuildings: buildingsWithRole(user, 'building_admin'),
memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)),
adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_id)),
},
parents: [],
};
}
export function organisationEntity(organisationId) {
return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };
}
export function buildingEntity({ id, organisation_id }) {
return {
uid: ref('Building', id),
attrs: { organisation: ref('Organisation', organisation_id) },
parents: [ref('Organisation', organisation_id)],
};
}
export function issueEntity(issue) {
const attrs = { building: ref('Building', issue.building_id), status: issue.status, priority: issue.priority };
if (issue.reported_by !== null) {
attrs.reportedBy = ref('User', issue.reported_by);
}
return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };
}
export function 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)] };
}
loadAccess no longer needs the orgAdminBuildings query from lesson 6.3. Remove it, one query fewer on every request:
const [memberships, assignments, orgAdminBuildings] = await Promise.all([ const [memberships, assignments] = await Promise.all([
query( `SELECT s.id AS building_id, s.organisation_id FROM buildings s JOIN memberships m ON m.organisation_id = s.organisation_id WHERE m.user_id = $1 AND m.role = 'org_admin' ORDER BY s.id`, [userId], ), ]); return { memberships: memberships.rows, assignments: assignments.rows, orgAdminBuildings: orgAdminBuildings.rows }; return { memberships: memberships.rows, assignments: assignments.rows };
Show the whole src/models/access.js after this change
import { query } from '../db.js'; // The current user's ACTIVE memberships and building role assignments.export async function loadAccess(userId) { const [memberships, assignments] = await Promise.all([ query( `SELECT m.organisation_id, o.name AS organisation_name, m.role FROM memberships m JOIN organisations o ON o.id = m.organisation_id WHERE m.user_id = $1 ORDER BY o.name`, [userId], ), query( `SELECT a.building_id, s.name AS building_name, s.organisation_id, a.role FROM building_role_assignments a JOIN buildings s ON s.id = a.building_id WHERE a.user_id = $1 AND a.revoked_at IS NULL ORDER BY s.id, a.role`, [userId], ), ]); return { memberships: memberships.rows, assignments: assignments.rows };}import { query } from '../db.js';
// The current user's ACTIVE memberships and building role assignments.
export async function loadAccess(userId) {
const [memberships, assignments] = await Promise.all([
query(
`SELECT m.organisation_id, o.name AS organisation_name, m.role
FROM memberships m
JOIN organisations o ON o.id = m.organisation_id
WHERE m.user_id = $1
ORDER BY o.name`,
[userId],
),
query(
`SELECT a.building_id, s.name AS building_name, s.organisation_id, a.role
FROM building_role_assignments a
JOIN buildings s ON s.id = a.building_id
WHERE a.user_id = $1 AND a.revoked_at IS NULL
ORDER BY s.id, a.role`,
[userId],
),
]);
return { memberships: memberships.rows, assignments: assignments.rows };
}
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) (520.736125ms)
✔ edit issue 101 (87.794333ms)
✔ view issue 103 (building 20) (65.649ms)
✔ edit issue 103 (reported by dave) (78.14125ms)
✔ report an issue at building 20 (94.832792ms)
✔ view issue 105 (building 30) (49.07675ms)
✔ view issue 106 (building 40, reported by bob) (39.251ms)
✔ approve inspection 201 (created by dave) (47.266333ms)
✔ approve inspection 202 (created by alice) (51.856916ms)
✔ update organisation 1 (47.523791ms)
✔ issues in each user's list come only from the expected buildings (91.218417ms)
✔ the scenario loads exactly as specified (191.470458ms)
✔ only one active assignment per user, building and role (0.885959ms)
✔ a revoked role can be granted again (1.461167ms)
✔ the My access page shows what the server loaded (71.810334ms)
✔ a correct login creates a session and shows the user (268.843042ms)
✔ a wrong password or unknown email gets the same 401 (52.6455ms)
✔ registration validates, creates a user, and logs them in (47.003042ms)
✔ registering an existing email is a field error (31.76875ms)
✔ logout destroys the session (48.652084ms)
✖ allow: a permit matched and nothing forbade it (224.217791ms)
✔ explicit deny: a forbid overrides a matching permit (6.416458ms)
✔ implicit deny: no permit matched (5.276875ms)
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.689708ms)
✔ unknown actions throw instead of deciding (1.714542ms)
✔ a building can be created inside an organisation (307.581083ms)
✔ a duplicate building name in the same organisation is a field error (11.979833ms)
Show 137 more lines
✔ the same building name is allowed in another organisation (16.557917ms)
✔ a building with issues cannot be deleted (32.957958ms)
✔ an empty building can be deleted (25.568542ms)
✔ an organisation with buildings cannot be deleted, an empty one can (52.857959ms)
✔ a logged-in POST without a token is refused with 403 (270.633542ms)
✔ a token from another session is refused (34.932458ms)
✔ the right token in the form field works (34.748541ms)
✔ every POST form on every page carries the token (174.491417ms)
✔ the dashboard counts match the database (254.223459ms)
✔ only the buildings carol can see appear (5.563875ms)
✔ create a draft, edit it, submit it, approve it (382.470083ms)
✔ invalid transitions are refused with 409 and change nothing (40.20825ms)
✔ only drafts can be edited (19.145ms)
✔ returning a submitted inspection makes it editable again (23.94075ms)
✔ concurrent approvals: exactly one wins (63.203917ms)
✔ unknown actions are 404 (3.179667ms)
✔ the issues list contains only issues from visible buildings (534.034ms)
✔ a filter for another tenant's building returns nothing (4.051833ms)
✔ the inspections list is scoped too (9.109459ms)
✔ organisations are listed for their members only (8.893833ms)
✔ the dashboard counts only visible data (9.2175ms)
✔ view issue 101 (building 10) (530.808333ms)
✔ open the edit form for issue 101 (111.188791ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (90.168417ms)
✔ view issue 105 (building 30) and 106 (building 40) (89.994083ms)
✔ report an issue at building 20 (98.721292ms)
✔ a reporter cannot edit their own issue once it is closed (36.272833ms)
✔ only building admins may delete; refusals change nothing (38.333917ms)
✔ the edit form cannot move an issue to another building (11.0135ms)
✔ the list pages 10 at a time and reports the total (284.118042ms)
✔ pages do not overlap (16.7945ms)
✔ filters combine with AND (5.217417ms)
✔ sorting by priority puts critical first when descending (4.919041ms)
✔ unknown sort keys and SQL in the query string are ignored (27.64225ms)
✔ GET /issues lists issues from the database (5310.766208ms)
✔ GET /issues/101 shows one issue with its building (28.807667ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (39.962125ms)
✔ POST /issues re-renders the form with errors (21.971583ms)
✔ POST /issues stores the issue and redirects to it (32.647208ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (20.126083ms)
✔ the stored row has the cleaned values and ignores a client-sent status (13.39125ms)
✔ an issue time in the future is rejected (16.504666ms)
✔ GET /issues/101/edit shows the current values (24.50775ms)
✔ POST /issues/:id/edit changes the status and updated_at (15.005791ms)
✔ POST /issues/:id/delete removes the issue (21.99075ms)
✔ GET /organisations lists organisations with building counts (265.29275ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (33.000333ms)
✔ POST /organisations validates and creates (27.538042ms)
✔ POST /organisations/:id/edit renames the organisation (31.459584ms)
✔ unknown organisations are 404 (7.060875ms)
✔ every policy is valid against the schema (38.741459ms)
✖ every action used by the app is mentioned by at least one policy (1.719959ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (340.197458ms)
✔ anonymous requests are redirected to the login page (215.26ms)
✔ anonymous writes are refused and change nothing (11.479584ms)
✔ login and register pages stay public (5.800084ms)
✔ login issues a new session id (no session fixation) (31.964125ms)
✔ returnTo only follows local paths (27.160375ms)
✔ new issues and transitions record the logged-in user (96.499833ms)
✔ the session cookie has the attributes we chose (30.369417ms)
✔ organisation 1: view and update (600.81175ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (32.315208ms)
✔ building 10: view, update, delete (147.773292ms)
✔ creating buildings needs org_admin (46.437958ms)
✔ creating an organisation makes the creator its admin (21.838125ms)
✔ inspections: view 201, open the edit form for draft 203 (117.260375ms)
✔ approve inspection 201 (dave's): only building admins (39.073708ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (46.389958ms)
ℹ tests 95
ℹ suites 0
ℹ pass 93
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 16610.555917
✖ failing tests:
test at test/authz-decisions.test.js:12:1
✖ allow: a permit matched and nothing forbade it (224.217791ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
allowed: true,
reasons: [
+ 'building-admin'
- 'administer-building-data'
]
}
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/authz-decisions.test.js:14:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: { allowed: true, reasons: [ 'building-admin' ] },
expected: { allowed: true, reasons: [ 'administer-building-data' ] },
operator: 'deepStrictEqual',
diff: 'simple'
}
test at test/policies.test.js:15:1
✖ every action used by the app is mentioned by at least one policy (1.719959ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'UpdateOrganisation',
+ 'DeleteOrganisation',
+ 'CreateBuilding',
+ 'ViewBuilding',
+ 'UpdateBuilding',
+ 'DeleteBuilding',
+ 'ViewIssue',
+ 'DeleteIssue',
+ 'ViewInspection',
+ 'ReturnInspection'
+ ]
- []
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/policies.test.js:18:10)
at Test.runInAsyncScope (node:async_hooks:214:14)
at Test.run (node:internal/test_runner/test:1047:25)
at Test.processPendingSubtests (node:internal/test_runner/test:744:18)
at Test.postRun (node:internal/test_runner/test:1173:19)
at Test.run (node:internal/test_runner/test:1101:12)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [ 'UpdateOrganisation', 'DeleteOrganisation', 'CreateBuilding', 'ViewBuilding', 'UpdateBuilding', 'DeleteBuilding', 'ViewIssue', 'DeleteIssue', 'ViewInspection', 'ReturnInspection' ],
expected: [],
operator: 'deepStrictEqual',
diff: 'simple'
}
Two tests fail, and both describe the old policy names. The first is "allow: a permit matched" in test/authz-decisions.test.js: Carol's approval of inspection 202 is now allowed by building-admin, not by administer-building-data. Update the expected reason:
assert.deepEqual({ allowed: result.allowed, reasons: result.reasons }, { allowed: true, reasons: ['administer-building-data'] }); assert.deepEqual({ allowed: result.allowed, reasons: result.reasons }, { allowed: true, reasons: ['building-admin'] });
Show the whole test/authz-decisions.test.js after this change
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { authorize } from '../src/authz/authorize.js';import { findInspection } from '../src/models/inspections.js';import { findIssue } from '../src/models/issues.js';import { resetDatabase, loadUserNamed } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('allow: a permit matched and nothing forbade it', async () => { const result = authorize(await loadUserNamed('carol'), 'ApproveInspection', await findInspection(202)); assert.deepEqual({ allowed: result.allowed, reasons: result.reasons }, { allowed: true, reasons: ['building-admin'] });}); test('explicit deny: a forbid overrides a matching permit', async () => { const result = authorize(await loadUserNamed('alice'), 'ApproveInspection', await findInspection(202)); assert.deepEqual({ decision: result.decision, reasons: result.reasons, errors: result.errors }, { decision: 'deny', reasons: ['forbid-self-approval'], errors: [] });}); test('implicit deny: no permit matched', async () => { const result = authorize(await loadUserNamed('nora'), 'ViewIssue', await findIssue(101)); assert.deepEqual({ decision: result.decision, reasons: result.reasons }, { decision: 'deny', reasons: [] });}); test('failure: a row that does not fit the schema is never allowed', async () => { const broken = { ...(await findInspection(201)), status: 7 }; const result = authorize(await loadUserNamed('alice'), 'ApproveInspection', broken); assert.equal(result.allowed, false); assert.equal(result.decision, 'failure'); assert.match(result.errors[0], /status/);}); test('unknown actions throw instead of deciding', async () => { const alice = await loadUserNamed('alice'); assert.throws(() => authorize(alice, 'LaunchRocket', { id: 1 }), /No Cedar resource type/);});import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { pool } from '../src/db.js';
import { authorize } from '../src/authz/authorize.js';
import { findInspection } from '../src/models/inspections.js';
import { findIssue } from '../src/models/issues.js';
import { resetDatabase, loadUserNamed } from './helpers.js';
before(resetDatabase);
after(() => pool.end());
test('allow: a permit matched and nothing forbade it', async () => {
const result = authorize(await loadUserNamed('carol'), 'ApproveInspection', await findInspection(202));
assert.deepEqual({ allowed: result.allowed, reasons: result.reasons }, { allowed: true, reasons: ['building-admin'] });
});
test('explicit deny: a forbid overrides a matching permit', async () => {
const result = authorize(await loadUserNamed('alice'), 'ApproveInspection', await findInspection(202));
assert.deepEqual({ decision: result.decision, reasons: result.reasons, errors: result.errors }, { decision: 'deny', reasons: ['forbid-self-approval'], errors: [] });
});
test('implicit deny: no permit matched', async () => {
const result = authorize(await loadUserNamed('nora'), 'ViewIssue', await findIssue(101));
assert.deepEqual({ decision: result.decision, reasons: result.reasons }, { decision: 'deny', reasons: [] });
});
test('failure: a row that does not fit the schema is never allowed', async () => {
const broken = { ...(await findInspection(201)), status: 7 };
const result = authorize(await loadUserNamed('alice'), 'ApproveInspection', broken);
assert.equal(result.allowed, false);
assert.equal(result.decision, 'failure');
assert.match(result.errors[0], /status/);
});
test('unknown actions throw instead of deciding', async () => {
const alice = await loadUserNamed('alice');
assert.throws(() => authorize(alice, 'LaunchRocket', { id: 1 }), /No Cedar resource type/);
});
The second is "every action used by the app is mentioned by at least one policy" from lesson 6.5. It searched policy text for Action::"ViewBuilding", but ViewBuilding is now covered through its group ReadBuildingData. The check is still worth having; it must follow group membership. Cedar can give us the schema as JSON, where each action lists the groups it is memberOf:
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}"`));test('every action used by the app is mentioned by a policy, directly or through its group', () => { const { schema, policies } = loadPolicyStore(); const text = Object.values(policies).join('\n'); const actions = cedar.schemaToJson(schema).json.Caretaker.actions; const missing = Object.keys(RESOURCE_TYPES).filter((action) => { const names = [action, ...(actions[action].memberOf ?? []).map((group) => group.id)]; return !names.some((name) => text.includes(`Action::"${name}"`)); }); 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 a policy, directly or through its group', () => { const { schema, policies } = loadPolicyStore(); const text = Object.values(policies).join('\n'); const actions = cedar.schemaToJson(schema).json.Caretaker.actions; const missing = Object.keys(RESOURCE_TYPES).filter((action) => { const names = [action, ...(actions[action].memberOf ?? []).map((group) => group.id)]; return !names.some((name) => text.includes(`Action::"${name}"`)); }); 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 a policy, directly or through its group', () => {
const { schema, policies } = loadPolicyStore();
const text = Object.values(policies).join('\n');
const actions = cedar.schemaToJson(schema).json.Caretaker.actions;
const missing = Object.keys(RESOURCE_TYPES).filter((action) => {
const names = [action, ...(actions[action].memberOf ?? []).map((group) => group.id)];
return !names.some((name) => text.includes(`Action::"${name}"`));
});
assert.deepEqual(missing, []);
});
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) (530.056916ms)
✔ edit issue 101 (87.506416ms)
✔ view issue 103 (building 20) (65.537625ms)
✔ edit issue 103 (reported by dave) (77.251875ms)
✔ report an issue at building 20 (88.739541ms)
✔ view issue 105 (building 30) (38.528458ms)
✔ view issue 106 (building 40, reported by bob) (32.377875ms)
✔ approve inspection 201 (created by dave) (37.775875ms)
✔ approve inspection 202 (created by alice) (47.807ms)
✔ update organisation 1 (48.777ms)
✔ issues in each user's list come only from the expected buildings (109.905083ms)
✔ the scenario loads exactly as specified (211.541792ms)
✔ only one active assignment per user, building and role (0.868041ms)
✔ a revoked role can be granted again (1.29075ms)
✔ the My access page shows what the server loaded (74.318916ms)
✔ a correct login creates a session and shows the user (268.811708ms)
✔ a wrong password or unknown email gets the same 401 (52.939542ms)
✔ registration validates, creates a user, and logs them in (51.617333ms)
✔ registering an existing email is a field error (32.114917ms)
✔ logout destroys the session (51.499667ms)
✔ allow: a permit matched and nothing forbade it (211.305041ms)
✔ explicit deny: a forbid overrides a matching permit (5.63875ms)
✔ implicit deny: no permit matched (5.2775ms)
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.360625ms)
✔ unknown actions throw instead of deciding (1.745166ms)
✔ a building can be created inside an organisation (291.068292ms)
✔ a duplicate building name in the same organisation is a field error (12.080334ms)
Show 76 more lines
✔ the same building name is allowed in another organisation (16.10125ms)
✔ a building with issues cannot be deleted (31.344416ms)
✔ an empty building can be deleted (20.839625ms)
✔ an organisation with buildings cannot be deleted, an empty one can (60.097583ms)
✔ a logged-in POST without a token is refused with 403 (281.602875ms)
✔ a token from another session is refused (36.624292ms)
✔ the right token in the form field works (34.541625ms)
✔ every POST form on every page carries the token (187.533291ms)
✔ the dashboard counts match the database (267.642541ms)
✔ only the buildings carol can see appear (6.949708ms)
✔ create a draft, edit it, submit it, approve it (372.903167ms)
✔ invalid transitions are refused with 409 and change nothing (37.407375ms)
✔ only drafts can be edited (19.71675ms)
✔ returning a submitted inspection makes it editable again (22.843667ms)
✔ concurrent approvals: exactly one wins (63.9665ms)
✔ unknown actions are 404 (3.147167ms)
✔ the issues list contains only issues from visible buildings (538.914834ms)
✔ a filter for another tenant's building returns nothing (3.679833ms)
✔ the inspections list is scoped too (9.333083ms)
✔ organisations are listed for their members only (8.213666ms)
✔ the dashboard counts only visible data (7.546208ms)
✔ view issue 101 (building 10) (518.420291ms)
✔ open the edit form for issue 101 (86.568333ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (80.82375ms)
✔ view issue 105 (building 30) and 106 (building 40) (83.737875ms)
✔ report an issue at building 20 (77.405875ms)
✔ a reporter cannot edit their own issue once it is closed (27.497584ms)
✔ only building admins may delete; refusals change nothing (33.566458ms)
✔ the edit form cannot move an issue to another building (8.9435ms)
✔ the list pages 10 at a time and reports the total (254.63ms)
✔ pages do not overlap (16.723084ms)
✔ filters combine with AND (5.465833ms)
✔ sorting by priority puts critical first when descending (5.0095ms)
✔ unknown sort keys and SQL in the query string are ignored (30.977667ms)
✔ GET /issues lists issues from the database (299.6245ms)
✔ GET /issues/101 shows one issue with its building (23.278125ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (16.51075ms)
✔ POST /issues re-renders the form with errors (18.846458ms)
✔ POST /issues stores the issue and redirects to it (20.441875ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (16.617208ms)
✔ the stored row has the cleaned values and ignores a client-sent status (9.530542ms)
✔ an issue time in the future is rejected (16.366167ms)
✔ GET /issues/101/edit shows the current values (23.431625ms)
✔ POST /issues/:id/edit changes the status and updated_at (15.543959ms)
✔ POST /issues/:id/delete removes the issue (25.135125ms)
✔ GET /organisations lists organisations with building counts (279.927541ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (35.887916ms)
✔ POST /organisations validates and creates (28.485542ms)
✔ POST /organisations/:id/edit renames the organisation (37.20925ms)
✔ unknown organisations are 404 (13.671833ms)
✔ every policy is valid against the schema (30.5635ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (8.89125ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (358.125709ms)
✔ anonymous requests are redirected to the login page (224.035084ms)
✔ anonymous writes are refused and change nothing (10.689917ms)
✔ login and register pages stay public (6.762041ms)
✔ login issues a new session id (no session fixation) (32.656083ms)
✔ returnTo only follows local paths (28.394625ms)
✔ new issues and transitions record the logged-in user (112.240208ms)
✔ the session cookie has the attributes we chose (40.873166ms)
✔ organisation 1: view and update (623.608917ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (31.007958ms)
✔ building 10: view, update, delete (130.983958ms)
✔ creating buildings needs org_admin (43.396417ms)
✔ creating an organisation makes the creator its admin (18.234667ms)
✔ inspections: view 201, open the edit form for draft 203 (118.013167ms)
✔ approve inspection 201 (dave's): only building admins (41.177709ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (77.152041ms)
ℹ tests 95
ℹ suites 0
ℹ pass 95
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 11527.774292
Same 95 tests, same behaviour, new model. Look at Carol now:
npm run authz:explain -- carol ViewIssue 103 | sed -n '/== 4/,$p'
== 4. entities built by the mapper
[
{
"uid": {
"type": "Caretaker::User",
"id": "3"
},
"attrs": {
"viewerBuildings": [],
"reporterBuildings": [],
"inspectorBuildings": [],
"adminBuildings": [],
"memberOrganisations": [
{
"type": "Caretaker::Organisation",
"id": "1"
}
],
"adminOrganisations": [
{
"type": "Caretaker::Organisation",
"id": "1"
}
]
},
"parents": []
},
{
"uid": {
"type": "Caretaker::Issue",
"id": "103"
},
"attrs": {
"building": {
"type": "Caretaker::Building",
"id": "20"
},
"status": "open",
"priority": "medium",
"reportedBy": {
Show 70 more lines
"type": "Caretaker::User",
"id": "4"
}
},
"parents": [
{
"type": "Caretaker::Building",
"id": "20"
}
]
},
{
"uid": {
"type": "Caretaker::Building",
"id": "20"
},
"attrs": {
"organisation": {
"type": "Caretaker::Organisation",
"id": "1"
}
},
"parents": [
{
"type": "Caretaker::Organisation",
"id": "1"
}
]
},
{
"uid": {
"type": "Caretaker::Organisation",
"id": "1"
},
"attrs": {},
"parents": []
}
]
== 5. request
{
"principal": {
"type": "Caretaker::User",
"id": "3"
},
"action": {
"type": "Caretaker::Action",
"id": "ViewIssue"
},
"resource": {
"type": "Caretaker::Issue",
"id": "103"
},
"context": {}
}
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"building-read"
],
"errors": []
}
},
"warnings": []
}
In section 4, Carol's building sets are all empty; adminOrganisations is [Organisation::"1"]. Issue 103's parent is Building::"20", whose parent is Organisation::"1". Cedar walked that chain for resource in principal.adminOrganisations, and building-read allowed it. The rule "org admins inherit every building" now appears in a policy you can read, and in the reason of the decision.
Alice across two buildings
Alice holds two facts: adminBuildings = [Building::"10"] and viewerBuildings = [Building::"20"]. Here is how the policies combine them, with no role per building anywhere in the code:
| Alice asks | Building 10 (admin) | Building 20 (viewer) |
|---|---|---|
ViewIssue (in ReadBuildingData) |
allow: building-read (in adminBuildings) |
allow: building-read (in viewerBuildings) |
UpdateIssue (in AdministerBuilding) |
allow: building-admin |
deny: no permit |
CreateIssue (in AdministerBuilding) |
allow: building-admin |
deny: not a reporter or admin there |
ApproveInspection on her own inspection 202 |
deny: forbid-self-approval |
n/a |
The explorer below evaluates the final policies with the real engine for every user, building, issue and inspection of the scenario. Revoke one of Alice's roles and watch which cells change:
Check two cells yourself:
npm run authz:explain -- alice UpdateIssue 103 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "deny",
"diagnostics": {
"reason": [],
"errors": []
}
},
"warnings": []
}
npm run authz:explain -- alice UpdateIssue 101 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"building-admin"
],
"errors": []
}
},
"warnings": []
}
Experiment
Parents only work if the parent entities are in the entity list. Cedar does not fetch anything; an ancestor it was not given does not exist for it.
buildAuthorizationCall forgot to include the building entity, would Carol's request for issue 103 be allowed, denied, or an error?node --env-file=.env --input-type=module -e "
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { pool } 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 { loadPolicyStore } from './src/authz/policy-store.js';
import { buildAuthorizationCall } from './src/authz/request.js';
const carol = await findUserById(3);
carol.access = await loadAccess(3);
const call = buildAuthorizationCall(carol, 'ViewIssue', await findIssue(103));
const { schema, policies } = loadPolicyStore();
const decide = (entities) => cedar.isAuthorized({ ...call, entities, schema, validateRequest: true, policies: { staticPolicies: policies } }).response;
const full = decide(call.entities);
const partial = decide(call.entities.filter((e) => e.uid.type !== 'Caretaker::Building'));
console.log('with the building entity:', full.decision, JSON.stringify(full.diagnostics));
console.log('without the building entity:', partial.decision, JSON.stringify(partial.diagnostics));
await pool.end();
"
with the building entity: allow {"reason":["building-read"],"errors":[]}
without the building entity: deny {"reason":[],"errors":[]}
Reveal Answer
Denied, without any error. Issue 103 still says its parent is Building::"20", but without the building entity Cedar cannot know that building 20 is inside organisation 1. in simply evaluates to false. This is the quiet failure mode of hierarchies: an incomplete entity list produces wrong denials (or, with a forbid that relies on in, wrong allows), not errors. The access matrix test would catch this one for Carol; the general lesson is that building the right slice of entities is part of authorization, and must be tested like it.
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) (470.832166ms)
✔ edit issue 101 (84.642084ms)
✔ view issue 103 (building 20) (66.706ms)
✔ edit issue 103 (reported by dave) (79.102042ms)
✔ report an issue at building 20 (98.758791ms)
✔ view issue 105 (building 30) (51.09225ms)
✔ view issue 106 (building 40, reported by bob) (41.0515ms)
✔ approve inspection 201 (created by dave) (41.575583ms)
✔ approve inspection 202 (created by alice) (54.320875ms)
✔ update organisation 1 (49.493708ms)
✔ issues in each user's list come only from the expected buildings (99.830417ms)
✔ the scenario loads exactly as specified (204.619542ms)
✔ only one active assignment per user, building and role (0.89175ms)
✔ a revoked role can be granted again (0.90175ms)
✔ the My access page shows what the server loaded (72.338709ms)
✔ a correct login creates a session and shows the user (268.307875ms)
✔ a wrong password or unknown email gets the same 401 (54.798333ms)
✔ registration validates, creates a user, and logs them in (51.280291ms)
✔ registering an existing email is a field error (32.542166ms)
✔ logout destroys the session (53.941583ms)
✔ allow: a permit matched and nothing forbade it (212.92725ms)
✔ explicit deny: a forbid overrides a matching permit (5.58225ms)
✔ implicit deny: no permit matched (5.127125ms)
authz problem {
user: 1,
action: 'ApproveInspection',
resource: 'Inspection::201',
decision: 'failure',
errors: [
'entity does not conform to the schema: in attribute `status` on `Caretaker::Inspection::"201"`, type mismatch: value was expected to have type string, but it actually has type long: `7`'
]
}
✔ failure: a row that does not fit the schema is never allowed (7.0185ms)
✔ unknown actions throw instead of deciding (1.733208ms)
✔ a building can be created inside an organisation (298.324541ms)
✔ a duplicate building name in the same organisation is a field error (12.22075ms)
Show 76 more lines
✔ the same building name is allowed in another organisation (14.667625ms)
✔ a building with issues cannot be deleted (34.994375ms)
✔ an empty building can be deleted (21.210334ms)
✔ an organisation with buildings cannot be deleted, an empty one can (51.425375ms)
✔ a logged-in POST without a token is refused with 403 (272.884583ms)
✔ a token from another session is refused (36.70475ms)
✔ the right token in the form field works (34.389459ms)
✔ every POST form on every page carries the token (169.621958ms)
✔ the dashboard counts match the database (273.592667ms)
✔ only the buildings carol can see appear (4.810333ms)
✔ create a draft, edit it, submit it, approve it (384.037583ms)
✔ invalid transitions are refused with 409 and change nothing (35.748125ms)
✔ only drafts can be edited (16.472209ms)
✔ returning a submitted inspection makes it editable again (19.937583ms)
✔ concurrent approvals: exactly one wins (64.741125ms)
✔ unknown actions are 404 (3.622584ms)
✔ the issues list contains only issues from visible buildings (560.922125ms)
✔ a filter for another tenant's building returns nothing (3.91825ms)
✔ the inspections list is scoped too (9.797917ms)
✔ organisations are listed for their members only (9.078958ms)
✔ the dashboard counts only visible data (7.115458ms)
✔ view issue 101 (building 10) (512.678208ms)
✔ open the edit form for issue 101 (76.921917ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (80.570167ms)
✔ view issue 105 (building 30) and 106 (building 40) (87.957ms)
✔ report an issue at building 20 (96.624917ms)
✔ a reporter cannot edit their own issue once it is closed (32.955917ms)
✔ only building admins may delete; refusals change nothing (43.279292ms)
✔ the edit form cannot move an issue to another building (12.31225ms)
✔ the list pages 10 at a time and reports the total (284.067541ms)
✔ pages do not overlap (16.9125ms)
✔ filters combine with AND (5.536292ms)
✔ sorting by priority puts critical first when descending (4.852209ms)
✔ unknown sort keys and SQL in the query string are ignored (28.73575ms)
✔ GET /issues lists issues from the database (277.298042ms)
✔ GET /issues/101 shows one issue with its building (22.558417ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (17.593042ms)
✔ POST /issues re-renders the form with errors (17.035709ms)
✔ POST /issues stores the issue and redirects to it (21.574ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (18.655375ms)
✔ the stored row has the cleaned values and ignores a client-sent status (12.706416ms)
✔ an issue time in the future is rejected (16.32ms)
✔ GET /issues/101/edit shows the current values (21.784667ms)
✔ POST /issues/:id/edit changes the status and updated_at (18.491875ms)
✔ POST /issues/:id/delete removes the issue (27.183458ms)
✔ GET /organisations lists organisations with building counts (256.736708ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (30.943125ms)
✔ POST /organisations validates and creates (26.822917ms)
✔ POST /organisations/:id/edit renames the organisation (35.203667ms)
✔ unknown organisations are 404 (11.818958ms)
✔ every policy is valid against the schema (30.278541ms)
✔ every action used by the app is mentioned by a policy, directly or through its group (8.502042ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (341.971375ms)
✔ anonymous requests are redirected to the login page (211.201208ms)
✔ anonymous writes are refused and change nothing (10.222583ms)
✔ login and register pages stay public (7.638709ms)
✔ login issues a new session id (no session fixation) (32.052041ms)
✔ returnTo only follows local paths (32.174125ms)
✔ new issues and transitions record the logged-in user (101.043542ms)
✔ the session cookie has the attributes we chose (31.502959ms)
✔ organisation 1: view and update (578.005542ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (33.062209ms)
✔ building 10: view, update, delete (159.135167ms)
✔ creating buildings needs org_admin (49.059458ms)
✔ creating an organisation makes the creator its admin (21.048333ms)
✔ inspections: view 201, open the edit form for draft 203 (110.875167ms)
✔ approve inspection 201 (dave's): only building admins (38.482458ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (44.747458ms)
ℹ tests 95
ℹ suites 0
ℹ pass 95
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 11393.355459
git add -A
git commit -m "Facts, parents and action groups"
[main f2365ae] Facts, parents and action groups
21 files changed, 65 insertions(+), 91 deletions(-)
delete mode 100644 src/authz/policies/administer-building-data.cedar
delete mode 100644 src/authz/policies/administer-organisation.cedar
create mode 100644 src/authz/policies/building-admin.cedar
create mode 100644 src/authz/policies/building-read.cedar
delete mode 100644 src/authz/policies/create-inspection.cedar
delete mode 100644 src/authz/policies/create-issue.cedar
delete mode 100644 src/authz/policies/delete-building.cedar
create mode 100644 src/authz/policies/inspector-create-inspection.cedar
rename src/authz/policies/{own-inspections.cedar => inspector-own-inspections.cedar} (80%)
create mode 100644 src/authz/policies/org-admin.cedar
rename src/authz/policies/{view-organisation.cedar => org-member.cedar} (66%)
create mode 100644 src/authz/policies/reporter-create-issue.cedar
rename src/authz/policies/{update-own-issue.cedar => reporter-own-issues.cedar} (80%)
delete mode 100644 src/authz/policies/update-building.cedar
delete mode 100644 src/authz/policies/view-building-data.cedar
delete mode 100644 src/authz/policies/view-building.cedar
Symptom unrecognized action ... ReadBuildingData or validation errors about groups
An action group must be declared (action ReadBuildingData;) before any action is put in it, and policies must refer to it as Caretaker::Action::"ReadBuildingData".
Symptom Carol is denied everything after the change
Check that buildingEntity still sets parents: [ref('Organisation', organisation_id)], and that buildAuthorizationCall includes the building and organisation entities for issues and inspections.
Recap and next step
The mapper now reports only facts: one set per role, and the organisations from memberships. Inheritance is a parent chain that Cedar follows with in; the role ladder is action-group membership in the schema. Nine policies describe the role table directly, and the decision reasons name them. We also saw that hierarchies depend on a complete entity slice.
There is a third way to model "Alice is admin of building 10": a policy per assignment, generated from a template. Next lesson builds a small, real example and compares it with what we have.
Open the checkpoint files for lesson 7.1 (separate page; only files from this lesson and earlier)