Caretaker Express · PostgreSQL · Cedar

Module 8 · Lists, writes and multi-tenant isolation

8.1 Lists and policies, kept aligned

Understand why Cedar cannot filter a list for you, prove that the SQL list filter and the Cedar policies agree for every user and record, add a per-item guard, make per-item decisions fast, and look at partial evaluation honestly.

≈ 45 min 19 steps 101 lines of code Replay verified

Starting point

Single-resource decisions come from Cedar. The issues and inspections lists are filtered in SQL by visibleBuildingCondition (lesson 5.3), which encodes the same rule as the building-read policy, in another language.

Outcome

Text
test/list-parity.test.js     (new: SQL lists and Cedar agree for every user and record)src/routes/issues.js         (a per-item guard on the list page)src/authz/cedar.js           (pre-parsed policies: much faster per decision)scripts/authz-bench.js       (new)scripts/partial-demo.js      (new)

You can explain how a collection is authorized correctly, why the SQL filter is not "generated by Cedar", and how we would notice if the two ever disagree.

The problem

Cedar answers: may this principal do this action on this resource? A list page asks a different question: which resources may this principal see? Three ways to answer it, and why two are wrong:

  1. Fetch everything, ask Cedar per row, show the allowed ones. Correct for ten rows. For a real tenant database it fetches every company's records on every page view, and paging breaks: LIMIT 10 OFFSET 20 is applied before the filter, so a page could show three rows, or none, and the total count is wrong. Lesson 5.3 showed this.
  2. Send everything to the browser and hide what the user may not see. Never. Hidden is not protected: the data is in the response, readable with "view source" or curl.
  3. Filter in the query, with a condition that implements the same rule as the policy. Correct and efficient. The cost: the rule exists twice, once in Cedar and once in SQL.

We use the third. Cedar does not generate our SQL. So the honest engineering task is to make the duplication safe: prove the two agree, and detect it at runtime if they ever do not.

Build it

1. A parity test

For every seeded user and every issue and inspection in the database, the list must contain exactly the records Cedar allows. Create test/list-parity.test.js:

Create filetest/list-parity.test.jsJavaScript
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { can } from '../src/authz/rules.js';import { listIssues, findIssue } from '../src/models/issues.js';import { listInspections, findInspection } from '../src/models/inspections.js';import { resetDatabase, loadUserNamed } from './helpers.js'; const USERS = ['alice', 'bob', 'carol', 'dave', 'nora', 'ravi'];before(resetDatabase);after(() => pool.end()); test('the issues list contains exactly the issues Cedar lets each user view', async () => {  const { rows } = await pool.query('SELECT id FROM issues ORDER BY id');  const mismatches = [];  for (const name of USERS) {    const user = await loadUserNamed(name);    const listed = new Set((await listIssues({ userId: user.id, perPage: 1000 })).issues.map((e) => e.id));    for (const { id } of rows) {      const allowed = can(user, 'ViewIssue', await findIssue(id));      if (allowed !== listed.has(id)) mismatches.push(`${name} issue ${id}: cedar=${allowed} list=${listed.has(id)}`);    }  }  assert.deepEqual(mismatches, []);}); test('the inspections list contains exactly the inspections Cedar lets each user view', async () => {  const { rows } = await pool.query('SELECT id FROM inspections ORDER BY id');  const mismatches = [];  for (const name of USERS) {    const user = await loadUserNamed(name);    const listed = new Set((await listInspections({ userId: user.id })).map((a) => a.id));    for (const { id } of rows) {      const allowed = can(user, 'ViewInspection', await findInspection(id));      if (allowed !== listed.has(id)) mismatches.push(`${name} inspection ${id}: cedar=${allowed} list=${listed.has(id)}`);    }  }  assert.deepEqual(mismatches, []);});

