Caretaker Express · PostgreSQL · Cedar

Module 6 · Introduce Cedar

6.4 Cedar behind can(): the first route

Load and validate the policy store at startup, wrap the engine so that it fails closed, log decisions, and let Cedar decide ViewIssue inside the running app without changing a route, a template or a test.

≈ 35 min 15 steps 51 lines of code Replay verified

Starting point

The mapper builds correct entities (the parity test checked 180 pairs). The app still decides everything with JavaScript in can().

Outcome

Text
src/authz/cedar.js       (new: the engine, loaded and validated once)src/authz/authorize.js   (new: build the call, evaluate, log)src/authz/rules.js       (ViewIssue now asks Cedar)

Every check of ViewIssue (opening an issue, every other issue route, the Edit and Delete buttons' pages) is decided by Cedar. The app refuses to start if the policy store is invalid. With AUTHZ_LOG=1 the server prints each decision with the policy that made it.

The problem

We want to switch engines without a big-bang rewrite. Our routes, templates and tests all go through one function, can(user, action, resource), so that function is the seam: we change what is inside it, one action at a time, and the access matrix tells us immediately if behaviour changed.

Two design questions come first:

  1. When do we load and check the policies? Reading and validating them on every request is wasteful, and finding out in the middle of a request that a policy is broken is too late. We load them once, at startup, and refuse to start if they are invalid.
  2. What do we do with anything that is not a clean answer? Cedar can return a failure (bad input) or a decision with evaluation errors. Authorization must fail closed: if in doubt, deny, and make the problem visible.

Build it

1. The engine module

Create src/authz/cedar.js:

Create filesrc/authz/cedar.jsJavaScript
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { loadPolicyStore } from './policy-store.js'; // Loaded and validated once, the first time this module is imported.// If the policy store is invalid, importing this module throws and the app does not start.const { schema, policies } = loadPolicyStore();const validation = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });if (validation.type !== 'success' || validation.validationErrors.length > 0) {  const problems = validation.type === 'success'    ? validation.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`)    : validation.errors.map((e) => e.message);  throw new Error(`The Cedar policy store is invalid:\n${problems.join('\n')}`);} export const policyIds = Object.keys(policies); // Evaluates one call against the policy store.// Fails closed: only a successful "allow" without evaluation errors is allowed.export function evaluate(call) {  const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } });  if (answer.type === 'failure') {    return { allowed: false, decision: 'failure', reasons: [], errors: answer.errors.map((e) => e.message) };  }  const { decision, diagnostics } = answer.response;  const errors = diagnostics.errors.map((e) => `${e.policyId}: ${e.error.message}`);  return { allowed: decision === 'allow' && errors.length === 0, decision, reasons: diagnostics.reason, errors };}
  • Validation at import. Node runs a module's top-level code once. The first import of cedar.js (when app.js loads its routes) validates the store or throws.
  • validateRequest: true with the schema means that a wrongly typed request or entity is a failure, never a quiet deny.
  • allowed is stricter than decision. An allow that came with evaluation errors is treated as not allowed. Lesson 6.6 shows the case that makes this necessary.
  • Every call passes the policies as text, so Cedar parses them each time. On the machine that recorded this course, one call took about 0.6 ms. That is fine for one decision per request; Module 8, where a list needs many decisions, measures it and switches to Cedar's pre-parsed API.

2. One function that does the whole job

Create src/authz/authorize.js:

Create filesrc/authz/authorize.jsJavaScript
import { config } from '../config.js';import { buildAuthorizationCall } from './request.js';import { evaluate } from './cedar.js'; // Builds the Cedar call for this user, action and database row, evaluates it, and logs.export function authorize(user, action, row) {  const call = buildAuthorizationCall(user, action, row);  const result = evaluate(call);  const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`;  if (result.decision === 'failure' || result.errors.length > 0) {    console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors });  }  if (config.authzLog) {    console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`);  }  return result;}

The log line contains IDs, the action, the decision and the policy IDs. It does not contain entity attributes, emails or names: authorization logs are read by many people and kept for a long time, so they should hold what you need to investigate and nothing more. Module 10 returns to this.

Add the setting to src/config.js:

Editsrc/config.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  logSql: process.env.LOG_SQL === '1',  authzLog: process.env.AUTHZ_LOG === '1',
Show the whole src/config.js after this change
function required(name) {  const value = process.env[name];  if (!value) {    throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`);  }  return value;} export const config = {  port: Number(process.env.PORT ?? 3000),  databaseUrl: required('DATABASE_URL'),  logSql: process.env.LOG_SQL === '1',  authzLog: process.env.AUTHZ_LOG === '1',  env: process.env.NODE_ENV ?? 'development',  sessionSecret: required('SESSION_SECRET'),  // Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production).  cookieSecure: process.env.COOKIE_SECURE === '1',  loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),};

3. Move one action

In src/authz/rules.js, replace the JavaScript rule for ViewIssue with a call to Cedar:

Editsrc/authz/rules.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 2
// Authorization rules in plain JavaScript (Module 5).// Every route asks can(user, action, resource). Module 6 keeps this question// and moves the answer into Cedar policies.// Authorization rules. Every route asks can(user, action, resource).// Actions are moving from JavaScript (Module 5) to Cedar policies (Module 6).import { authorize } from './authorize.js';
Change 2 of 2
    case 'ViewIssue':      return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);      return authorize(user, action, resource).allowed; // decided by Cedar
Show the whole src/authz/rules.js after this change
// Authorization rules. Every route asks can(user, action, resource).// Actions are moving from JavaScript (Module 5) to Cedar policies (Module 6).import { authorize } from './authorize.js'; const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin']; // The roles a user effectively holds at one building: the roles assigned there,// plus building_admin if they are org_admin of the organisation that owns the building.export function rolesAtBuilding(user, buildingId, organisationId) {  const roles = new Set();  for (const assignment of user.access.assignments) {    if (assignment.building_id === buildingId) {      roles.add(assignment.role);    }  }  if (isOrgAdmin(user, organisationId)) {    roles.add('building_admin');  }  return roles;} function isMember(user, organisationId) {  return user.access.memberships.some((m) => m.organisation_id === organisationId);} function isOrgAdmin(user, organisationId) {  return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');} function hasAny(roles, wanted) {  return wanted.some((role) => roles.has(role));} export function can(user, action, resource) {  switch (action) {    // Organisations. resource: an organisation row { id, ... }    case 'ViewOrganisation':      return isMember(user, resource.id);    case 'UpdateOrganisation':    case 'DeleteOrganisation':    case 'CreateBuilding':      return isOrgAdmin(user, resource.id);     // Buildings. resource: a building row { id, organisation_id, ... }    case 'ViewBuilding':      return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE);    case 'UpdateBuilding':      return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin');    case 'DeleteBuilding':      return isOrgAdmin(user, resource.organisation_id);    case 'CreateIssue':      return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']);    case 'CreateInspection':      return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']);     // Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... }    case 'ViewIssue':      return authorize(user, action, resource).allowed; // decided by Cedar    case 'UpdateIssue': {      const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);      if (roles.has('building_admin')) {        return true;      }      return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed';    }    case 'DeleteIssue':      return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');     // Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... }    case 'ViewInspection':      return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);    case 'UpdateInspection':    case 'SubmitInspection': {      const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);      if (roles.has('building_admin')) {        return true;      }      return roles.has('inspector') && resource.created_by === user.id;    }    case 'ApproveInspection':      // Separation of duties: nobody approves an inspection they created, whatever their role.      return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin')        && resource.created_by !== user.id;    case 'ReturnInspection':      return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');     default:      // An action without a rule is a bug. Fail loudly rather than allow.      throw new Error(`No authorization rule for action ${action}`);  }}

That is the entire switch. loadIssue still calls can(req.user, 'ViewIssue', issue); it does not know an engine changed.

The parity test from the last lesson compared Cedar with the JavaScript ViewIssue rule. That rule no longer exists: can() now is Cedar for this action, so the test would compare Cedar with itself. It did its job; remove it. The access matrix stays, and it is what protects behaviour from now on.

Runcaretaker/
git rm -q test/cedar-parity.test.js

Run and inspect

Run and comparecaretaker/
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) (489.743ms)
✔ edit issue 101 (30.258834ms)
✔ view issue 103 (building 20) (27.142375ms)
✔ edit issue 103 (reported by dave) (24.742375ms)
✔ report an issue at building 20 (22.311125ms)
✔ view issue 105 (building 30) (23.345542ms)
✔ view issue 106 (building 40, reported by bob) (23.422791ms)
✔ approve inspection 201 (created by dave) (18.353917ms)
✔ approve inspection 202 (created by alice) (20.704083ms)
✔ update organisation 1 (16.2675ms)
✔ issues in each user's list come only from the expected buildings (93.005833ms)
✔ the scenario loads exactly as specified (211.902083ms)
✔ only one active assignment per user, building and role (0.996708ms)
✔ a revoked role can be granted again (0.976292ms)
✔ the My access page shows what the server loaded (71.70675ms)
✔ a correct login creates a session and shows the user (273.03475ms)
✔ a wrong password or unknown email gets the same 401 (52.664375ms)
✔ registration validates, creates a user, and logs them in (41.741167ms)
✔ registering an existing email is a field error (34.859916ms)
✔ logout destroys the session (51.561ms)
✔ a building can be created inside an organisation (278.416125ms)
✔ a duplicate building name in the same organisation is a field error (4.486709ms)
✔ the same building name is allowed in another organisation (10.285625ms)
✔ a building with issues cannot be deleted (21.088584ms)
✔ an empty building can be deleted (10.557333ms)
✔ an organisation with buildings cannot be deleted, an empty one can (22.749459ms)
✔ a logged-in POST without a token is refused with 403 (261.090292ms)
✔ a token from another session is refused (37.403ms)
✔ the right token in the form field works (20.78875ms)
✔ every POST form on every page carries the token (46.871292ms)
✔ the dashboard counts match the database (294.092792ms)
✔ only the buildings carol can see appear (7.355292ms)
✔ create a draft, edit it, submit it, approve it (332.355208ms)
✔ invalid transitions are refused with 409 and change nothing (9.473542ms)
✔ only drafts can be edited (5.002792ms)
✔ returning a submitted inspection makes it editable again (6.988375ms)
Show 61 more lines✔ concurrent approvals: exactly one wins (22.133584ms) ✔ unknown actions are 404 (3.144542ms) ✔ the issues list contains only issues from visible buildings (543.087292ms) ✔ a filter for another tenant's building returns nothing (3.857875ms) ✔ the inspections list is scoped too (9.323667ms) ✔ organisations are listed for their members only (8.237666ms) ✔ the dashboard counts only visible data (6.685167ms) ✔ view issue 101 (building 10) (485.303792ms) ✔ open the edit form for issue 101 (30.620833ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (33.462334ms) ✔ view issue 105 (building 30) and 106 (building 40) (56.409291ms) ✔ report an issue at building 20 (19.874917ms) ✔ a reporter cannot edit their own issue once it is closed (10.252084ms) ✔ only building admins may delete; refusals change nothing (23.489916ms) ✔ the edit form cannot move an issue to another building (5.216959ms) ✔ the list pages 10 at a time and reports the total (264.277833ms) ✔ pages do not overlap (18.34725ms) ✔ filters combine with AND (5.596584ms) ✔ sorting by priority puts critical first when descending (5.146666ms) ✔ unknown sort keys and SQL in the query string are ignored (27.438458ms) ✔ GET /issues lists issues from the database (269.47625ms) ✔ GET /issues/101 shows one issue with its building (15.167042ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (15.353083ms) ✔ POST /issues re-renders the form with errors (4.316708ms) ✔ POST /issues stores the issue and redirects to it (9.20025ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.846917ms) ✔ the stored row has the cleaned values and ignores a client-sent status (5.859667ms) ✔ an issue time in the future is rejected (4.228084ms) ✔ GET /issues/101/edit shows the current values (6.637917ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.853708ms) ✔ POST /issues/:id/delete removes the issue (12.053291ms) ✔ GET /organisations lists organisations with building counts (270.955083ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.636084ms) ✔ POST /organisations validates and creates (13.540084ms) ✔ POST /organisations/:id/edit renames the organisation (8.556625ms) ✔ unknown organisations are 404 (6.267209ms) ✔ every policy is valid against the schema (24.545458ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (348.262167ms) ✔ anonymous requests are redirected to the login page (214.105042ms) ✔ anonymous writes are refused and change nothing (10.838875ms) ✔ login and register pages stay public (5.601875ms) ✔ login issues a new session id (no session fixation) (42.692375ms) ✔ returnTo only follows local paths (31.528125ms) ✔ new issues and transitions record the logged-in user (79.570833ms) ✔ the session cookie has the attributes we chose (25.981416ms) ✔ organisation 1: view and update (466.000583ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.140625ms) ✔ building 10: view, update, delete (48.492625ms) ✔ creating buildings needs org_admin (20.968208ms) ✔ creating an organisation makes the creator its admin (8.6945ms) ✔ inspections: view 201, open the edit form for draft 203 (40.222917ms) ✔ approve inspection 201 (dave's): only building admins (15.107458ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (10.42475ms) ℹ tests 89 ℹ suites 0 ℹ pass 89 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 9258.653416

All 89 tests pass, including every ViewIssue cell of the access matrix and the issue tests from Modules 3 to 5. The behaviour did not change; the engine did.

Watch the decisions as they happen:

Server terminal (leave it running)caretaker/
AUTHZ_LOG=1 npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000
Run and comparecaretaker/
rm -f /tmp/alice.txt
TOKEN=$(curl -s -c /tmp/alice.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/alice.txt -c /tmp/alice.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=alice@example.test -d password=password123
for id in 101 105; do curl -s -o /dev/null -w "GET /issues/$id -> %{http_code}\n" -b /tmp/alice.txt http://localhost:3000/issues/$id; done
GET /issues/101 -> 200
GET /issues/105 -> 404
Server terminal output
authz user=1 action=ViewIssue resource=Issue::101 decision=allow reasons=view-issue
GET /issues/101 -> 200 (44 ms)
authz user=1 action=ViewIssue resource=Issue::105 decision=deny reasons=-
GET /issues/105 -> 404 (17 ms)

Two lines per request: Cedar's decision, then the request log. For issue 101 the reason is view-issue; for issue 105 the reason is empty (implicit deny), and the route turned the deny into 404. The template for issue 101 also asked can('UpdateIssue', ...) and can('DeleteIssue', ...); those are still JavaScript, so they do not appear in the Cedar log yet.

Here is the same request as a sequence you can step through, with the values recorded from the reference application at the end of the course:

Loading interactive explorer…

Experiment

The policy store is now part of the application. What happens if someone commits a broken policy?

Predict A teammate renames the attribute in view-issue.cedar to principal.viewerBuildings and starts the app. What happens?
Editsrc/authz/policies/view-issue.cedarCedar
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
when { principal.issueViewerBuildings.contains(resource.building) };when { principal.viewerBuildings.contains(resource.building) };
Show the whole src/authz/policies/view-issue.cedar after this change
// Users may view an issue at any building where they can view issues.permit (  principal,  action == Caretaker::Action::"ViewIssue",  resource)when { principal.viewerBuildings.contains(resource.building) };
Ctrl+C Stop the server in the server terminal.
Run and comparecaretaker/exit code 1 (expected)
node --env-file=.env src/server.js
file:///Users/you/code/caretaker/src/authz/cedar.js:12
  throw new Error(`The Cedar policy store is invalid:\n${problems.join('\n')}`);
        ^

Error: The Cedar policy store is invalid:
view-issue: for policy `view-issue`, attribute `viewerBuildings` on entity type `Caretaker::User` not found
    at file:///Users/you/code/caretaker/src/authz/cedar.js:12:9
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

Node.js v22.23.1
Reveal Answer

The app refuses to start, and says exactly which policy is wrong and why. The alternative, an app that starts and then denies every issue view at runtime, is much harder to notice and diagnose. The same check runs in npm test (test/policies.test.js), so a broken policy should never reach a running server in the first place.

Restore the policy:

Editsrc/authz/policies/view-issue.cedarCedar
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
when { principal.viewerBuildings.contains(resource.building) };when { principal.issueViewerBuildings.contains(resource.building) };
Show the whole src/authz/policies/view-issue.cedar after this change
// Users may view an issue at any building where they can view issues.permit (  principal,  action == Caretaker::Action::"ViewIssue",  resource)when { principal.issueViewerBuildings.contains(resource.building) };

Checkpoint

Run and comparecaretaker/
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) (439.838584ms)
✔ edit issue 101 (33.36375ms)
✔ view issue 103 (building 20) (34.0495ms)
✔ edit issue 103 (reported by dave) (31.142583ms)
✔ report an issue at building 20 (24.188791ms)
✔ view issue 105 (building 30) (23.178125ms)
✔ view issue 106 (building 40, reported by bob) (23.047917ms)
✔ approve inspection 201 (created by dave) (15.20475ms)
✔ approve inspection 202 (created by alice) (19.356667ms)
✔ update organisation 1 (14.808458ms)
✔ issues in each user's list come only from the expected buildings (93.823083ms)
✔ the scenario loads exactly as specified (202.42975ms)
✔ only one active assignment per user, building and role (0.90275ms)
✔ a revoked role can be granted again (1.414792ms)
✔ the My access page shows what the server loaded (73.911833ms)
✔ a correct login creates a session and shows the user (267.019292ms)
✔ a wrong password or unknown email gets the same 401 (54.645167ms)
✔ registration validates, creates a user, and logs them in (47.580333ms)
✔ registering an existing email is a field error (32.251125ms)
✔ logout destroys the session (44.255292ms)
✔ a building can be created inside an organisation (265.698625ms)
✔ a duplicate building name in the same organisation is a field error (4.566208ms)
✔ the same building name is allowed in another organisation (9.943667ms)
✔ a building with issues cannot be deleted (19.371625ms)
✔ an empty building can be deleted (10.397916ms)
✔ an organisation with buildings cannot be deleted, an empty one can (23.054583ms)
✔ a logged-in POST without a token is refused with 403 (280.3075ms)
✔ a token from another session is refused (37.1985ms)
✔ the right token in the form field works (21.997167ms)
✔ every POST form on every page carries the token (47.665166ms)
✔ the dashboard counts match the database (264.414584ms)
✔ only the buildings carol can see appear (5.748083ms)
✔ create a draft, edit it, submit it, approve it (325.781542ms)
✔ invalid transitions are refused with 409 and change nothing (10.500667ms)
✔ only drafts can be edited (5.297375ms)
✔ returning a submitted inspection makes it editable again (6.9985ms)
Show 61 more lines✔ concurrent approvals: exactly one wins (21.950958ms) ✔ unknown actions are 404 (2.876625ms) ✔ the issues list contains only issues from visible buildings (536.153084ms) ✔ a filter for another tenant's building returns nothing (3.894959ms) ✔ the inspections list is scoped too (9.799833ms) ✔ organisations are listed for their members only (8.573708ms) ✔ the dashboard counts only visible data (7.1615ms) ✔ view issue 101 (building 10) (474.409584ms) ✔ open the edit form for issue 101 (28.65475ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (28.063542ms) ✔ view issue 105 (building 30) and 106 (building 40) (46.182334ms) ✔ report an issue at building 20 (20.136084ms) ✔ a reporter cannot edit their own issue once it is closed (8.170792ms) ✔ only building admins may delete; refusals change nothing (18.870125ms) ✔ the edit form cannot move an issue to another building (4.573084ms) ✔ the list pages 10 at a time and reports the total (285.164417ms) ✔ pages do not overlap (16.559167ms) ✔ filters combine with AND (5.581709ms) ✔ sorting by priority puts critical first when descending (5.517625ms) ✔ unknown sort keys and SQL in the query string are ignored (30.709708ms) ✔ GET /issues lists issues from the database (280.495166ms) ✔ GET /issues/101 shows one issue with its building (13.673917ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (16.293375ms) ✔ POST /issues re-renders the form with errors (4.59675ms) ✔ POST /issues stores the issue and redirects to it (10.413459ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.070625ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.145083ms) ✔ an issue time in the future is rejected (3.580542ms) ✔ GET /issues/101/edit shows the current values (5.46725ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.520958ms) ✔ POST /issues/:id/delete removes the issue (11.813958ms) ✔ GET /organisations lists organisations with building counts (271.041209ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (6.49625ms) ✔ POST /organisations validates and creates (12.515917ms) ✔ POST /organisations/:id/edit renames the organisation (11.692625ms) ✔ unknown organisations are 404 (6.784083ms) ✔ every policy is valid against the schema (24.585ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (350.217333ms) ✔ anonymous requests are redirected to the login page (217.626917ms) ✔ anonymous writes are refused and change nothing (11.625ms) ✔ login and register pages stay public (5.948667ms) ✔ login issues a new session id (no session fixation) (32.998792ms) ✔ returnTo only follows local paths (30.003333ms) ✔ new issues and transitions record the logged-in user (67.280834ms) ✔ the session cookie has the attributes we chose (25.816083ms) ✔ organisation 1: view and update (505.8095ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.311625ms) ✔ building 10: view, update, delete (53.687209ms) ✔ creating buildings needs org_admin (15.754625ms) ✔ creating an organisation makes the creator its admin (9.771333ms) ✔ inspections: view 201, open the edit form for draft 203 (39.598333ms) ✔ approve inspection 201 (dave's): only building admins (16.994833ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (10.872917ms) ℹ tests 89 ℹ suites 0 ℹ pass 89 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 9242.365833
Run and comparecaretaker/
git add -A
git commit -m "Cedar decides ViewIssue"
[main 2862a15] Cedar decides ViewIssue
 5 files changed, 49 insertions(+), 39 deletions(-)
 create mode 100644 src/authz/authorize.js
 create mode 100644 src/authz/cedar.js
 delete mode 100644 test/cedar-parity.test.js
Symptom Every issue is 404 after the switch

Run npm run authz:explain -- alice ViewIssue 101. If the explain output says allow but the app denies, the app's user object differs from the script's: check that loadUser uses loadAccess (with orgAdminBuildings) for req.user.access.

Symptom authz problem lines in the server log

Read the errors field. A failure means the request or entities did not match the schema; an evaluation error names the policy that could not be evaluated. Both are bugs in the mapper or the policies, and the request was denied.

Recap and next step

The policy store is loaded and validated once; an invalid store stops the app. evaluate fails closed. authorize builds the call from server-side data, evaluates it and logs IDs and policy reasons. can() now delegates ViewIssue to Cedar, and the unchanged test suite shows the behaviour is identical.

One action down, sixteen to go. Next we move all of them, and the schema and the mapper grow to carry what each policy needs.