Module 6 · Introduce Cedar
6.6 Forbid, precedence, errors and failures
Express separation of duties as a forbid policy that overrides every permit, see why an evaluation error in a forbid policy is dangerous, and test how the app handles a normal deny, an evaluation error and a failure.
Starting point
Twelve permit policies decide every action. approve-inspection.cedar carries the separation-of-duties exception inside its condition.
Outcome
src/authz/policies/forbid-self-approval.cedar (new)src/authz/policies/approve-inspection.cedar (deleted: approval joins administer-building-data)scripts/cedar-errors-demo.js (new, standalone)test/authz-decisions.test.js (new)You can predict Cedar's decision for any mix of permit and forbid policies, and you can name the four outcomes our app distinguishes: allow, normal deny, evaluation error, and failure.
The problem
Separation of duties is not a property of approving. It is an exception that must hold no matter which permit grants approval. Today only approve-inspection.cedar knows about it. If someone later adds a policy such as "organisation admins may approve anything in their organisation", that new permit would let Carol approve her own inspections, because the exception lives in a different file.
The JavaScript version had the same weakness. Cedar has a construct designed for exceptions: forbid.
Build it
1. A forbid policy
// Separation of duties: nobody approves an inspection they created,// whatever other policies permit.forbid (principal, action == Caretaker::Action::"ApproveInspection", resource)when { resource has createdBy && resource.createdBy == principal };Recall the rule from lesson 6.1: if any forbid matches, the decision is deny, regardless of how many permits match. A forbid can only take rights away; it can never grant them.
Now approval is an ordinary admin action. Add it to the admin policy, and delete the special permit:
Caretaker::Action::"SubmitInspection", Caretaker::Action::"ApproveInspection", Caretaker::Action::"ReturnInspection"
Show the whole src/authz/policies/administer-building-data.cedar after this change
// 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::"ApproveInspection", Caretaker::Action::"ReturnInspection" ], resource)when { principal.adminBuildings.contains(resource.building) };// 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::"ApproveInspection",
Caretaker::Action::"ReturnInspection"
],
resource
)
when { principal.adminBuildings.contains(resource.building) };
git rm -q src/authz/policies/approve-inspection.cedar
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
12 policies are valid against the schema
Still 12 policies: one permit gone, one forbid added.
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) (575.479291ms)
✔ edit issue 101 (81.199083ms)
✔ view issue 103 (building 20) (62.799833ms)
✔ edit issue 103 (reported by dave) (65.897625ms)
✔ report an issue at building 20 (71.185792ms)
✔ view issue 105 (building 30) (40.433375ms)
✔ view issue 106 (building 40, reported by bob) (42.127667ms)
✔ approve inspection 201 (created by dave) (39.075584ms)
✔ approve inspection 202 (created by alice) (54.652834ms)
✔ update organisation 1 (50.262125ms)
✔ issues in each user's list come only from the expected buildings (107.405459ms)
✔ the scenario loads exactly as specified (217.4005ms)
✔ only one active assignment per user, building and role (0.958542ms)
✔ a revoked role can be granted again (1.2835ms)
✔ the My access page shows what the server loaded (71.74725ms)
✔ a correct login creates a session and shows the user (260.322834ms)
✔ a wrong password or unknown email gets the same 401 (54.871625ms)
✔ registration validates, creates a user, and logs them in (36.334167ms)
✔ registering an existing email is a field error (30.697667ms)
✔ logout destroys the session (53.892ms)
✔ a building can be created inside an organisation (310.997292ms)
✔ a duplicate building name in the same organisation is a field error (11.840875ms)
✔ the same building name is allowed in another organisation (17.197209ms)
✔ a building with issues cannot be deleted (36.952125ms)
✔ an empty building can be deleted (21.981125ms)
✔ an organisation with buildings cannot be deleted, an empty one can (47.277458ms)
✔ a logged-in POST without a token is refused with 403 (270.129292ms)
✔ a token from another session is refused (37.754541ms)
✔ the right token in the form field works (33.163125ms)
✔ every POST form on every page carries the token (159.769709ms)
✔ the dashboard counts match the database (275.433ms)
✔ only the buildings carol can see appear (7.310875ms)
✔ create a draft, edit it, submit it, approve it (382.657792ms)
✔ invalid transitions are refused with 409 and change nothing (35.666709ms)
✔ only drafts can be edited (19.391542ms)
✔ returning a submitted inspection makes it editable again (18.8695ms)
Show 62 more lines
✔ concurrent approvals: exactly one wins (61.341042ms)
✔ unknown actions are 404 (2.996333ms)
✔ the issues list contains only issues from visible buildings (526.04475ms)
✔ a filter for another tenant's building returns nothing (3.76575ms)
✔ the inspections list is scoped too (10.132875ms)
✔ organisations are listed for their members only (8.720667ms)
✔ the dashboard counts only visible data (7.017917ms)
✔ view issue 101 (building 10) (511.721375ms)
✔ open the edit form for issue 101 (80.158875ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (84.1245ms)
✔ view issue 105 (building 30) and 106 (building 40) (86.045375ms)
✔ report an issue at building 20 (87.532833ms)
✔ a reporter cannot edit their own issue once it is closed (34.953417ms)
✔ only building admins may delete; refusals change nothing (35.358083ms)
✔ the edit form cannot move an issue to another building (10.032166ms)
✔ the list pages 10 at a time and reports the total (282.128458ms)
✔ pages do not overlap (17.421875ms)
✔ filters combine with AND (5.354417ms)
✔ sorting by priority puts critical first when descending (5.221583ms)
✔ unknown sort keys and SQL in the query string are ignored (28.840125ms)
✔ GET /issues lists issues from the database (322.289834ms)
✔ GET /issues/101 shows one issue with its building (23.261125ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (15.645541ms)
✔ POST /issues re-renders the form with errors (15.854292ms)
✔ POST /issues stores the issue and redirects to it (21.217125ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (18.118917ms)
✔ the stored row has the cleaned values and ignores a client-sent status (11.812791ms)
✔ an issue time in the future is rejected (17.365167ms)
✔ GET /issues/101/edit shows the current values (25.486667ms)
✔ POST /issues/:id/edit changes the status and updated_at (13.53175ms)
✔ POST /issues/:id/delete removes the issue (19.198709ms)
✔ GET /organisations lists organisations with building counts (266.868125ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (31.176292ms)
✔ POST /organisations validates and creates (25.809166ms)
✔ POST /organisations/:id/edit renames the organisation (31.726834ms)
✔ unknown organisations are 404 (13.343375ms)
✔ every policy is valid against the schema (30.672916ms)
✔ every action used by the app is mentioned by at least one policy (0.5835ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (329.075875ms)
✔ anonymous requests are redirected to the login page (213.548334ms)
✔ anonymous writes are refused and change nothing (11.233333ms)
✔ login and register pages stay public (6.127375ms)
✔ login issues a new session id (no session fixation) (32.086542ms)
✔ returnTo only follows local paths (27.646375ms)
✔ new issues and transitions record the logged-in user (95.702834ms)
✔ the session cookie has the attributes we chose (28.649958ms)
✔ organisation 1: view and update (561.359583ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (26.51425ms)
✔ building 10: view, update, delete (150.251459ms)
✔ creating buildings needs org_admin (47.153125ms)
✔ creating an organisation makes the creator its admin (19.604083ms)
✔ inspections: view 201, open the edit form for draft 203 (113.662791ms)
✔ approve inspection 201 (dave's): only building admins (39.306417ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (41.402167ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 10906.523417
The matrix row "approve inspection 202 (created by alice)" still expects 403 for Alice and 303 for Carol, and it passes. Look at why Alice is refused now:
npm run authz:explain -- alice ApproveInspection 202 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "deny",
"diagnostics": {
"reason": [
"forbid-self-approval"
],
"errors": []
}
},
"warnings": []
}
deny, and the reason is forbid-self-approval. When a forbid decides, the reason lists the forbid policies that matched; the permit that also matched (administer-building-data) is not listed, because it did not determine the outcome. Compare with Dave, who is not a building admin at building 10, asking to approve Alice's inspection:
npm run authz:explain -- dave ApproveInspection 202 | sed -n '/== 6/,$p'
== 6. Cedar answer
{
"type": "success",
"response": {
"decision": "deny",
"diagnostics": {
"reason": [],
"errors": []
}
},
"warnings": []
}
deny with an empty reason: nothing permitted it, and no forbid applied because Dave did not create inspection 202. (Ask the same question about inspection 201, which Dave created, and the reason becomes forbid-self-approval even though no permit matched either: the reason reports every forbid that matched.) Two denials, two different explanations. Your decision log can tell an explicit rule ("forbidden by separation of duties") from a missing permission.
The four outcomes
| Outcome | What Cedar returned | What our evaluate() returns |
What the route does |
|---|---|---|---|
| Allow | success, allow, no errors |
allowed: true |
acts |
| Normal deny | success, deny, no errors (reason empty or forbid IDs) |
allowed: false |
404 or 403 |
| Evaluation error | success plus diagnostics.errors: a policy could not be evaluated and was skipped |
allowed: false, logged as authz problem |
404 or 403 |
| Failure | failure: the request or entities do not match the schema, or a policy does not parse |
allowed: false, decision: 'failure', logged |
404 or 403 |
The third row needs a closer look.
Why an evaluation error must deny
Create a standalone demonstration. It uses no schema, so that we can make a mistake the schema would otherwise catch:
// What happens when a forbid policy cannot be evaluated? Standalone; no schema on purpose.import * as cedar from '@cedar-policy/cedar-wasm/nodejs'; const ref = (type, id) => ({ type: `Caretaker::${type}`, id: String(id) });const policies = { 'view-anything': 'permit (principal, action == Caretaker::Action::"ViewIssue", resource);', 'forbid-suspended': 'forbid (principal, action, resource) when { principal.suspended };',}; for (const [label, attrs] of [['suspended: true', { suspended: true }], ['suspended: false', { suspended: false }], ['attribute missing', {}]]) { const answer = cedar.isAuthorized({ principal: ref('User', 1), action: { type: 'Caretaker::Action', id: 'ViewIssue' }, resource: ref('Issue', 101), context: {}, policies: { staticPolicies: policies }, entities: [{ uid: ref('User', 1), attrs, parents: [] }, { uid: ref('Issue', 101), attrs: {}, parents: [] }], }); const { decision, diagnostics } = answer.response; console.log(`${label.padEnd(18)} decision=${decision} reason=${diagnostics.reason.join(',')} errors=${diagnostics.errors.map((e) => e.policyId).join(',') || '-'}`);}suspended, what does Cedar decide?node scripts/cedar-errors-demo.js
suspended: true decision=deny reason=forbid-suspended errors=-
suspended: false decision=allow reason=view-anything errors=-
attribute missing decision=allow reason=view-anything errors=forbid-suspended
Reveal Why this matters
With the attribute missing, the forbid policy could not be evaluated, so Cedar skipped it, and the permit allowed the request: decision=allow, with forbid-suspended listed under errors. A bug in the mapper silently disabled a security rule. Two things in our app stop that:
- The schema. With a schema,
suspendedwould be declared. If declared as required, an entity without it is afailure; if optional, the validator rejects any policy that reads it withouthas. - Fail-closed evaluation.
evaluate()treatsallowwith errors as not allowed, andauthorize()logs it. Even if a mistake slips past the schema, the error makes the request fail safely and loudly.
Tests for each outcome
Add a helper that loads a user exactly as loadUser does, so tests can call authorize() directly:
import { seed, SEED_PASSWORD } from '../src/seed.js';import { query } from '../src/db.js';import { findUserById } from '../src/models/users.js';import { loadAccess } from '../src/models/access.js'; // Loads a seeded user and their access, like loadUser does for a request.export async function loadUserNamed(name) { const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]); const user = await findUserById(rows[0].id); user.access = await loadAccess(user.id); return user;}
Show the whole test/helpers.js after this change
import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { config } from '../src/config.js';import { migrate } from '../src/migrate.js';import { seed, SEED_PASSWORD } from '../src/seed.js';import { query } from '../src/db.js';import { findUserById } from '../src/models/users.js';import { loadAccess } from '../src/models/access.js'; // Loads a seeded user and their access, like loadUser does for a request.export async function loadUserNamed(name) { const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]); const user = await findUserById(rows[0].id); user.access = await loadAccess(user.id); return user;} export function csrfTokenFrom(html) { const match = html.match(/<meta name="csrf-token" content="([^"]+)">/); if (!match) { throw new Error('No CSRF token on the page'); } return match[1];} // An agent that has visited the login page and sends its CSRF token on every request.export async function anonymousAgent() { const agent = request.agent(app); const page = await agent.get('/login'); agent.set('X-CSRF-Token', csrfTokenFrom(page.text)); return agent;} // Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.export async function loginAs(name, password = SEED_PASSWORD) { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password }); if (res.status !== 303) { throw new Error(`Login as ${name} failed with status ${res.status}`); } // Login regenerated the session, so the token changed. Read the new one. const home = await agent.get('/'); agent.set('X-CSRF-Token', csrfTokenFrom(home.text)); return agent;} export async function resetDatabase() { if (!config.databaseUrl.endsWith('/caretaker_test')) { throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`); } await migrate(config.databaseUrl, { log: () => {} }); const client = await pool.connect(); try { await seed(client); } finally { client.release(); }}import request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { config } from '../src/config.js';
import { migrate } from '../src/migrate.js';
import { seed, SEED_PASSWORD } from '../src/seed.js';
import { query } from '../src/db.js';
import { findUserById } from '../src/models/users.js';
import { loadAccess } from '../src/models/access.js';
// Loads a seeded user and their access, like loadUser does for a request.
export async function loadUserNamed(name) {
const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]);
const user = await findUserById(rows[0].id);
user.access = await loadAccess(user.id);
return user;
}
export function csrfTokenFrom(html) {
const match = html.match(/<meta name="csrf-token" content="([^"]+)">/);
if (!match) {
throw new Error('No CSRF token on the page');
}
return match[1];
}
// An agent that has visited the login page and sends its CSRF token on every request.
export async function anonymousAgent() {
const agent = request.agent(app);
const page = await agent.get('/login');
agent.set('X-CSRF-Token', csrfTokenFrom(page.text));
return agent;
}
// Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.
export async function loginAs(name, password = SEED_PASSWORD) {
const agent = await anonymousAgent();
const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password });
if (res.status !== 303) {
throw new Error(`Login as ${name} failed with status ${res.status}`);
}
// Login regenerated the session, so the token changed. Read the new one.
const home = await agent.get('/');
agent.set('X-CSRF-Token', csrfTokenFrom(home.text));
return agent;
}
export async function resetDatabase() {
if (!config.databaseUrl.endsWith('/caretaker_test')) {
throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`);
}
await migrate(config.databaseUrl, { log: () => {} });
const client = await pool.connect();
try {
await seed(client);
} finally {
client.release();
}
}
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: ['administer-building-data'] });}); 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 failure test passes a deliberately broken row (status as a number). The test output will include the authz problem line that authorize() logs: that line is the alarm you would see in production.
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) (521.994875ms)
✔ edit issue 101 (76.86225ms)
✔ view issue 103 (building 20) (61.310833ms)
✔ edit issue 103 (reported by dave) (74.381667ms)
✔ report an issue at building 20 (87.968042ms)
✔ view issue 105 (building 30) (47.144167ms)
✔ view issue 106 (building 40, reported by bob) (37.891834ms)
✔ approve inspection 201 (created by dave) (43.798834ms)
✔ approve inspection 202 (created by alice) (46.853458ms)
✔ update organisation 1 (49.904291ms)
✔ issues in each user's list come only from the expected buildings (99.582ms)
✔ the scenario loads exactly as specified (194.097625ms)
✔ only one active assignment per user, building and role (0.923ms)
✔ a revoked role can be granted again (0.8905ms)
✔ the My access page shows what the server loaded (69.330042ms)
✔ a correct login creates a session and shows the user (262.233708ms)
✔ a wrong password or unknown email gets the same 401 (55.147417ms)
✔ registration validates, creates a user, and logs them in (50.124291ms)
✔ registering an existing email is a field error (32.023917ms)
✔ logout destroys the session (53.933041ms)
✔ allow: a permit matched and nothing forbade it (214.0605ms)
✔ explicit deny: a forbid overrides a matching permit (6.165ms)
✔ implicit deny: no permit matched (5.268334ms)
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.264458ms)
✔ unknown actions throw instead of deciding (1.865584ms)
✔ a building can be created inside an organisation (300.680541ms)
✔ a duplicate building name in the same organisation is a field error (12.476792ms)
Show 76 more lines
✔ the same building name is allowed in another organisation (17.738458ms)
✔ a building with issues cannot be deleted (36.59575ms)
✔ an empty building can be deleted (20.777791ms)
✔ an organisation with buildings cannot be deleted, an empty one can (48.363208ms)
✔ a logged-in POST without a token is refused with 403 (272.769917ms)
✔ a token from another session is refused (36.976833ms)
✔ the right token in the form field works (33.024083ms)
✔ every POST form on every page carries the token (151.979417ms)
✔ the dashboard counts match the database (274.933583ms)
✔ only the buildings carol can see appear (5.58225ms)
✔ create a draft, edit it, submit it, approve it (375.371583ms)
✔ invalid transitions are refused with 409 and change nothing (37.195083ms)
✔ only drafts can be edited (18.307292ms)
✔ returning a submitted inspection makes it editable again (21.789917ms)
✔ concurrent approvals: exactly one wins (60.251708ms)
✔ unknown actions are 404 (3.199708ms)
✔ the issues list contains only issues from visible buildings (542.535625ms)
✔ a filter for another tenant's building returns nothing (3.955ms)
✔ the inspections list is scoped too (9.578084ms)
✔ organisations are listed for their members only (8.554542ms)
✔ the dashboard counts only visible data (7.0395ms)
✔ view issue 101 (building 10) (503.690333ms)
✔ open the edit form for issue 101 (81.422834ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (80.696667ms)
✔ view issue 105 (building 30) and 106 (building 40) (80.05ms)
✔ report an issue at building 20 (91.351417ms)
✔ a reporter cannot edit their own issue once it is closed (33.478125ms)
✔ only building admins may delete; refusals change nothing (42.756ms)
✔ the edit form cannot move an issue to another building (10.229333ms)
✔ the list pages 10 at a time and reports the total (288.812208ms)
✔ pages do not overlap (15.515292ms)
✔ filters combine with AND (5.165417ms)
✔ sorting by priority puts critical first when descending (4.754875ms)
✔ unknown sort keys and SQL in the query string are ignored (27.170625ms)
✔ GET /issues lists issues from the database (269.955833ms)
✔ GET /issues/101 shows one issue with its building (21.675708ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (17.058667ms)
✔ POST /issues re-renders the form with errors (15.75575ms)
✔ POST /issues stores the issue and redirects to it (21.604083ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (19.280833ms)
✔ the stored row has the cleaned values and ignores a client-sent status (9.765375ms)
✔ an issue time in the future is rejected (15.77575ms)
✔ GET /issues/101/edit shows the current values (23.116667ms)
✔ POST /issues/:id/edit changes the status and updated_at (12.902708ms)
✔ POST /issues/:id/delete removes the issue (22.173375ms)
✔ GET /organisations lists organisations with building counts (252.415292ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (33.653125ms)
✔ POST /organisations validates and creates (28.237958ms)
✔ POST /organisations/:id/edit renames the organisation (35.400417ms)
✔ unknown organisations are 404 (8.58375ms)
✔ every policy is valid against the schema (30.473375ms)
✔ every action used by the app is mentioned by at least one policy (0.676334ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (340.994666ms)
✔ anonymous requests are redirected to the login page (190.569041ms)
✔ anonymous writes are refused and change nothing (10.715375ms)
✔ login and register pages stay public (5.599208ms)
✔ login issues a new session id (no session fixation) (32.399167ms)
✔ returnTo only follows local paths (28.268625ms)
✔ new issues and transitions record the logged-in user (106.295042ms)
✔ the session cookie has the attributes we chose (28.157166ms)
✔ organisation 1: view and update (607.176958ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (29.339833ms)
✔ building 10: view, update, delete (140.719375ms)
✔ creating buildings needs org_admin (45.0015ms)
✔ creating an organisation makes the creator its admin (18.610666ms)
✔ inspections: view 201, open the edit form for draft 203 (107.932459ms)
✔ approve inspection 201 (dave's): only building admins (37.555292ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (44.087209ms)
ℹ tests 95
ℹ suites 0
ℹ pass 95
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 11207.320167
Experiment
A new requirement arrives: "organisation admins may approve any inspection in their organisation". Add it as a permit:
// Organisation admins may approve inspections anywhere in their organisation.permit (principal, action == Caretaker::Action::"ApproveInspection", resource)when { principal.adminOrganisations.contains(resource.building.organisation) };npm run authz:validate && node --env-file=.env --input-type=module -e "
import { pool, query } from './src/db.js';
import { authorize } from './src/authz/authorize.js';
import { findInspection } from './src/models/inspections.js';
import { findUserById } from './src/models/users.js';
import { loadAccess } from './src/models/access.js';
const carol = await findUserById(3);
carol.access = await loadAccess(3);
const inspection = { ...(await findInspection(203)), status: 'submitted' };
const result = authorize(carol, 'ApproveInspection', inspection);
console.log(result.decision, result.reasons.join(','));
await pool.end();
"
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
13 policies are valid against the schema
deny forbid-self-approval
Reveal Answer
No. The new permit matches (so does administer-building-data), but forbid-self-approval also matches, and forbid wins. The exception was written once and protects every present and future way of granting approval. That is the practical value of forbid: exceptions are not woven into each permit. (Note how the new policy reads resource.building.organisation: it follows a reference from the inspection to its building entity, then reads the building's attribute. That works because buildAuthorizationCall included the building entity.)
The requirement was hypothetical. Remove the policy again:
rm src/authz/policies/org-admin-approves.cedar
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) (510.821375ms)
✔ edit issue 101 (79.367667ms)
✔ view issue 103 (building 20) (61.16225ms)
✔ edit issue 103 (reported by dave) (72.824875ms)
✔ report an issue at building 20 (84.154875ms)
✔ view issue 105 (building 30) (38.818417ms)
✔ view issue 106 (building 40, reported by bob) (33.7465ms)
✔ approve inspection 201 (created by dave) (38.760958ms)
✔ approve inspection 202 (created by alice) (43.442208ms)
✔ update organisation 1 (43.203709ms)
✔ issues in each user's list come only from the expected buildings (90.945833ms)
✔ the scenario loads exactly as specified (211.245792ms)
✔ only one active assignment per user, building and role (0.811875ms)
✔ a revoked role can be granted again (1.591709ms)
✔ the My access page shows what the server loaded (71.721958ms)
✔ a correct login creates a session and shows the user (251.321375ms)
✔ a wrong password or unknown email gets the same 401 (54.293584ms)
✔ registration validates, creates a user, and logs them in (39.552917ms)
✔ registering an existing email is a field error (31.533208ms)
✔ logout destroys the session (46.325375ms)
✔ allow: a permit matched and nothing forbade it (223.422ms)
✔ explicit deny: a forbid overrides a matching permit (6.113417ms)
✔ implicit deny: no permit matched (5.306917ms)
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.063ms)
✔ unknown actions throw instead of deciding (1.663375ms)
✔ a building can be created inside an organisation (299.287416ms)
✔ a duplicate building name in the same organisation is a field error (10.930792ms)
Show 76 more lines
✔ the same building name is allowed in another organisation (16.487041ms)
✔ a building with issues cannot be deleted (41.806709ms)
✔ an empty building can be deleted (21.965959ms)
✔ an organisation with buildings cannot be deleted, an empty one can (51.255125ms)
✔ a logged-in POST without a token is refused with 403 (268.357625ms)
✔ a token from another session is refused (39.521791ms)
✔ the right token in the form field works (34.894584ms)
✔ every POST form on every page carries the token (129.772917ms)
✔ the dashboard counts match the database (270.470125ms)
✔ only the buildings carol can see appear (7.571209ms)
✔ create a draft, edit it, submit it, approve it (379.01425ms)
✔ invalid transitions are refused with 409 and change nothing (32.358292ms)
✔ only drafts can be edited (22.172625ms)
✔ returning a submitted inspection makes it editable again (24.05475ms)
✔ concurrent approvals: exactly one wins (59.039ms)
✔ unknown actions are 404 (3.174958ms)
✔ the issues list contains only issues from visible buildings (531.931625ms)
✔ a filter for another tenant's building returns nothing (4.756541ms)
✔ the inspections list is scoped too (9.878333ms)
✔ organisations are listed for their members only (8.415958ms)
✔ the dashboard counts only visible data (6.69025ms)
✔ view issue 101 (building 10) (511.375625ms)
✔ open the edit form for issue 101 (78.320667ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (62.808333ms)
✔ view issue 105 (building 30) and 106 (building 40) (67.142375ms)
✔ report an issue at building 20 (68.759334ms)
✔ a reporter cannot edit their own issue once it is closed (25.478375ms)
✔ only building admins may delete; refusals change nothing (36.676083ms)
✔ the edit form cannot move an issue to another building (10.398125ms)
✔ the list pages 10 at a time and reports the total (313.91675ms)
✔ pages do not overlap (17.917708ms)
✔ filters combine with AND (5.575708ms)
✔ sorting by priority puts critical first when descending (5.151792ms)
✔ unknown sort keys and SQL in the query string are ignored (29.183333ms)
✔ GET /issues lists issues from the database (273.29125ms)
✔ GET /issues/101 shows one issue with its building (23.279208ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (16.392709ms)
✔ POST /issues re-renders the form with errors (16.042292ms)
✔ POST /issues stores the issue and redirects to it (19.99975ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (13.911709ms)
✔ the stored row has the cleaned values and ignores a client-sent status (6.814958ms)
✔ an issue time in the future is rejected (13.52275ms)
✔ GET /issues/101/edit shows the current values (17.935917ms)
✔ POST /issues/:id/edit changes the status and updated_at (9.999541ms)
✔ POST /issues/:id/delete removes the issue (23.604167ms)
✔ GET /organisations lists organisations with building counts (269.946542ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (30.048084ms)
✔ POST /organisations validates and creates (29.64675ms)
✔ POST /organisations/:id/edit renames the organisation (30.983333ms)
✔ unknown organisations are 404 (8.77325ms)
✔ every policy is valid against the schema (29.744625ms)
✔ every action used by the app is mentioned by at least one policy (0.642667ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (349.828ms)
✔ anonymous requests are redirected to the login page (213.886167ms)
✔ anonymous writes are refused and change nothing (10.916375ms)
✔ login and register pages stay public (6.135292ms)
✔ login issues a new session id (no session fixation) (38.097333ms)
✔ returnTo only follows local paths (27.960833ms)
✔ new issues and transitions record the logged-in user (102.685083ms)
✔ the session cookie has the attributes we chose (28.931667ms)
✔ organisation 1: view and update (597.977583ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (29.006ms)
✔ building 10: view, update, delete (159.204375ms)
✔ creating buildings needs org_admin (48.771375ms)
✔ creating an organisation makes the creator its admin (18.219417ms)
✔ inspections: view 201, open the edit form for draft 203 (101.890458ms)
✔ approve inspection 201 (dave's): only building admins (36.466958ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (41.966958ms)
ℹ tests 95
ℹ suites 0
ℹ pass 95
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 11131.20125
git add -A
git commit -m "Separation of duties as a forbid policy; test decision outcomes"
[main df00884] Separation of duties as a forbid policy; test decision outcomes
6 files changed, 75 insertions(+), 6 deletions(-)
create mode 100644 scripts/cedar-errors-demo.js
delete mode 100644 src/authz/policies/approve-inspection.cedar
create mode 100644 src/authz/policies/forbid-self-approval.cedar
create mode 100644 test/authz-decisions.test.js
Symptom The forbid never matches
Check the condition against the explain output: createdBy must be present on the inspection entity (the seed sets created_by for every inspection), and both sides of == must be User references.
Symptom authz problem lines appear during npm test
One comes from the deliberate failure test and is expected. Any other line names a real problem: read its errors.
Recap and next step
forbid expresses exceptions once, and they override every permit, present and future. The reason field distinguishes an explicit forbid from a missing permit. Cedar skips policies that cannot be evaluated, so an error in a forbid could open access; our schema and our fail-closed evaluate() prevent that, and tests cover allow, explicit deny, implicit deny and failure.
Module 6 is complete: every decision is made by Cedar, with behaviour proven unchanged. But look again at entities.js: the mapper decides that organisation admins are building admins, and that building admins are reporters. That is policy, hiding in JavaScript. Module 7 moves it where it belongs.
Open the checkpoint files for lesson 6.6 (separate page; only files from this lesson and earlier)