It checks 6 users × 30 issues and 6 users × 4 inspections, both directions: nothing listed that Cedar denies (a leak), and nothing hidden that Cedar allows (a usability bug).

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) (530.565625ms)
✔ edit issue 101 (100.542666ms)
✔ view issue 103 (building 20) (73.069959ms)
✔ edit issue 103 (reported by dave) (94.457541ms)
✔ report an issue at building 20 (117.924291ms)
✔ view issue 105 (building 30) (51.762375ms)
✔ view issue 106 (building 40, reported by bob) (45.696583ms)
✔ approve inspection 201 (created by dave) (56.010167ms)
✔ approve inspection 202 (created by alice) (61.388708ms)
✔ update organisation 1 (60.617542ms)
✔ change own role at building 10 (18.372792ms)
✔ grant building_admin at building 10 to dave (73.400166ms)
✔ grant viewer at building 10 to dave (62.330625ms)
✔ issues in each user's list come only from the expected buildings (100.539209ms)
✔ the scenario loads exactly as specified (215.639584ms)
✔ only one active assignment per user, building and role (0.920084ms)
✔ a revoked role can be granted again (0.897125ms)
✔ the My access page shows what the server loaded (73.035584ms)
✔ a correct login creates a session and shows the user (263.352709ms)
✔ a wrong password or unknown email gets the same 401 (53.055125ms)
✔ registration validates, creates a user, and logs them in (40.449292ms)
✔ registering an existing email is a field error (26.5655ms)
✔ logout destroys the session (53.470875ms)
✔ allow: a permit matched and nothing forbade it (227.82225ms)
✔ explicit deny: a forbid overrides a matching permit (7.009916ms)
✔ implicit deny: no permit matched (6.354083ms)
authz problem {
  user: 1,
  action: 'ApproveInspection',
  resource: 'Inspection::201',
  decision: 'failure',
  errors: [
    'entity does not conform to the schema: in attribute `status` on `Caretaker::Inspection::"201"`, type mismatch: value was expected to have type string, but it actually has type long: `7`'
  ]
}
✔ failure: a row that does not fit the schema is never allowed (7.132125ms)
Show 92 more lines✔ unknown actions throw instead of deciding (1.691125ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (423.586708ms) ✔ a revoked assignment cannot be revoked again (13.473125ms) ✔ an assignment id from another building is not found here (13.727625ms) ✔ alice cannot revoke her own building_admin role; carol can (43.622959ms) ✔ grants are limited to members of the building's organisation (19.446375ms) ✔ a building can be created inside an organisation (310.185583ms) ✔ a duplicate building name in the same organisation is a field error (13.589708ms) ✔ the same building name is allowed in another organisation (16.378042ms) ✔ a building with issues cannot be deleted (43.664083ms) ✔ an empty building can be deleted (24.543458ms) ✔ an organisation with buildings cannot be deleted, an empty one can (61.074208ms) ✔ a logged-in POST without a token is refused with 403 (280.442ms) ✔ a token from another session is refused (36.374625ms) ✔ the right token in the form field works (36.929375ms) ✔ every POST form on every page carries the token (193.062334ms) ✔ the dashboard counts match the database (273.675292ms) ✔ only the buildings carol can see appear (6.627041ms) ✔ create a draft, edit it, submit it, approve it (441.447208ms) ✔ invalid transitions are refused with 409 and change nothing (51.270125ms) ✔ only drafts can be edited (20.51675ms) ✔ returning a submitted inspection makes it editable again (22.302375ms) ✔ concurrent approvals: exactly one wins (96.60225ms) ✔ unknown actions are 404 (3.424875ms) ✔ the issues list contains only issues from visible buildings (566.703708ms) ✔ a filter for another tenant's building returns nothing (4.302209ms) ✔ the inspections list is scoped too (10.007125ms) ✔ organisations are listed for their members only (8.911333ms) ✔ the dashboard counts only visible data (7.355708ms) ✔ view issue 101 (building 10) (544.558583ms) ✔ open the edit form for issue 101 (97.805625ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (99.926375ms) ✔ view issue 105 (building 30) and 106 (building 40) (101.861792ms) ✔ report an issue at building 20 (98.977083ms) ✔ a reporter cannot edit their own issue once it is closed (31.996375ms) ✔ only building admins may delete; refusals change nothing (40.496625ms) ✔ the edit form cannot move an issue to another building (16.135958ms) ✔ the list pages 10 at a time and reports the total (285.098958ms) ✔ pages do not overlap (16.764583ms) ✔ filters combine with AND (5.633416ms) ✔ sorting by priority puts critical first when descending (5.16825ms) ✔ unknown sort keys and SQL in the query string are ignored (29.964042ms) ✔ GET /issues lists issues from the database (275.853208ms) ✔ GET /issues/101 shows one issue with its building (23.491458ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (19.02975ms) ✔ POST /issues re-renders the form with errors (20.129625ms) ✔ POST /issues stores the issue and redirects to it (32.027834ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (18.8975ms) ✔ the stored row has the cleaned values and ignores a client-sent status (9.979792ms) ✔ an issue time in the future is rejected (18.078ms) ✔ GET /issues/101/edit shows the current values (24.710208ms) ✔ POST /issues/:id/edit changes the status and updated_at (12.33075ms) ✔ POST /issues/:id/delete removes the issue (21.897667ms) ✔ the issues list contains exactly the issues Cedar lets each user view (1064.581125ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (118.280166ms) ✔ only organisation admins can open the members page (486.306833ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (61.629583ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (53.254958ms) ✔ nobody changes their own membership (18.308208ms) ✔ unknown emails and roles are form errors (29.54825ms) ✔ a member cannot add members, even with a well-formed request (9.671ms) ✔ GET /organisations lists organisations with building counts (274.957125ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (39.275041ms) ✔ POST /organisations validates and creates (35.252958ms) ✔ POST /organisations/:id/edit renames the organisation (39.75525ms) ✔ unknown organisations are 404 (9.048375ms) ✔ every policy is valid against the schema (39.540542ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.720833ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (356.410708ms) ✔ anonymous requests are redirected to the login page (215.033334ms) ✔ anonymous writes are refused and change nothing (10.965083ms) ✔ login and register pages stay public (5.60975ms) ✔ login issues a new session id (no session fixation) (32.286459ms) ✔ returnTo only follows local paths (28.235458ms) ✔ new issues and transitions record the logged-in user (112.245875ms) ✔ the session cookie has the attributes we chose (29.265875ms) ✔ organisation 1: view and update (599.377667ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (32.856125ms) ✔ building 10: view, update, delete (159.581292ms) ✔ creating buildings needs org_admin (43.494416ms) ✔ creating an organisation makes the creator its admin (19.476375ms) ✔ inspections: view 201, open the edit form for draft 203 (125.897709ms) ✔ approve inspection 201 (dave's): only building admins (44.774208ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (54.152834ms) ℹ tests 111 ℹ suites 0 ℹ pass 111 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 15104.784875

They agree today. Now see what the test is for.

2. A per-item guard on the list page

The parity test runs on seeded data. At runtime we add a cheap second line of defence: after the SQL returns a page, ask Cedar about each row on it, drop any row Cedar denies, and log loudly if that ever happens. In src/routes/issues.js:

Editsrc/routes/issues.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  const { issues, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });  const { issues: rows, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });  // Defence in depth: the SQL filter should already match the policies. If a row on  // this page is denied by Cedar, hide it and report it: the two have drifted apart.  const issues = rows.filter((issue) => can(req.user, 'ViewIssue', issue));  if (issues.length !== rows.length) {    console.error('list/policy mismatch', { user: req.user.id, hidden: rows.filter((e) => !issues.includes(e)).map((e) => e.id) });  }  const buildings = await listVisibleBuildings(req.user.id);
Show the whole src/routes/issues.js after this change
import express from 'express';import { listIssues, findIssue, createIssue, updateIssue, deleteIssue, ISSUE_SORTS } from '../models/issues.js';import { listBuildings, findBuilding, listVisibleBuildings } from '../models/buildings.js';import { can } from '../authz/rules.js';import { notFound, forbidden } from '../lib/http.js';import { PG_ERRORS } from '../db.js';import { parseId } from '../lib/ids.js';import { cleanText } from '../lib/validation.js'; export const issuesRouter = express.Router(); export const PRIORITIES = ['low', 'medium', 'high', 'critical'];export const STATUSES = ['open', 'investigating', 'closed'];const FIVE_MINUTES = 5 * 60 * 1000; // <input type="datetime-local"> sends "2026-11-02T09:15" without a time zone. We treat it as UTC.function parseDateTimeLocal(value) {  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) {    return null;  }  const date = new Date(`${value}:00Z`);  return Number.isNaN(date.getTime()) ? null : date;} // The reverse: a Date as "YYYY-MM-DDTHH:MM" in UTC, for the input's value attribute.function toDateTimeLocal(date) {  return new Date(date).toISOString().slice(0, 16);} function validateIssue(input, { editing }) {  const errors = {};  const title = cleanText(input.title, { min: 3, max: 200 });  const description = cleanText(input.description, { max: 2000 });  const buildingId = parseId(input.building_id);  const occurredAt = parseDateTimeLocal(input.occurred_at);  const status = editing ? input.status : 'open';  if (!title.ok) {    errors.title = 'Title must be between 3 and 200 characters.';  }  if (!description.ok) {    errors.description = 'Description must be at most 2000 characters.';  }  if (!PRIORITIES.includes(input.priority)) {    errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;  }  if (!editing && buildingId === null) {    errors.building_id = 'Choose a building.';  }  if (!occurredAt) {    errors.occurred_at = 'Enter the date and time it happened (UTC).';  } else if (occurredAt.getTime() > Date.now() + FIVE_MINUTES) {    errors.occurred_at = 'That time is in the future.';  }  if (!STATUSES.includes(status)) {    errors.status = `Status must be one of: ${STATUSES.join(', ')}.`;  }  // values: what the form shows again. record: what we store.  const values = {    title: title.text,    description: description.text,    priority: input.priority,    building_id: buildingId,    status,    occurred_at: typeof input.occurred_at === 'string' ? input.occurred_at : '',  };  const record = { ...values, occurred_at: occurredAt };  return { errors, values, record };} async function renderIssueForm(req, res, status, { issue = null, values = {}, errors = {} } = {}) {  const buildings = (await listBuildings()).filter((building) => can(req.user, 'CreateIssue', building));  res.status(status).render('issues/form', {    title: issue ? `Edit issue #${issue.id}` : 'Report an issue',    action: issue ? `/issues/${issue.id}/edit` : '/issues',    issue,    values,    errors,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,  });} const PER_PAGE = 10; // Converts the query string into list options. Invalid values become defaults.function parseListQuery(query) {  const page = parseId(query.page) ?? 1;  return {    page,    sort: Object.hasOwn(ISSUE_SORTS, query.sort) ? query.sort : 'occurred_at',    dir: query.dir === 'asc' ? 'asc' : 'desc',    status: STATUSES.includes(query.status) ? query.status : null,    priority: PRIORITIES.includes(query.priority) ? query.priority : null,    building: parseId(query.building),  };} // Builds a /issues URL from the current options plus overrides, dropping defaults.function listUrl(options, overrides = {}) {  const merged = { ...options, ...overrides };  const params = new URLSearchParams();  for (const [key, value] of Object.entries(merged)) {    const isDefault = value === null || (key === 'page' && value === 1) || (key === 'sort' && value === 'occurred_at') || (key === 'dir' && value === 'desc');    if (!isDefault) params.set(key, String(value));  }  const qs = params.toString();  return qs ? `/issues?${qs}` : '/issues';} async function loadIssue(req, res) {  const id = parseId(req.params.id);  const issue = id === null ? null : await findIssue(id);  if (!issue || !can(req.user, 'ViewIssue', issue)) {    notFound(req, res);    return null;  }  return issue;} issuesRouter.get('/', async (req, res) => {  const options = parseListQuery(req.query);  const { issues: rows, total } = await listIssues({ ...options, buildingId: options.building, perPage: PER_PAGE, userId: req.user.id });  // Defence in depth: the SQL filter should already match the policies. If a row on  // this page is denied by Cedar, hide it and report it: the two have drifted apart.  const issues = rows.filter((issue) => can(req.user, 'ViewIssue', issue));  if (issues.length !== rows.length) {    console.error('list/policy mismatch', { user: req.user.id, hidden: rows.filter((e) => !issues.includes(e)).map((e) => e.id) });  }  const buildings = await listVisibleBuildings(req.user.id);  res.render('issues/index', {    title: 'Maintenance issues',    issues,    total,    options,    buildings,    priorities: PRIORITIES,    statuses: STATUSES,    totalPages: Math.max(1, Math.ceil(total / PER_PAGE)),    listUrl: (overrides) => listUrl(options, overrides),  });}); issuesRouter.get('/new', async (req, res) => {  await renderIssueForm(req, res, 200, { values: { occurred_at: toDateTimeLocal(new Date()) } });}); issuesRouter.post('/', async (req, res) => {  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: false });  if (Object.keys(errors).length > 0) {    return renderIssueForm(req, res, 400, { values, errors });  }  // The building id came from the form. Load the real building and check the user may report there.  const building = await findBuilding(record.building_id);  if (!building || !can(req.user, 'CreateIssue', building)) {    return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building where you can report issues.' } });  }  let created;  try {    created = await createIssue(record, req.user.id);  } catch (err) {    if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {      return renderIssueForm(req, res, 400, { values, errors: { building_id: 'Choose a building.' } });    }    throw err;  }  res.redirect(303, `/issues/${created.id}`);}); issuesRouter.get('/:id', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  res.render('issues/show', { title: issue.title, issue });}); issuesRouter.get('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);  await renderIssueForm(req, res, 200, { issue, values: { ...issue, occurred_at: toDateTimeLocal(issue.occurred_at) } });}); issuesRouter.post('/:id/edit', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'UpdateIssue', issue)) return forbidden(res);  const { errors, values, record } = validateIssue(req.body ?? {}, { editing: true });  if (Object.keys(errors).length > 0) {    return renderIssueForm(req, res, 400, { issue, values, errors });  }  // The edit form cannot move an issue: the building stays the one we loaded.  await updateIssue(issue.id, { ...record, building_id: issue.building_id });  res.redirect(303, `/issues/${issue.id}`);}); issuesRouter.post('/:id/delete', async (req, res) => {  const issue = await loadIssue(req, res);  if (!issue) return;  if (!can(req.user, 'DeleteIssue', issue)) return forbidden(res);  await deleteIssue(issue.id);  res.redirect(303, '/issues');});

This guard is not the filter: it only sees the ten rows of one page, and the total count still comes from SQL. Its job is to stop a leak in the moment and to tell you that the parity broke.

3. Make per-item decisions cheap

A list page now makes at least ten decisions. Measure what one costs. Create scripts/authz-bench.js:

Create filescripts/authz-bench.jsJavaScript
// Measures the average time of one authorization decision, end to end through authorize().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 { authorize } from '../src/authz/authorize.js'; const user = await findUserById(1);user.access = await loadAccess(1);const issue = await findIssue(101);authorize(user, 'ViewIssue', issue);const runs = 2000;const started = performance.now();for (let i = 0; i < runs; i++) authorize(user, 'ViewIssue', issue);console.log(`${((performance.now() - started) / runs).toFixed(3)} ms per decision (${runs} runs)`);await pool.end();
Run and comparecaretaker/
node --env-file=.env scripts/authz-bench.js
2.824 ms per decision (2000 runs)

Most of that time is Cedar parsing the schema and twelve policies again on every call. The engine can parse them once and keep the result: preparseSchema and preparsePolicySet store parsed copies under a name, and statefulIsAuthorized evaluates against them. Change src/authz/cedar.js:

Editsrc/authz/cedar.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
export const policyIds = Object.keys(policies); // Parse once and keep the parsed copies inside the engine, under these names.const SCHEMA_NAME = 'caretaker';const POLICY_SET_ID = 'caretaker';for (const result of [cedar.preparseSchema(SCHEMA_NAME, schema), cedar.preparsePolicySet(POLICY_SET_ID, { staticPolicies: policies })]) {  if (result.type !== 'success') {    throw new Error(`Could not pre-parse the policy store: ${result.errors.map((e) => e.message).join('; ')}`);  }}
Change 2 of 2
  const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } });  const answer = cedar.statefulIsAuthorized({ ...call, preparsedSchemaName: SCHEMA_NAME, preparsedPolicySetId: POLICY_SET_ID, validateRequest: true });
Show the whole src/authz/cedar.js after this change
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); // Parse once and keep the parsed copies inside the engine, under these names.const SCHEMA_NAME = 'caretaker';const POLICY_SET_ID = 'caretaker';for (const result of [cedar.preparseSchema(SCHEMA_NAME, schema), cedar.preparsePolicySet(POLICY_SET_ID, { staticPolicies: policies })]) {  if (result.type !== 'success') {    throw new Error(`Could not pre-parse the policy store: ${result.errors.map((e) => e.message).join('; ')}`);  }} // 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.statefulIsAuthorized({ ...call, preparsedSchemaName: SCHEMA_NAME, preparsedPolicySetId: POLICY_SET_ID, validateRequest: true });  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 };}
Run and comparecaretaker/
node --env-file=.env scripts/authz-bench.js
0.136 ms per decision (2000 runs)

Compare the two numbers. On the machine that recorded this course, one decision through authorize() went from about 2.8 ms to about 0.13 ms. The decisions are the same (the full test suite below proves it); only repeated parsing went away. The entity mapping and the WebAssembly call remain.

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) (483.650416ms)
✔ edit issue 101 (24.950292ms)
✔ view issue 103 (building 20) (25.163875ms)
✔ edit issue 103 (reported by dave) (23.093916ms)
✔ report an issue at building 20 (27.990708ms)
✔ view issue 105 (building 30) (18.525583ms)
✔ view issue 106 (building 40, reported by bob) (19.445417ms)
✔ approve inspection 201 (created by dave) (16.608208ms)
✔ approve inspection 202 (created by alice) (22.241875ms)
✔ update organisation 1 (22.7645ms)
✔ change own role at building 10 (4.933458ms)
✔ grant building_admin at building 10 to dave (20.601208ms)
✔ grant viewer at building 10 to dave (20.351917ms)
✔ issues in each user's list come only from the expected buildings (123.09275ms)
✔ the scenario loads exactly as specified (213.093ms)
✔ only one active assignment per user, building and role (0.9195ms)
✔ a revoked role can be granted again (1.244958ms)
✔ the My access page shows what the server loaded (74.236291ms)
✔ a correct login creates a session and shows the user (268.426ms)
✔ a wrong password or unknown email gets the same 401 (54.670625ms)
✔ registration validates, creates a user, and logs them in (46.971625ms)
✔ registering an existing email is a field error (31.177833ms)
✔ logout destroys the session (54.377875ms)
✔ allow: a permit matched and nothing forbade it (240.949083ms)
✔ explicit deny: a forbid overrides a matching permit (3.438584ms)
✔ implicit deny: no permit matched (2.469958ms)
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 (3.277375ms)
Show 92 more lines✔ unknown actions throw instead of deciding (1.47225ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (403.010416ms) ✔ a revoked assignment cannot be revoked again (4.987416ms) ✔ an assignment id from another building is not found here (5.766542ms) ✔ alice cannot revoke her own building_admin role; carol can (13.59075ms) ✔ grants are limited to members of the building's organisation (6.431084ms) ✔ a building can be created inside an organisation (291.237041ms) ✔ a duplicate building name in the same organisation is a field error (6.979959ms) ✔ the same building name is allowed in another organisation (13.965625ms) ✔ a building with issues cannot be deleted (14.139125ms) ✔ an empty building can be deleted (10.20325ms) ✔ an organisation with buildings cannot be deleted, an empty one can (26.709084ms) ✔ a logged-in POST without a token is refused with 403 (280.224875ms) ✔ a token from another session is refused (36.388875ms) ✔ the right token in the form field works (22.829083ms) ✔ every POST form on every page carries the token (56.22225ms) ✔ the dashboard counts match the database (276.57625ms) ✔ only the buildings carol can see appear (5.016916ms) ✔ create a draft, edit it, submit it, approve it (348.361167ms) ✔ invalid transitions are refused with 409 and change nothing (11.808333ms) ✔ only drafts can be edited (5.940416ms) ✔ returning a submitted inspection makes it editable again (8.145417ms) ✔ concurrent approvals: exactly one wins (28.304084ms) ✔ unknown actions are 404 (3.15125ms) ✔ the issues list contains only issues from visible buildings (588.639209ms) ✔ a filter for another tenant's building returns nothing (3.71225ms) ✔ the inspections list is scoped too (9.75875ms) ✔ organisations are listed for their members only (8.655916ms) ✔ the dashboard counts only visible data (8.919167ms) ✔ view issue 101 (building 10) (475.041709ms) ✔ open the edit form for issue 101 (25.730584ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (24.43475ms) ✔ view issue 105 (building 30) and 106 (building 40) (39.884584ms) ✔ report an issue at building 20 (32.831958ms) ✔ a reporter cannot edit their own issue once it is closed (10.38425ms) ✔ only building admins may delete; refusals change nothing (14.92425ms) ✔ the edit form cannot move an issue to another building (4.154042ms) ✔ the list pages 10 at a time and reports the total (298.365458ms) ✔ pages do not overlap (23.1075ms) ✔ filters combine with AND (6.992041ms) ✔ sorting by priority puts critical first when descending (6.834917ms) ✔ unknown sort keys and SQL in the query string are ignored (40.951125ms) ✔ GET /issues lists issues from the database (282.712958ms) ✔ GET /issues/101 shows one issue with its building (8.547042ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (16.043667ms) ✔ POST /issues re-renders the form with errors (5.716083ms) ✔ POST /issues stores the issue and redirects to it (9.151541ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.987458ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.222292ms) ✔ an issue time in the future is rejected (4.319ms) ✔ GET /issues/101/edit shows the current values (5.373584ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.041ms) ✔ POST /issues/:id/delete removes the issue (10.381042ms) ✔ the issues list contains exactly the issues Cedar lets each user view (323.255041ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (20.93175ms) ✔ only organisation admins can open the members page (414.979042ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (14.6425ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (11.915042ms) ✔ nobody changes their own membership (4.009042ms) ✔ unknown emails and roles are form errors (9.705583ms) ✔ a member cannot add members, even with a well-formed request (3.268958ms) ✔ GET /organisations lists organisations with building counts (273.284709ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (15.415ms) ✔ POST /organisations validates and creates (13.780541ms) ✔ POST /organisations/:id/edit renames the organisation (11.078541ms) ✔ unknown organisations are 404 (6.157125ms) ✔ every policy is valid against the schema (32.192125ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.55025ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (355.323791ms) ✔ anonymous requests are redirected to the login page (211.5065ms) ✔ anonymous writes are refused and change nothing (10.832875ms) ✔ login and register pages stay public (6.180042ms) ✔ login issues a new session id (no session fixation) (31.765917ms) ✔ returnTo only follows local paths (28.360292ms) ✔ new issues and transitions record the logged-in user (87.657625ms) ✔ the session cookie has the attributes we chose (29.006166ms) ✔ organisation 1: view and update (492.759958ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.770458ms) ✔ building 10: view, update, delete (63.023292ms) ✔ creating buildings needs org_admin (17.163958ms) ✔ creating an organisation makes the creator its admin (8.753ms) ✔ inspections: view 201, open the edit form for draft 203 (50.402625ms) ✔ approve inspection 201 (dave's): only building admins (16.109875ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (16.023292ms) ℹ tests 111 ℹ suites 0 ℹ pass 111 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 12002.445959
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/bob.txt
TOKEN=$(curl -s -c /tmp/bob.txt http://localhost:3000/login | sed -n 's/.*name="csrf-token" content="\([^"]*\)".*/\1/p')
curl -s -b /tmp/bob.txt -c /tmp/bob.txt -o /dev/null http://localhost:3000/login -d _csrf=$TOKEN -d email=bob@example.test -d password=password123
curl -s -o /dev/null -w "%{http_code}\n" -b /tmp/bob.txt http://localhost:3000/issues
200
Server terminal output
POST /login -> 303 (48 ms)
authz user=2 action=ViewIssue resource=Issue::105 decision=allow reasons=building-read
GET /issues -> 200 (47 ms)

Bob's list had one row (issue 105, the only issue at building 30), and the guard asked Cedar about it. No list/policy mismatch line.

Ctrl+C Stop the server in the server terminal.

What about generating the filter from the policies?

Cedar has an API called partial evaluation: evaluate the policies with the resource left unknown, and get back the conditions that would still have to be true. Create scripts/partial-demo.js:

Create filescripts/partial-demo.jsJavaScript
// Partial evaluation: what must be true of an unknown resource for Alice to view it?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 { loadPolicyStore } from '../src/authz/policy-store.js';import { userEntity, ref } from '../src/authz/entities.js'; const name = process.argv[2] ?? 'alice';const ids = { alice: 1, bob: 2, carol: 3, dave: 4, nora: 5, ravi: 6 };const user = await findUserById(ids[name]);user.access = await loadAccess(user.id);const { schema, policies } = loadPolicyStore();const answer = cedar.isAuthorizedPartial({  principal: ref('User', user.id),  action: { type: 'Caretaker::Action', id: 'ViewIssue' },  context: {},  schema,  policies: { staticPolicies: policies },  entities: [userEntity(user)],});console.log('decision:', answer.response.decision ?? 'depends on the resource');for (const id of answer.response.nontrivialResiduals) {  console.log(`${id}:`, cedar.policyToText(answer.response.residuals[id]).text);}await pool.end();
Run and comparecaretaker/
node --env-file=.env scripts/partial-demo.js alice
decision: depends on the resource
building-read: permit(principal, action, resource) when { true && (true && (true && ((unknown("resource") in [Caretaker::Building::"20"]) || (unknown("resource") in []) || (unknown("resource") in []) || (unknown("resource") in [Caretaker::Building::"10"]) || (unknown("resource") in [])))) };

The residual of building-read for Alice says: allowed if the resource is in Building::"20" or in Building::"10" (the empty sets are her roles with no buildings). That is exactly what our SQL condition expresses. For Carol the residual mentions Organisation::"1", and translating "resource in an organisation" into SQL means knowing that in follows the issue → building → organisation path, which is our schema's knowledge, not Cedar's. Partial evaluation is a useful tool for building or checking such translations, but it gives you Cedar expressions, not SQL, and the translation is your code to write and test. We keep the hand-written condition and the parity test.

Experiment

A product owner asks: "members of an organisation should see every issue in it". You add the policy and forget the SQL:

Create filesrc/authz/policies/members-read-everything.cedarCedar
// Experiment: organisation members may read all building data in their organisation.permit (principal, action in Caretaker::Action::"ReadBuildingData", resource)when { resource in principal.memberOrganisations };
Predict Which tests fail, and what does each failure tell you?
Run and comparecaretaker/exit code 1 (expected)
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) (480.7405ms)
✔ edit issue 101 (23.474167ms)
✔ view issue 103 (building 20) (22.796875ms)
✔ edit issue 103 (reported by dave) (24.024459ms)
✔ report an issue at building 20 (25.18425ms)
✖ view issue 105 (building 30) (20.014542ms)
✖ view issue 106 (building 40, reported by bob) (21.646125ms)
✔ approve inspection 201 (created by dave) (18.711417ms)
✔ approve inspection 202 (created by alice) (24.929541ms)
✔ update organisation 1 (18.8065ms)
✔ change own role at building 10 (4.27325ms)
✔ grant building_admin at building 10 to dave (19.12775ms)
✔ grant viewer at building 10 to dave (16.925083ms)
✔ issues in each user's list come only from the expected buildings (120.11925ms)
✔ the scenario loads exactly as specified (207.498333ms)
✔ only one active assignment per user, building and role (0.850125ms)
✔ a revoked role can be granted again (1.247875ms)
✔ the My access page shows what the server loaded (79.742333ms)
✔ a correct login creates a session and shows the user (269.079209ms)
✔ a wrong password or unknown email gets the same 401 (52.68875ms)
✔ registration validates, creates a user, and logs them in (36.212667ms)
✔ registering an existing email is a field error (28.33975ms)
✔ logout destroys the session (55.214792ms)
✔ allow: a permit matched and nothing forbade it (212.863542ms)
✔ explicit deny: a forbid overrides a matching permit (2.757625ms)
✔ implicit deny: no permit matched (2.175167ms)
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 (3.137083ms)
Show 294 more lines✔ unknown actions throw instead of deciding (1.291792ms) ✖ revoking dave's inspector role at building 10 takes effect on his next request (392.125583ms) ✔ a revoked assignment cannot be revoked again (7.211959ms) ✔ an assignment id from another building is not found here (4.901625ms) ✖ alice cannot revoke her own building_admin role; carol can (14.826791ms) ✔ grants are limited to members of the building's organisation (7.631292ms) ✔ a building can be created inside an organisation (293.807042ms) ✔ a duplicate building name in the same organisation is a field error (5.808333ms) ✔ the same building name is allowed in another organisation (9.743167ms) ✔ a building with issues cannot be deleted (13.934958ms) ✔ an empty building can be deleted (9.741792ms) ✔ an organisation with buildings cannot be deleted, an empty one can (25.147958ms) ✔ a logged-in POST without a token is refused with 403 (259.60575ms) ✔ a token from another session is refused (36.690292ms) ✔ the right token in the form field works (18.711292ms) ✔ every POST form on every page carries the token (56.167875ms) ✔ the dashboard counts match the database (270.886541ms) ✔ only the buildings carol can see appear (5.915083ms) ✔ create a draft, edit it, submit it, approve it (319.009916ms) ✔ invalid transitions are refused with 409 and change nothing (11.836541ms) ✔ only drafts can be edited (5.42175ms) ✔ returning a submitted inspection makes it editable again (8.167ms) ✔ concurrent approvals: exactly one wins (26.955667ms) ✔ unknown actions are 404 (3.14ms) ✔ the issues list contains only issues from visible buildings (568.053584ms) ✔ a filter for another tenant's building returns nothing (3.590084ms) ✔ the inspections list is scoped too (9.824666ms) ✔ organisations are listed for their members only (8.963584ms) ✔ the dashboard counts only visible data (7.491625ms) ✔ view issue 101 (building 10) (470.794209ms) ✔ open the edit form for issue 101 (26.05675ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (24.576417ms) ✖ view issue 105 (building 30) and 106 (building 40) (20.449375ms) ✔ report an issue at building 20 (26.247417ms) ✔ a reporter cannot edit their own issue once it is closed (10.6895ms) ✔ only building admins may delete; refusals change nothing (18.189333ms) ✔ the edit form cannot move an issue to another building (4.465917ms) ✔ the list pages 10 at a time and reports the total (292.048333ms) ✔ pages do not overlap (22.662709ms) ✔ filters combine with AND (6.797541ms) ✔ sorting by priority puts critical first when descending (7.090042ms) ✔ unknown sort keys and SQL in the query string are ignored (39.837458ms) ✔ GET /issues lists issues from the database (282.405875ms) ✔ GET /issues/101 shows one issue with its building (6.997917ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (17.157042ms) ✔ POST /issues re-renders the form with errors (5.383ms) ✔ POST /issues stores the issue and redirects to it (8.541584ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.083333ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.034209ms) ✔ an issue time in the future is rejected (4.487833ms) ✔ GET /issues/101/edit shows the current values (5.200959ms) ✔ POST /issues/:id/edit changes the status and updated_at (4.829458ms) ✔ POST /issues/:id/delete removes the issue (11.421458ms) ✖ the issues list contains exactly the issues Cedar lets each user view (337.053292ms) ✖ the inspections list contains exactly the inspections Cedar lets each user view (21.966208ms) ✔ only organisation admins can open the members page (430.813334ms) ✖ controlled onboarding: carol adds nora; nora sees the organisation but no building (18.726417ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (13.234666ms) ✔ nobody changes their own membership (4.110375ms) ✔ unknown emails and roles are form errors (9.741458ms) ✔ a member cannot add members, even with a well-formed request (3.747ms) ✔ GET /organisations lists organisations with building counts (275.266541ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (13.964917ms) ✔ POST /organisations validates and creates (14.622375ms) ✔ POST /organisations/:id/edit renames the organisation (10.53225ms) ✔ unknown organisations are 404 (6.332375ms) ✔ every policy is valid against the schema (32.155875ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.045208ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (313.174292ms) ✔ anonymous requests are redirected to the login page (215.345625ms) ✔ anonymous writes are refused and change nothing (11.007875ms) ✔ login and register pages stay public (5.678709ms) ✔ login issues a new session id (no session fixation) (31.613959ms) ✔ returnTo only follows local paths (27.576208ms) ✔ new issues and transitions record the logged-in user (82.707208ms) ✔ the session cookie has the attributes we chose (28.574792ms) ✔ organisation 1: view and update (501.877041ms) ✖ ravi is still a member of organisation 2 but can see none of its buildings (9.642333ms) ✔ building 10: view, update, delete (60.01ms) ✔ creating buildings needs org_admin (15.680375ms) ✔ creating an organisation makes the creator its admin (10.341417ms) ✔ inspections: view 201, open the edit form for draft 203 (42.152458ms) ✔ approve inspection 201 (dave's): only building admins (19.495208ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (12.38125ms) ℹ tests 111 ℹ suites 0 ℹ pass 102 ℹ fail 9 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 11756.671916 ✖ failing tests: test at test/access-matrix.test.js:48:3 ✖ view issue 105 (building 30) (20.014542ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, + ravi: 200 - ravi: 404 } at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/access-matrix.test.js:53:12) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 200 }, expected: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 }, operator: 'deepStrictEqual', diff: 'simple' } test at test/access-matrix.test.js:48:3 ✖ view issue 106 (building 40, reported by bob) (21.646125ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected { alice: 404, + bob: 200, - bob: 404, carol: 404, dave: 404, nora: 404, + ravi: 200 - ravi: 404 } at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/access-matrix.test.js:53:12) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 200 }, expected: { alice: 404, bob: 404, carol: 404, dave: 404, nora: 404, ravi: 404 }, operator: 'deepStrictEqual', diff: 'simple' } test at test/building-access.test.js:13:1 ✖ revoking dave's inspector role at building 10 takes effect on his next request (392.125583ms) AssertionError [ERR_ASSERTION]: same session, no new login 200 !== 404 at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/building-access.test.js:17:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) { generatedMessage: false, code: 'ERR_ASSERTION', actual: 200, expected: 404, operator: 'strictEqual', diff: 'simple' } test at test/building-access.test.js:35:1 ✖ alice cannot revoke her own building_admin role; carol can (14.826791ms) AssertionError [ERR_ASSERTION]: alice lost all access to building 10 403 !== 404 at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/building-access.test.js:38:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: false, code: 'ERR_ASSERTION', actual: 403, expected: 404, operator: 'strictEqual', diff: 'simple' } test at test/issue-authz.test.js:36:1 ✖ view issue 105 (building 30) and 106 (building 40) (20.449375ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, + ravi: 200 - ravi: 404 } at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/issue-authz.test.js:37:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 200 }, expected: { alice: 404, bob: 200, carol: 404, dave: 404, nora: 404, ravi: 404 }, operator: 'deepStrictEqual', diff: 'simple' } test at test/list-parity.test.js:13:1 ✖ the issues list contains exactly the issues Cedar lets each user view (337.053292ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected + [ + 'bob issue 106: cedar=true list=false', + 'ravi issue 105: cedar=true list=false', + 'ravi issue 106: cedar=true list=false' + ] - [] at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/list-parity.test.js:24:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) { generatedMessage: true, code: 'ERR_ASSERTION', actual: [ 'bob issue 106: cedar=true list=false', 'ravi issue 105: cedar=true list=false', 'ravi issue 106: cedar=true list=false' ], expected: [], operator: 'deepStrictEqual', diff: 'simple' } test at test/list-parity.test.js:27:1 ✖ the inspections list contains exactly the inspections Cedar lets each user view (21.966208ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: + actual - expected + [ + 'ravi inspection 204: cedar=true list=false' + ] - [] at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/list-parity.test.js:38:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: [ 'ravi inspection 204: cedar=true list=false' ], expected: [], operator: 'deepStrictEqual', diff: 'simple' } test at test/members.test.js:19:1 ✖ controlled onboarding: carol adds nora; nora sees the organisation but no building (18.726417ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 200 !== 404 at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/members.test.js:23:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: 200, expected: 404, operator: 'strictEqual', diff: 'simple' } test at test/resource-authz.test.js:27:1 ✖ ravi is still a member of organisation 2 but can see none of its buildings (9.642333ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 200 !== 404 at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/resource-authz.test.js:29:10) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async Test.run (node:internal/test_runner/test:1054:7) at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: 200, expected: 404, operator: 'strictEqual', diff: 'simple' }
Reveal Answer

The list-parity tests name the exact drift: bob issue 106, ravi issue 105, ravi issue 106 and ravi inspection 204, all cedar=true list=false. As members of Harbour Lets, Bob and Ravi could now open those records, but the list does not show them. The access matrix rows for issues 105 and 106 fail too, as do the tests that state "a member sees no building" and "revocation removes access": they all describe behaviour that this policy changed. The tests turned a silent inconsistency into a precise list. A complete change would update the policy, visibleBuildingCondition, and the matrix and tests together, deliberately.

Remove the experiment policy:

Runcaretaker/
rm src/authz/policies/members-read-everything.cedar

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) (465.585667ms)
✔ edit issue 101 (23.767292ms)
✔ view issue 103 (building 20) (23.395541ms)
✔ edit issue 103 (reported by dave) (28.194916ms)
✔ report an issue at building 20 (31.540542ms)
✔ view issue 105 (building 30) (22.761875ms)
✔ view issue 106 (building 40, reported by bob) (17.920417ms)
✔ approve inspection 201 (created by dave) (16.648375ms)
✔ approve inspection 202 (created by alice) (22.595ms)
✔ update organisation 1 (24.06075ms)
✔ change own role at building 10 (4.579167ms)
✔ grant building_admin at building 10 to dave (28.811125ms)
✔ grant viewer at building 10 to dave (18.075917ms)
✔ issues in each user's list come only from the expected buildings (114.574167ms)
✔ the scenario loads exactly as specified (205.978708ms)
✔ only one active assignment per user, building and role (0.885542ms)
✔ a revoked role can be granted again (0.818042ms)
✔ the My access page shows what the server loaded (71.459875ms)
✔ a correct login creates a session and shows the user (293.924709ms)
✔ a wrong password or unknown email gets the same 401 (52.489666ms)
✔ registration validates, creates a user, and logs them in (38.41825ms)
✔ registering an existing email is a field error (26.027417ms)
✔ logout destroys the session (42.539041ms)
✔ allow: a permit matched and nothing forbade it (211.173209ms)
✔ explicit deny: a forbid overrides a matching permit (3.147625ms)
✔ implicit deny: no permit matched (2.509834ms)
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 (3.215291ms)
Show 92 more lines✔ unknown actions throw instead of deciding (1.464833ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (393.542916ms) ✔ a revoked assignment cannot be revoked again (4.574416ms) ✔ an assignment id from another building is not found here (4.243291ms) ✔ alice cannot revoke her own building_admin role; carol can (12.286916ms) ✔ grants are limited to members of the building's organisation (6.144625ms) ✔ a building can be created inside an organisation (288.061375ms) ✔ a duplicate building name in the same organisation is a field error (5.395334ms) ✔ the same building name is allowed in another organisation (10.783792ms) ✔ a building with issues cannot be deleted (14.568167ms) ✔ an empty building can be deleted (10.284583ms) ✔ an organisation with buildings cannot be deleted, an empty one can (23.6485ms) ✔ a logged-in POST without a token is refused with 403 (274.200208ms) ✔ a token from another session is refused (36.333ms) ✔ the right token in the form field works (18.410792ms) ✔ every POST form on every page carries the token (50.971542ms) ✔ the dashboard counts match the database (268.548667ms) ✔ only the buildings carol can see appear (5.1655ms) ✔ create a draft, edit it, submit it, approve it (344.126875ms) ✔ invalid transitions are refused with 409 and change nothing (12.001917ms) ✔ only drafts can be edited (5.624541ms) ✔ returning a submitted inspection makes it editable again (8.27025ms) ✔ concurrent approvals: exactly one wins (25.99525ms) ✔ unknown actions are 404 (2.860917ms) ✔ the issues list contains only issues from visible buildings (570.290875ms) ✔ a filter for another tenant's building returns nothing (3.650625ms) ✔ the inspections list is scoped too (9.612292ms) ✔ organisations are listed for their members only (8.294958ms) ✔ the dashboard counts only visible data (9.05825ms) ✔ view issue 101 (building 10) (478.858292ms) ✔ open the edit form for issue 101 (28.450083ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (25.544667ms) ✔ view issue 105 (building 30) and 106 (building 40) (41.744708ms) ✔ report an issue at building 20 (26.090708ms) ✔ a reporter cannot edit their own issue once it is closed (11.022416ms) ✔ only building admins may delete; refusals change nothing (18.154916ms) ✔ the edit form cannot move an issue to another building (4.221583ms) ✔ the list pages 10 at a time and reports the total (328.06975ms) ✔ pages do not overlap (25.190125ms) ✔ filters combine with AND (8.487792ms) ✔ sorting by priority puts critical first when descending (7.871792ms) ✔ unknown sort keys and SQL in the query string are ignored (39.594708ms) ✔ GET /issues lists issues from the database (294.312ms) ✔ GET /issues/101 shows one issue with its building (5.972084ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.059125ms) ✔ POST /issues re-renders the form with errors (5.265ms) ✔ POST /issues stores the issue and redirects to it (8.922625ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.7545ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.660542ms) ✔ an issue time in the future is rejected (4.425833ms) ✔ GET /issues/101/edit shows the current values (5.161916ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.341333ms) ✔ POST /issues/:id/delete removes the issue (11.051791ms) ✔ the issues list contains exactly the issues Cedar lets each user view (324.009041ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (20.428375ms) ✔ only organisation admins can open the members page (435.87525ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (15.202542ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.562333ms) ✔ nobody changes their own membership (3.980167ms) ✔ unknown emails and roles are form errors (9.01325ms) ✔ a member cannot add members, even with a well-formed request (3.229583ms) ✔ GET /organisations lists organisations with building counts (285.655459ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (14.525625ms) ✔ POST /organisations validates and creates (14.079916ms) ✔ POST /organisations/:id/edit renames the organisation (10.997125ms) ✔ unknown organisations are 404 (6.199041ms) ✔ every policy is valid against the schema (32.648792ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.492625ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (335.808208ms) ✔ anonymous requests are redirected to the login page (207.958458ms) ✔ anonymous writes are refused and change nothing (10.397875ms) ✔ login and register pages stay public (5.526708ms) ✔ login issues a new session id (no session fixation) (30.97825ms) ✔ returnTo only follows local paths (31.478125ms) ✔ new issues and transitions record the logged-in user (96.557208ms) ✔ the session cookie has the attributes we chose (26.027375ms) ✔ organisation 1: view and update (511.029041ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (8.734917ms) ✔ building 10: view, update, delete (64.187834ms) ✔ creating buildings needs org_admin (23.01275ms) ✔ creating an organisation makes the creator its admin (10.26025ms) ✔ inspections: view 201, open the edit form for draft 203 (42.5325ms) ✔ approve inspection 201 (dave's): only building admins (17.147875ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (13.847875ms) ℹ tests 111 ℹ suites 0 ℹ pass 111 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 11874.601833
Run and comparecaretaker/
git add -A
git commit -m "Lists and policies aligned: parity test, per-item guard, pre-parsed policies"
[main 29be76d] Lists and policies aligned: parity test, per-item guard, pre-parsed policies
 5 files changed, 98 insertions(+), 2 deletions(-)
 create mode 100644 scripts/authz-bench.js
 create mode 100644 scripts/partial-demo.js
 create mode 100644 test/list-parity.test.js
Symptom Could not pre-parse the policy store

The same causes as a validation failure; run npm run authz:validate.

Symptom list/policy mismatch in the server log

The SQL filter shows a row that Cedar denies. Run npm test; the list-parity test names the user and record. Fix the SQL condition or the policy so that they say the same thing.

Recap and next step

A list is authorized in the query, by a SQL condition that must mean what the policies mean. A parity test proves it for every user and record; a per-item guard on each page catches drift at runtime; pre-parsed policies make per-item decisions cheap. Partial evaluation shows the conditions a resource must meet, but turning them into SQL is our job, not Cedar's.

Next: creating and moving records. A new issue has no row yet to authorize, and a moved issue leaves one building for another.