Module 6 · Introduce Cedar
6.3 From database rows to Cedar entities
Build Cedar entities from the rows the app already loads, assemble a complete authorization call, trace one request with real values, and prove the Cedar answer matches the JavaScript rules for every user and issue.
Starting point
The policy store (schema plus view-issue.cedar) validates. The app still decides with can() in JavaScript. Cedar has only ever seen hand-typed entities.
Outcome
src/authz/entities.js (new: the entity mapper)src/authz/request.js (new: builds a complete isAuthorized call)src/models/access.js (+ the buildings a user administers through an organisation)scripts/authz-explain.js (new: npm run authz:explain -- alice ViewIssue 101)test/cedar-parity.test.js (new: Cedar and can() agree on ViewIssue for every user and issue)You can show, for any user and issue, every value that goes into Cedar and where it came from.
The problem
Cedar needs the principal and the resource as entities with attributes. Where does principal.issueViewerBuildings come from? Not from the request: the browser sends only a session cookie and an issue ID. It must be computed on the server from rows we trust. That code, the entity mapper, is the most security-sensitive code in this module: if it builds a wrong attribute, Cedar will faithfully compute a wrong answer.
There is one gap in our data. Carol has no building assignments; her access to buildings 10 and 20 comes from org_admin on organisation 1. To list her viewable buildings, we must know which buildings belong to the organisations she administers. req.user.access does not contain that yet.
Build it
1. Load the buildings a user administers through an organisation
Add a third query to loadAccess in src/models/access.js:
const [memberships, assignments] = await Promise.all([ const [memberships, assignments, orgAdminBuildings] = await Promise.all([
WHERE a.user_id = $1 AND a.revoked_at IS NULL ORDER BY s.id, a.role`, [userId], ), 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 }; return { memberships: memberships.rows, assignments: assignments.rows, orgAdminBuildings: orgAdminBuildings.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, orgAdminBuildings] = 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], ), 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 };}import { query } from '../db.js';
// The current user's ACTIVE memberships and building role assignments.
export async function loadAccess(userId) {
const [memberships, assignments, orgAdminBuildings] = 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],
),
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 };
}
2. The entity mapper
Create 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) };} // Version 1: one derived attribute. A building's issues are viewable if the user// holds any active role at the building, or is org_admin of the building's organisation.export function userEntity(user) { const viewable = new Set([ ...user.access.assignments.map((a) => a.building_id), ...user.access.orgAdminBuildings.map((s) => s.building_id), ]); return { uid: ref('User', user.id), attrs: { issueViewerBuildings: [...viewable].sort((a, b) => a - b).map((id) => ref('Building', 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)] };}- IDs become strings. Database integer
101becomes"101".ref('Building', 10)andref('Building', '10')produce the same reference. issueViewerBuildingsis the union of the user's assigned buildings and the buildings they administer through an organisation. It is sorted only to make output easy to compare.- Revoked roles never appear, because
loadAccessfiltered them withrevoked_at IS NULL. The mapper cannot include what it was never given. reportedByis omitted when it isnull. The schema declared it optional (reportedBy?: User). Cedar has nonull; an attribute is either present with a value of the right type, or absent.- Parents. An issue's parent is its building; a building's parent is its organisation. The schema allowed these (
Issue in [Building],Building in [Organisation]). No policy uses them yet; Module 7 does.
3. A complete authorization call
The mapper builds single entities. A request needs the principal, the action, the resource, the context, and every entity a policy might look at. Create src/authz/request.js:
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity } from './entities.js'; // Which entity type each action's resource is. Grows as actions move to Cedar.export const RESOURCE_TYPES = { ViewIssue: 'Issue',}; // 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 entities = [userEntity(user)]; let resource; if (type === 'Issue') { const issue = issueEntity(row); entities.push(issue, buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id)); resource = issue.uid; } return { principal: ref('User', user.id), action: { type: 'Caretaker::Action', id: action }, resource, context: {}, entities, };}The resource's building and organisation come from the issue row (building_id, and organisation_id from the join with buildings in findIssue). The URL only told us which issue to load.
4. An explain command
To remove the last black box, write a script that shows, for one user, action and issue, every value from the database rows to Cedar's answer. Create scripts/authz-explain.js:
// Usage: npm run authz:explain -- <user> <action> <issueId>// 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 { loadPolicyStore } from '../src/authz/policy-store.js';import { buildAuthorizationCall } from '../src/authz/request.js'; const [name, action, issueId] = process.argv.slice(2);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 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 call = buildAuthorizationCall(user, action, issue); 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();}npm pkg set scripts.authz:explain="node --env-file=.env scripts/authz-explain.js"
Run and inspect
Explain the request behind GET /issues/101 for Alice:
npm run authz:explain -- alice ViewIssue 101
> caretaker@1.0.0 authz:explain
> node --env-file=.env scripts/authz-explain.js alice ViewIssue 101
== 1. users row (the session holds only this id)
{
"id": 1,
"email": "alice@example.test"
}
== 2. access rows loaded for this request
{
"memberships": [
{
"organisation_id": 1,
"organisation_name": "Liffey Estates",
"role": "member"
}
],
"assignments": [
{
"building_id": 10,
"building_name": "Dublin Offices",
"organisation_id": 1,
"role": "building_admin"
},
{
"building_id": 20,
"building_name": "Cork Apartments",
"organisation_id": 1,
"role": "viewer"
}
],
"orgAdminBuildings": []
}
== 3. issue row
{
"id": 101,
Show 111 more lines
"building_id": 10,
"organisation_id": 1,
"reported_by": 1,
"status": "open",
"priority": "high"
}
== 4. entities built by the mapper
[
{
"uid": {
"type": "Caretaker::User",
"id": "1"
},
"attrs": {
"issueViewerBuildings": [
{
"type": "Caretaker::Building",
"id": "10"
},
{
"type": "Caretaker::Building",
"id": "20"
}
]
},
"parents": []
},
{
"uid": {
"type": "Caretaker::Issue",
"id": "101"
},
"attrs": {
"building": {
"type": "Caretaker::Building",
"id": "10"
},
"status": "open",
"priority": "high",
"reportedBy": {
"type": "Caretaker::User",
"id": "1"
}
},
"parents": [
{
"type": "Caretaker::Building",
"id": "10"
}
]
},
{
"uid": {
"type": "Caretaker::Building",
"id": "10"
},
"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": "1"
},
"action": {
"type": "Caretaker::Action",
"id": "ViewIssue"
},
"resource": {
"type": "Caretaker::Issue",
"id": "101"
},
"context": {}
}
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"view-issue"
],
"errors": []
}
},
"warnings": []
}
Follow the numbers in the output; this is the whole chain with real values:
- The session cookie led to a session row holding
userId: 1(lesson 4.2). That ID is the only thing about the user the request provided. loadAccess(1)returned two active assignments,10:building_adminand20:viewer, and noorgAdminBuildings.findIssue(101)returnedbuilding_id: 10,organisation_id: 1,reported_by: 1.- The mapper produced
User::"1"withissueViewerBuildings: [Building::"10", Building::"20"], andIssue::"101"withbuilding: Building::"10"and parentBuilding::"10", whose parent isOrganisation::"1". - The request: principal
User::"1", actionViewIssue, resourceIssue::"101", empty context. - Cedar evaluated
principal.issueViewerBuildings.contains(resource.building): does[Building::"10", Building::"20"]containBuilding::"10"? Yes. Decisionallow, reasonview-issue.
Explore the same mapping interactively. Pick a user and a resource, then hover or focus any attribute of an entity to see the database row and column it came from. Revoked rows are shown greyed out, because loadAccess never returns them:
The JavaScript equivalent of the policy is user.issueViewerBuildings.some((s) => s.id === issue.building.id). One difference matters: Cedar compares entity references by type and ID. Building::"10" and Organisation::"10" are different, where a careless JavaScript comparison of raw numbers would treat them as equal.
Now Carol, whose rights come from her organisation, not from assignments:
npm run authz:explain -- carol ViewIssue 103
> caretaker@1.0.0 authz:explain
> node --env-file=.env scripts/authz-explain.js carol ViewIssue 103
== 1. users row (the session holds only this id)
{
"id": 3,
"email": "carol@example.test"
}
== 2. access rows loaded for this request
{
"memberships": [
{
"organisation_id": 1,
"organisation_name": "Liffey Estates",
"role": "org_admin"
}
],
"assignments": [],
"orgAdminBuildings": [
{
"building_id": 10,
"organisation_id": 1
},
{
"building_id": 20,
"organisation_id": 1
}
]
}
== 3. issue row
{
"id": 103,
"building_id": 20,
"organisation_id": 1,
"reported_by": 4,
"status": "open",
Show 107 more lines
"priority": "medium"
}
== 4. entities built by the mapper
[
{
"uid": {
"type": "Caretaker::User",
"id": "3"
},
"attrs": {
"issueViewerBuildings": [
{
"type": "Caretaker::Building",
"id": "10"
},
{
"type": "Caretaker::Building",
"id": "20"
}
]
},
"parents": []
},
{
"uid": {
"type": "Caretaker::Issue",
"id": "103"
},
"attrs": {
"building": {
"type": "Caretaker::Building",
"id": "20"
},
"status": "open",
"priority": "medium",
"reportedBy": {
"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": [
"view-issue"
],
"errors": []
}
},
"warnings": []
}
In section 2, assignments is empty and orgAdminBuildings lists buildings 10 and 20. In section 4 her issueViewerBuildings is the same as Alice's. The mapper applied the inheritance rule, in JavaScript, before Cedar saw anything. Keep that observation: it comes back in Module 7.
And Ravi, whose role was revoked:
npm run authz:explain -- ravi ViewIssue 105
> caretaker@1.0.0 authz:explain
> node --env-file=.env scripts/authz-explain.js ravi ViewIssue 105
== 1. users row (the session holds only this id)
{
"id": 6,
"email": "ravi@example.test"
}
== 2. access rows loaded for this request
{
"memberships": [
{
"organisation_id": 2,
"organisation_name": "Harbour Lets",
"role": "member"
}
],
"assignments": [],
"orgAdminBuildings": []
}
== 3. issue row
{
"id": 105,
"building_id": 30,
"organisation_id": 2,
"reported_by": 2,
"status": "open",
"priority": "critical"
}
== 4. entities built by the mapper
[
{
"uid": {
"type": "Caretaker::User",
"id": "6"
Show 87 more lines
},
"attrs": {
"issueViewerBuildings": []
},
"parents": []
},
{
"uid": {
"type": "Caretaker::Issue",
"id": "105"
},
"attrs": {
"building": {
"type": "Caretaker::Building",
"id": "30"
},
"status": "open",
"priority": "critical",
"reportedBy": {
"type": "Caretaker::User",
"id": "2"
}
},
"parents": [
{
"type": "Caretaker::Building",
"id": "30"
}
]
},
{
"uid": {
"type": "Caretaker::Building",
"id": "30"
},
"attrs": {
"organisation": {
"type": "Caretaker::Organisation",
"id": "2"
}
},
"parents": [
{
"type": "Caretaker::Organisation",
"id": "2"
}
]
},
{
"uid": {
"type": "Caretaker::Organisation",
"id": "2"
},
"attrs": {},
"parents": []
}
]
== 5. request
{
"principal": {
"type": "Caretaker::User",
"id": "6"
},
"action": {
"type": "Caretaker::Action",
"id": "ViewIssue"
},
"resource": {
"type": "Caretaker::Issue",
"id": "105"
},
"context": {}
}
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "deny",
"diagnostics": {
"reason": [],
"errors": []
}
},
"warnings": []
}
His issueViewerBuildings is an empty set. The revoked row is in the database, but loadAccess never returned it.
Experiment
Before we let Cedar decide anything in the app, prove that it would decide the same as can(). This test compares both, for every seeded user and every issue:
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';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 { can } from '../src/authz/rules.js';import { loadPolicyStore } from '../src/authz/policy-store.js';import { buildAuthorizationCall } from '../src/authz/request.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('Cedar and can() agree on ViewIssue for every user and issue', async () => { const { schema, policies } = loadPolicyStore(); const { rows: issueRows } = await pool.query('SELECT id FROM issues ORDER BY id'); const mismatches = []; let checked = 0; for (let userId = 1; userId <= 6; userId++) { const user = await findUserById(userId); user.access = await loadAccess(userId); for (const { id } of issueRows) { const issue = await findIssue(id); const answer = cedar.isAuthorized({ ...buildAuthorizationCall(user, 'ViewIssue', issue), schema, validateRequest: true, policies: { staticPolicies: policies } }); assert.equal(answer.type, 'success', JSON.stringify(answer.errors)); const cedarAllows = answer.response.decision === 'allow'; if (cedarAllows !== can(user, 'ViewIssue', issue)) mismatches.push(`user ${userId} issue ${id}`); checked++; } } assert.deepEqual(mismatches, []); assert.equal(checked, 6 * 30);});orgAdminBuildings, how many would disagree, and for whom?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) (432.717ms)
✔ edit issue 101 (17.751375ms)
✔ view issue 103 (building 20) (17.32925ms)
✔ edit issue 103 (reported by dave) (16.936375ms)
✔ report an issue at building 20 (17.687958ms)
✔ view issue 105 (building 30) (17.153458ms)
✔ view issue 106 (building 40, reported by bob) (15.254042ms)
✔ approve inspection 201 (created by dave) (15.331917ms)
✔ approve inspection 202 (created by alice) (15.083917ms)
✔ update organisation 1 (14.425209ms)
✔ issues in each user's list come only from the expected buildings (98.68975ms)
✔ the scenario loads exactly as specified (210.338958ms)
✔ only one active assignment per user, building and role (1.035916ms)
✔ a revoked role can be granted again (0.830292ms)
✔ the My access page shows what the server loaded (72.745167ms)
✔ a correct login creates a session and shows the user (256.565541ms)
✔ a wrong password or unknown email gets the same 401 (54.862084ms)
✔ registration validates, creates a user, and logs them in (43.568166ms)
✔ registering an existing email is a field error (30.780458ms)
✔ logout destroys the session (50.650875ms)
✔ a building can be created inside an organisation (269.18325ms)
✔ a duplicate building name in the same organisation is a field error (4.527041ms)
✔ the same building name is allowed in another organisation (9.600792ms)
✔ a building with issues cannot be deleted (18.289875ms)
✔ an empty building can be deleted (9.502917ms)
✔ an organisation with buildings cannot be deleted, an empty one can (22.819833ms)
✔ Cedar and can() agree on ViewIssue for every user and issue (457.189708ms)
✔ a logged-in POST without a token is refused with 403 (281.872416ms)
✔ a token from another session is refused (35.65375ms)
✔ the right token in the form field works (10.839583ms)
✔ every POST form on every page carries the token (40.134292ms)
✔ the dashboard counts match the database (287.153958ms)
✔ only the buildings carol can see appear (7.846708ms)
✔ create a draft, edit it, submit it, approve it (316.715375ms)
✔ invalid transitions are refused with 409 and change nothing (9.084583ms)
✔ only drafts can be edited (5.199917ms)
Show 62 more lines
✔ returning a submitted inspection makes it editable again (7.859458ms)
✔ concurrent approvals: exactly one wins (24.986709ms)
✔ unknown actions are 404 (3.038375ms)
✔ the issues list contains only issues from visible buildings (540.772583ms)
✔ a filter for another tenant's building returns nothing (4.375209ms)
✔ the inspections list is scoped too (10.472416ms)
✔ organisations are listed for their members only (9.895541ms)
✔ the dashboard counts only visible data (7.732042ms)
✔ view issue 101 (building 10) (446.0715ms)
✔ open the edit form for issue 101 (20.377125ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (19.242791ms)
✔ view issue 105 (building 30) and 106 (building 40) (33.306916ms)
✔ report an issue at building 20 (18.191083ms)
✔ a reporter cannot edit their own issue once it is closed (6.087208ms)
✔ only building admins may delete; refusals change nothing (13.415958ms)
✔ the edit form cannot move an issue to another building (3.832375ms)
✔ the list pages 10 at a time and reports the total (295.017ms)
✔ pages do not overlap (17.385375ms)
✔ filters combine with AND (5.639541ms)
✔ sorting by priority puts critical first when descending (5.202625ms)
✔ unknown sort keys and SQL in the query string are ignored (30.200334ms)
✔ GET /issues lists issues from the database (300.411959ms)
✔ GET /issues/101 shows one issue with its building (5.449416ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (15.478292ms)
✔ POST /issues re-renders the form with errors (4.494459ms)
✔ POST /issues stores the issue and redirects to it (7.605958ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (8.514625ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.675083ms)
✔ an issue time in the future is rejected (3.900791ms)
✔ GET /issues/101/edit shows the current values (4.734208ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.796166ms)
✔ POST /issues/:id/delete removes the issue (11.012125ms)
✔ GET /organisations lists organisations with building counts (282.347209ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.391792ms)
✔ POST /organisations validates and creates (11.641791ms)
✔ POST /organisations/:id/edit renames the organisation (9.911625ms)
✔ unknown organisations are 404 (9.080125ms)
✔ every policy is valid against the schema (24.591875ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (348.227167ms)
✔ anonymous requests are redirected to the login page (211.185583ms)
✔ anonymous writes are refused and change nothing (11.146917ms)
✔ login and register pages stay public (5.523708ms)
✔ login issues a new session id (no session fixation) (33.196292ms)
✔ returnTo only follows local paths (30.013917ms)
✔ new issues and transitions record the logged-in user (72.152416ms)
✔ the session cookie has the attributes we chose (31.676167ms)
✔ organisation 1: view and update (498.122958ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (6.213334ms)
✔ building 10: view, update, delete (52.744042ms)
✔ creating buildings needs org_admin (15.626625ms)
✔ creating an organisation makes the creator its admin (9.623917ms)
✔ inspections: view 201, open the edit form for draft 203 (39.174292ms)
✔ approve inspection 201 (dave's): only building admins (14.896375ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (10.63025ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 9180.723875
Reveal Answer
With orgAdminBuildings included, all 180 agree. Without it, Carol's issueViewerBuildings would be empty, so the 28 issues at buildings 10 and 20 would disagree for her: can() allows (organisation inheritance in rolesAtBuilding), Cedar denies. Try it: remove the ...user.access.orgAdminBuildings... line in entities.js, run npm test, read the mismatch list, then put the line back. A parity test like this is how you change an authorization engine without changing behaviour.
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) (465.300041ms)
✔ edit issue 101 (19.473ms)
✔ view issue 103 (building 20) (17.279291ms)
✔ edit issue 103 (reported by dave) (20.368333ms)
✔ report an issue at building 20 (18.916834ms)
✔ view issue 105 (building 30) (17.054917ms)
✔ view issue 106 (building 40, reported by bob) (15.422334ms)
✔ approve inspection 201 (created by dave) (16.264917ms)
✔ approve inspection 202 (created by alice) (16.529083ms)
✔ update organisation 1 (15.715042ms)
✔ issues in each user's list come only from the expected buildings (101.368208ms)
✔ the scenario loads exactly as specified (190.095958ms)
✔ only one active assignment per user, building and role (0.985916ms)
✔ a revoked role can be granted again (0.987917ms)
✔ the My access page shows what the server loaded (75.006167ms)
✔ a correct login creates a session and shows the user (267.798958ms)
✔ a wrong password or unknown email gets the same 401 (51.531875ms)
✔ registration validates, creates a user, and logs them in (47.197333ms)
✔ registering an existing email is a field error (31.556541ms)
✔ logout destroys the session (49.447583ms)
✔ a building can be created inside an organisation (281.295ms)
✔ a duplicate building name in the same organisation is a field error (4.569375ms)
✔ the same building name is allowed in another organisation (9.894416ms)
✔ a building with issues cannot be deleted (20.27525ms)
✔ an empty building can be deleted (10.026375ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.673458ms)
✔ Cedar and can() agree on ViewIssue for every user and issue (468.817792ms)
✔ a logged-in POST without a token is refused with 403 (264.184417ms)
✔ a token from another session is refused (37.839208ms)
✔ the right token in the form field works (9.440458ms)
✔ every POST form on every page carries the token (41.292208ms)
✔ the dashboard counts match the database (272.809875ms)
✔ only the buildings carol can see appear (5.758084ms)
✔ create a draft, edit it, submit it, approve it (327.564584ms)
✔ invalid transitions are refused with 409 and change nothing (9.512417ms)
✔ only drafts can be edited (4.528542ms)
Show 62 more lines
✔ returning a submitted inspection makes it editable again (7.006833ms)
✔ concurrent approvals: exactly one wins (22.235291ms)
✔ unknown actions are 404 (3.463958ms)
✔ the issues list contains only issues from visible buildings (524.441584ms)
✔ a filter for another tenant's building returns nothing (3.701041ms)
✔ the inspections list is scoped too (9.513708ms)
✔ organisations are listed for their members only (8.469667ms)
✔ the dashboard counts only visible data (6.551583ms)
✔ view issue 101 (building 10) (452.630709ms)
✔ open the edit form for issue 101 (21.16025ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (17.179167ms)
✔ view issue 105 (building 30) and 106 (building 40) (31.620583ms)
✔ report an issue at building 20 (18.2245ms)
✔ a reporter cannot edit their own issue once it is closed (6.027292ms)
✔ only building admins may delete; refusals change nothing (13.650541ms)
✔ the edit form cannot move an issue to another building (3.334958ms)
✔ the list pages 10 at a time and reports the total (279.470875ms)
✔ pages do not overlap (17.495792ms)
✔ filters combine with AND (5.436542ms)
✔ sorting by priority puts critical first when descending (5.179083ms)
✔ unknown sort keys and SQL in the query string are ignored (28.444958ms)
✔ GET /issues lists issues from the database (271.444666ms)
✔ GET /issues/101 shows one issue with its building (6.067292ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (16.224ms)
✔ POST /issues re-renders the form with errors (4.643625ms)
✔ POST /issues stores the issue and redirects to it (7.656291ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (3.63975ms)
✔ the stored row has the cleaned values and ignores a client-sent status (3.764875ms)
✔ an issue time in the future is rejected (3.708667ms)
✔ GET /issues/101/edit shows the current values (4.331333ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.955584ms)
✔ POST /issues/:id/delete removes the issue (8.582291ms)
✔ GET /organisations lists organisations with building counts (255.808916ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.32225ms)
✔ POST /organisations validates and creates (12.277542ms)
✔ POST /organisations/:id/edit renames the organisation (9.157542ms)
✔ unknown organisations are 404 (6.387292ms)
✔ every policy is valid against the schema (24.878792ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (347.813042ms)
✔ anonymous requests are redirected to the login page (214.181208ms)
✔ anonymous writes are refused and change nothing (11.429916ms)
✔ login and register pages stay public (5.974458ms)
✔ login issues a new session id (no session fixation) (33.032875ms)
✔ returnTo only follows local paths (30.096042ms)
✔ new issues and transitions record the logged-in user (84.536625ms)
✔ the session cookie has the attributes we chose (25.602667ms)
✔ organisation 1: view and update (511.38ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (6.030833ms)
✔ building 10: view, update, delete (45.13275ms)
✔ creating buildings needs org_admin (13.298459ms)
✔ creating an organisation makes the creator its admin (7.76875ms)
✔ inspections: view 201, open the edit form for draft 203 (32.92425ms)
✔ approve inspection 201 (dave's): only building admins (12.876625ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (9.751583ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 9101.33525
git add -A
git commit -m "Entity mapper, explain command and parity test"
[main 8b4a9a6] Entity mapper, explain command and parity test
6 files changed, 159 insertions(+), 3 deletions(-)
create mode 100644 scripts/authz-explain.js
create mode 100644 src/authz/entities.js
create mode 100644 src/authz/request.js
create mode 100644 test/cedar-parity.test.js
Symptom The parity test fails for every user
Check that IDs are compared as strings in references (ref converts with String(id)), and that findIssue returns organisation_id.
Symptom entity ... does not exist in the explain output
An entity referenced as the principal or resource is missing from entities. buildAuthorizationCall must push the principal, the resource, and the resource's building and organisation.
Recap and next step
The mapper builds entities only from server-side data: the user ID from the session, roles from loadAccess, the issue from findIssue. buildAuthorizationCall assembles principal, action, resource, context and entities. The explain command shows every value on the path from rows to decision. The parity test proves Cedar and can() agree for 180 user–issue pairs.
Cedar is ready to take over its first decision. Next lesson it does, inside the running app, behind the same can() function, with no change to any route or test.
Open the checkpoint files for lesson 6.3 (separate page; only files from this lesson and earlier)