Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 7.1

Facts, parents and action groups: checkpoint files

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

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

Files changed in this lesson

src/authz/entities.js changed

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) };} function refs(type, ids) {  return [...new Set(ids)].sort((a, b) => a - b).map((id) => ref(type, id));} function buildingsWithRole(user, role) {  return refs('Building', user.access.assignments.filter((a) => a.role === role).map((a) => a.building_id));} // Version 2: facts only. Each set is exactly the active rows of one role.// Inheritance (organisation -> building) and the role ladder are decided by the policies.export function userEntity(user) {  return {    uid: ref('User', user.id),    attrs: {      viewerBuildings: buildingsWithRole(user, 'viewer'),      reporterBuildings: buildingsWithRole(user, 'reporter'),      inspectorBuildings: buildingsWithRole(user, 'inspector'),      adminBuildings: buildingsWithRole(user, 'building_admin'),      memberOrganisations: refs('Organisation', user.access.memberships.map((m) => m.organisation_id)),      adminOrganisations: refs('Organisation', user.access.memberships.filter((m) => m.role === 'org_admin').map((m) => m.organisation_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)] };} export function inspectionEntity(inspection) {  const attrs = { building: ref('Building', inspection.building_id), status: inspection.status };  if (inspection.created_by !== null) {    attrs.createdBy = ref('User', inspection.created_by);  }  return { uid: ref('Inspection', inspection.id), attrs, parents: [ref('Building', inspection.building_id)] };}

src/authz/policies/administer-building-data.cedar deleted

src/authz/policies/administer-organisation.cedar deleted

src/authz/policies/building-admin.cedar added

src/authz/policies/building-admin.cedar
// Building admins may do every administrative action at their buildings.// Organisation admins are building admins at every building of their organisation.permit (principal, action in Caretaker::Action::"AdministerBuilding", resource)when { resource in principal.adminBuildings || resource in principal.adminOrganisations };

src/authz/policies/building-read.cedar added

src/authz/policies/building-read.cedar
// Any role at a building (or administering its organisation) lets you read the building's data.// "resource in S" is true if the resource is S, or S is one of its ancestors:// an issue is in its building, and a building is in its organisation.permit (principal, action in Caretaker::Action::"ReadBuildingData", resource)when {  resource in principal.viewerBuildings ||  resource in principal.reporterBuildings ||  resource in principal.inspectorBuildings ||  resource in principal.adminBuildings ||  resource in principal.adminOrganisations};

src/authz/policies/create-inspection.cedar deleted

src/authz/policies/create-issue.cedar deleted

src/authz/policies/delete-building.cedar deleted

src/authz/policies/inspector-create-inspection.cedar added

src/authz/policies/inspector-create-inspection.cedar
// Inspectors may create inspections at their buildings.permit (principal, action == Caretaker::Action::"CreateInspection", resource)when { resource in principal.inspectorBuildings };

src/authz/policies/inspector-own-inspections.cedar renamed

src/authz/policies/inspector-own-inspections.cedar
// Inspectors may edit and submit inspections they created.permit (  principal,  action in [Caretaker::Action::"UpdateInspection", Caretaker::Action::"SubmitInspection"],  resource)when {  resource in principal.inspectorBuildings &&  resource has createdBy &&  resource.createdBy == principal};

src/authz/policies/org-admin.cedar added

src/authz/policies/org-admin.cedar
// Organisation admins may manage the organisation itself and its buildings.permit (principal, action in Caretaker::Action::"AdministerOrganisation", resource)when { resource in principal.adminOrganisations };

src/authz/policies/org-member.cedar renamed

src/authz/policies/org-member.cedar
// Members may view their organisation.permit (principal, action == Caretaker::Action::"ViewOrganisation", resource)when { resource in principal.memberOrganisations };

src/authz/policies/reporter-create-issue.cedar added

src/authz/policies/reporter-create-issue.cedar
// Reporters may report issues at their buildings.permit (principal, action == Caretaker::Action::"CreateIssue", resource)when { resource in principal.reporterBuildings };

src/authz/policies/reporter-own-issues.cedar renamed

src/authz/policies/reporter-own-issues.cedar
// Reporters may edit issues they reported, while the issue is not closed.permit (principal, action == Caretaker::Action::"UpdateIssue", resource)when {  resource in principal.reporterBuildings &&  resource has reportedBy &&  resource.reportedBy == principal &&  resource.status != "closed"};

src/authz/policies/update-building.cedar deleted

src/authz/policies/view-building-data.cedar deleted

src/authz/policies/view-building.cedar deleted

src/authz/schema.cedarschema changed

