Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 8.1

Lists and policies, kept aligned: checkpoint files

Git tag in the reference repository
lesson/m08-l01 (commit 292038b)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 111, pass 111, fail 0)

Compare your folder with the reference using Git, if you cloned it: git diff lesson/m08-l01 -- src.

Files changed in this lesson

scripts/authz-bench.js added

scripts/authz-bench.js
// 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();

scripts/partial-demo.js added

scripts/partial-demo.js
// 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();

src/authz/cedar.js changed

src/authz/cedar.js
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 };}

src/routes/issues.js changed

src/routes/issues.js
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');});

test/list-parity.test.js added

test/list-parity.test.js
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, []);});

Project tree at this checkpoint

.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
migrations/005_create_memberships_and_building_roles.sql
migrations/006_create_permission_changes.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/authz-bench.js
scripts/authz-explain.js
scripts/cedar-errors-demo.js
scripts/cedar-hello.js
scripts/migrate.js
scripts/partial-demo.js
scripts/seed.js
scripts/template-demo.js
scripts/validate-policies.js
src/app.js
src/authz/authorize.js
src/authz/cedar.js
src/authz/entities.js
src/authz/policies/building-admin.cedar
src/authz/policies/building-read.cedar
src/authz/policies/forbid-building-admin-grants.cedar
src/authz/policies/forbid-self-approval.cedar
src/authz/policies/forbid-self-membership-change.cedar
src/authz/policies/forbid-self-role-change.cedar
src/authz/policies/inspector-create-inspection.cedar
src/authz/policies/inspector-own-inspections.cedar
src/authz/policies/org-admin.cedar
src/authz/policies/org-member.cedar
src/authz/policies/reporter-create-issue.cedar
src/authz/policies/reporter-own-issues.cedar
src/authz/policy-store.js
src/authz/request.js
src/authz/rules.js
src/authz/schema.cedarschema
src/config.js
src/db.js
src/lib/http.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/migrate.js
src/models/access.js
src/models/assignments.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/members.js
src/models/organisations.js
src/models/scope.js
src/models/users.js
src/routes/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access-matrix.test.js
test/access.test.js
test/auth.test.js
test/authz-decisions.test.js
test/building-access.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/helpers.js
test/inspections.test.js
test/isolation.test.js
test/issue-authz.test.js
test/issue-list.test.js
test/issues.test.js
test/list-parity.test.js
test/members.test.js
test/organisations.test.js
test/policies.test.js
test/rate-limit.test.js
test/require-login.test.js
test/resource-authz.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
views/buildings/access.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/forbidden.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/members.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 8.1