Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 6.3

From database rows to Cedar entities: checkpoint files

Git tag in the reference repository
lesson/m06-l03 (commit 9410fba)
Replay result
All steps replayed from an empty folder
Tests at this point
pass (tests 90, pass 90, fail 0)

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

Files changed in this lesson

package.json changed

package.json
{  "name": "caretaker",  "version": "1.0.0",  "description": "",  "scripts": {    "test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"",    "start": "node --env-file=.env src/server.js",    "dev": "node --env-file=.env --watch src/server.js",    "db:migrate": "node --env-file=.env scripts/migrate.js",    "db:seed": "node --env-file=.env scripts/seed.js",    "authz:validate": "node scripts/validate-policies.js",    "authz:explain": "node --env-file=.env scripts/authz-explain.js"  },  "keywords": [],  "author": "",  "license": "ISC",  "type": "module",  "dependencies": {    "@cedar-policy/cedar-wasm": "4.14.0",    "argon2": "0.45.2",    "connect-pg-simple": "10.0.0",    "ejs": "7.0.2",    "express": "5.3.0",    "express-rate-limit": "8.7.4",    "express-session": "1.19.0",    "pg": "8.23.1"  },  "devDependencies": {    "supertest": "7.3.2"  }}

scripts/authz-explain.js added

scripts/authz-explain.js
// Usage: npm run authz:explain -- <user> <action> <issueId>// Example: npm run authz:explain -- alice ViewIssue 101import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { pool, query } from '../src/db.js';import { findUserById } from '../src/models/users.js';import { loadAccess } from '../src/models/access.js';import { findIssue } from '../src/models/issues.js';import { loadPolicyStore } from '../src/authz/policy-store.js';import { buildAuthorizationCall } from '../src/authz/request.js'; const [name, action, issueId] = process.argv.slice(2);const show = (title, value) => console.log(`\n== ${title}\n${JSON.stringify(value, null, 2)}`); try {  const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]);  if (rows.length === 0) throw new Error(`no user ${name}@example.test`);  const user = await findUserById(rows[0].id);  user.access = await loadAccess(user.id);  show('1. users row (the session holds only this id)', { id: user.id, email: user.email });  show('2. access rows loaded for this request', user.access);   const issue = await findIssue(Number(issueId));  if (!issue) throw new Error(`no issue ${issueId}`);  show('3. issue row', { id: issue.id, building_id: issue.building_id, organisation_id: issue.organisation_id, reported_by: issue.reported_by, status: issue.status, priority: issue.priority });   const call = buildAuthorizationCall(user, action, issue);  show('4. entities built by the mapper', call.entities);  show('5. request', { principal: call.principal, action: call.action, resource: call.resource, context: call.context });   const { schema, policies } = loadPolicyStore();  const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } });  show('6. Cedar answer', answer);} finally {  await pool.end();}

src/authz/entities.js added

src/authz/entities.js
// The entity mapper: turns rows the application already loaded into Cedar entities.// Every value comes from the database (through loadAccess and the models) or from// the session (the user id). Nothing comes from the HTTP request. const NAMESPACE = 'Caretaker'; export function ref(type, id) {  return { type: `${NAMESPACE}::${type}`, id: String(id) };} // Version 1: one derived attribute. A building's issues are viewable if the user// holds any active role at the building, or is org_admin of the building's organisation.export function userEntity(user) {  const viewable = new Set([    ...user.access.assignments.map((a) => a.building_id),    ...user.access.orgAdminBuildings.map((s) => s.building_id),  ]);  return {    uid: ref('User', user.id),    attrs: {      issueViewerBuildings: [...viewable].sort((a, b) => a - b).map((id) => ref('Building', id)),    },    parents: [],  };} export function organisationEntity(organisationId) {  return { uid: ref('Organisation', organisationId), attrs: {}, parents: [] };} export function buildingEntity({ id, organisation_id }) {  return {    uid: ref('Building', id),    attrs: { organisation: ref('Organisation', organisation_id) },    parents: [ref('Organisation', organisation_id)],  };} export function issueEntity(issue) {  const attrs = {    building: ref('Building', issue.building_id),    status: issue.status,    priority: issue.priority,  };  if (issue.reported_by !== null) {    attrs.reportedBy = ref('User', issue.reported_by);  }  return { uid: ref('Issue', issue.id), attrs, parents: [ref('Building', issue.building_id)] };}

src/authz/request.js added

src/authz/request.js
import { ref, userEntity, organisationEntity, buildingEntity, issueEntity } from './entities.js'; // Which entity type each action's resource is. Grows as actions move to Cedar.export const RESOURCE_TYPES = {  ViewIssue: 'Issue',}; // Builds the request part of an isAuthorized call for one user, action and database row.export function buildAuthorizationCall(user, action, row) {  const type = RESOURCE_TYPES[action];  if (!type) {    throw new Error(`No Cedar resource type for action ${action}`);  }  const entities = [userEntity(user)];  let resource;  if (type === 'Issue') {    const issue = issueEntity(row);    entities.push(issue, buildingEntity({ id: row.building_id, organisation_id: row.organisation_id }), organisationEntity(row.organisation_id));    resource = issue.uid;  }  return {    principal: ref('User', user.id),    action: { type: 'Caretaker::Action', id: action },    resource,    context: {},    entities,  };}

src/models/access.js changed

src/models/access.js
import { query } from '../db.js'; // The current user's ACTIVE memberships and building role assignments.export async function loadAccess(userId) {  const [memberships, assignments, orgAdminBuildings] = await Promise.all([    query(      `SELECT m.organisation_id, o.name AS organisation_name, m.role       FROM memberships m       JOIN organisations o ON o.id = m.organisation_id       WHERE m.user_id = $1       ORDER BY o.name`,      [userId],    ),    query(      `SELECT a.building_id, s.name AS building_name, s.organisation_id, a.role       FROM building_role_assignments a       JOIN buildings s ON s.id = a.building_id       WHERE a.user_id = $1 AND a.revoked_at IS NULL       ORDER BY s.id, a.role`,      [userId],    ),    query(      `SELECT s.id AS building_id, s.organisation_id       FROM buildings s       JOIN memberships m ON m.organisation_id = s.organisation_id       WHERE m.user_id = $1 AND m.role = 'org_admin'       ORDER BY s.id`,      [userId],    ),  ]);  return { memberships: memberships.rows, assignments: assignments.rows, orgAdminBuildings: orgAdminBuildings.rows };}

test/cedar-parity.test.js added

test/cedar-parity.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { pool } from '../src/db.js';import { findUserById } from '../src/models/users.js';import { loadAccess } from '../src/models/access.js';import { findIssue } from '../src/models/issues.js';import { can } from '../src/authz/rules.js';import { loadPolicyStore } from '../src/authz/policy-store.js';import { buildAuthorizationCall } from '../src/authz/request.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('Cedar and can() agree on ViewIssue for every user and issue', async () => {  const { schema, policies } = loadPolicyStore();  const { rows: issueRows } = await pool.query('SELECT id FROM issues ORDER BY id');  const mismatches = [];  let checked = 0;  for (let userId = 1; userId <= 6; userId++) {    const user = await findUserById(userId);    user.access = await loadAccess(userId);    for (const { id } of issueRows) {      const issue = await findIssue(id);      const answer = cedar.isAuthorized({ ...buildAuthorizationCall(user, 'ViewIssue', issue), schema, validateRequest: true, policies: { staticPolicies: policies } });      assert.equal(answer.type, 'success', JSON.stringify(answer.errors));      const cedarAllows = answer.response.decision === 'allow';      if (cedarAllows !== can(user, 'ViewIssue', issue)) mismatches.push(`user ${userId} issue ${id}`);      checked++;    }  }  assert.deepEqual(mismatches, []);  assert.equal(checked, 6 * 30);});

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
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/authz-explain.js
scripts/cedar-hello.js
scripts/migrate.js
scripts/seed.js
scripts/validate-policies.js
src/app.js
src/authz/entities.js
src/authz/policies/view-issue.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/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.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/buildings.test.js
test/cedar-parity.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/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/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/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs

Back to lesson 6.3