src/authz/schema.cedarschema
// What Cedar may see in Caretaker, and in what shape. Version 2.namespace Caretaker {  entity Organisation;   entity Building in [Organisation] = {    organisation: Organisation,  };   // Version 2: facts only. Each set holds exactly the rows the database has.  entity User = {    viewerBuildings: Set<Building>,    reporterBuildings: Set<Building>,    inspectorBuildings: Set<Building>,    adminBuildings: Set<Building>,    memberOrganisations: Set<Organisation>,    adminOrganisations: Set<Organisation>,  };   entity Issue in [Building] = {    building: Building,    status: String,    priority: String,    reportedBy?: User,  };   entity Inspection in [Building] = {    building: Building,    status: String,    createdBy?: User,  };   // Action groups. A policy about a group applies to every action in it.  action ReadBuildingData;  action AdministerBuilding;  action AdministerOrganisation;   action ViewOrganisation appliesTo { principal: [User], resource: [Organisation] };  action UpdateOrganisation, DeleteOrganisation, CreateBuilding in [AdministerOrganisation] appliesTo {    principal: [User],    resource: [Organisation],  };  action DeleteBuilding in [AdministerOrganisation] appliesTo { principal: [User], resource: [Building] };   action ViewBuilding in [ReadBuildingData] appliesTo { principal: [User], resource: [Building] };  action ViewIssue in [ReadBuildingData] appliesTo { principal: [User], resource: [Issue] };  action ViewInspection in [ReadBuildingData] appliesTo { principal: [User], resource: [Inspection] };   action CreateIssue, CreateInspection, UpdateBuilding in [AdministerBuilding] appliesTo { principal: [User], resource: [Building] };  action UpdateIssue, DeleteIssue in [AdministerBuilding] appliesTo { principal: [User], resource: [Issue] };  action UpdateInspection, SubmitInspection, ApproveInspection, ReturnInspection in [AdministerBuilding] appliesTo {    principal: [User],    resource: [Inspection],  };}

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] = 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],    ),  ]);  return { memberships: memberships.rows, assignments: assignments.rows };}

test/authz-decisions.test.js changed

test/authz-decisions.test.js
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import { pool } from '../src/db.js';import { authorize } from '../src/authz/authorize.js';import { findInspection } from '../src/models/inspections.js';import { findIssue } from '../src/models/issues.js';import { resetDatabase, loadUserNamed } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('allow: a permit matched and nothing forbade it', async () => {  const result = authorize(await loadUserNamed('carol'), 'ApproveInspection', await findInspection(202));  assert.deepEqual({ allowed: result.allowed, reasons: result.reasons }, { allowed: true, reasons: ['building-admin'] });}); test('explicit deny: a forbid overrides a matching permit', async () => {  const result = authorize(await loadUserNamed('alice'), 'ApproveInspection', await findInspection(202));  assert.deepEqual({ decision: result.decision, reasons: result.reasons, errors: result.errors }, { decision: 'deny', reasons: ['forbid-self-approval'], errors: [] });}); test('implicit deny: no permit matched', async () => {  const result = authorize(await loadUserNamed('nora'), 'ViewIssue', await findIssue(101));  assert.deepEqual({ decision: result.decision, reasons: result.reasons }, { decision: 'deny', reasons: [] });}); test('failure: a row that does not fit the schema is never allowed', async () => {  const broken = { ...(await findInspection(201)), status: 7 };  const result = authorize(await loadUserNamed('alice'), 'ApproveInspection', broken);  assert.equal(result.allowed, false);  assert.equal(result.decision, 'failure');  assert.match(result.errors[0], /status/);}); test('unknown actions throw instead of deciding', async () => {  const alice = await loadUserNamed('alice');  assert.throws(() => authorize(alice, 'LaunchRocket', { id: 1 }), /No Cedar resource type/);});

test/policies.test.js changed

test/policies.test.js
import { test } from 'node:test';import assert from 'node:assert/strict';import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { loadPolicyStore } from '../src/authz/policy-store.js';import { RESOURCE_TYPES } from '../src/authz/request.js'; test('every policy is valid against the schema', () => {  const { schema, policies } = loadPolicyStore();  assert.ok(Object.keys(policies).length > 0, 'there are policies');  const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });  assert.equal(result.type, 'success', JSON.stringify(result.errors));  assert.deepEqual(result.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`), []);}); test('every action used by the app is mentioned by a policy, directly or through its group', () => {  const { schema, policies } = loadPolicyStore();  const text = Object.values(policies).join('\n');  const actions = cedar.schemaToJson(schema).json.Caretaker.actions;  const missing = Object.keys(RESOURCE_TYPES).filter((action) => {    const names = [action, ...(actions[action].memberOf ?? []).map((group) => group.id)];    return !names.some((name) => text.includes(`Action::"${name}"`));  });  assert.deepEqual(missing, []);});

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-errors-demo.js
scripts/cedar-hello.js
scripts/migrate.js
scripts/seed.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-self-approval.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/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/authz-decisions.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/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 7.1