Caretaker Express · PostgreSQL · Cedar

Checkpoint · Lesson 7.2

Policy templates, compared: checkpoint files

Git tag in the reference repository
lesson/m07-l02 (commit 49ec0a8)
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-l02 -- src.

Files changed in this lesson

scripts/template-demo.js added

scripts/template-demo.js
// Compares two designs on real data: role facts as entity attributes (the app)// versus one template-linked policy per grant (this script). Not used by the app.import * 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 { findInspection } from '../src/models/inspections.js';import { loadPolicyStore } from '../src/authz/policy-store.js';import { buildAuthorizationCall } from '../src/authz/request.js';import { ref } from '../src/authz/entities.js'; const { schema, policies } = loadPolicyStore(); // ?principal and ?resource are slots. A link fills them with real entities.const templates = {  'read-template': 'permit (principal == ?principal, action in Caretaker::Action::"ReadBuildingData", resource in ?resource);',  'admin-template': 'permit (principal == ?principal, action in Caretaker::Action::"AdministerBuilding", resource in ?resource);',}; function link(templateId, userId, resource) {  return { templateId, newId: `${templateId}:user-${userId}:${resource.type.replace('Caretaker::', '')}-${resource.id}`, values: { '?principal': ref('User', userId), '?resource': resource } };} // One link per grant, generated from the same rows loadAccess reads.async function buildLinks() {  const links = [];  const { rows: assignments } = await query('SELECT user_id, building_id, role FROM building_role_assignments WHERE revoked_at IS NULL ORDER BY id');  for (const a of assignments) {    links.push(link('read-template', a.user_id, ref('Building', a.building_id)));    if (a.role === 'building_admin') links.push(link('admin-template', a.user_id, ref('Building', a.building_id)));  }  const { rows: admins } = await query("SELECT user_id, organisation_id FROM memberships WHERE role = 'org_admin' ORDER BY user_id");  for (const m of admins) {    links.push(link('read-template', m.user_id, ref('Organisation', m.organisation_id)));    links.push(link('admin-template', m.user_id, ref('Organisation', m.organisation_id)));  }  return links;} function decide(call, policySet) {  return cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: policySet }).response.decision;} const links = await buildLinks();console.log(`template links generated: ${links.length}`);console.log('example link:', JSON.stringify(links.find((l) => l.newId.includes('user-1:Building-10') && l.templateId === 'admin-template'))); // Set WITHOUT_FORBID=1 to leave the separation-of-duties forbid out of the template design.const forbid = process.env.WITHOUT_FORBID === '1' ? {} : { 'forbid-self-approval': policies['forbid-self-approval'] };const templatePolicySet = { staticPolicies: forbid, templates, templateLinks: links };const attributePolicySet = { staticPolicies: policies }; // Compare read and admin-only actions for every user, issue and inspection.const checks = [['ViewIssue', findIssue], ['DeleteIssue', findIssue], ['ViewInspection', findInspection], ['ReturnInspection', findInspection], ['ApproveInspection', findInspection]];const { rows: issueIds } = await query('SELECT id FROM issues ORDER BY id');const { rows: inspectionIds } = await query('SELECT id FROM inspections ORDER BY id');let compared = 0;const differences = [];for (let userId = 1; userId <= 6; userId++) {  const user = await findUserById(userId);  user.access = await loadAccess(userId);  for (const [action, find] of checks) {    for (const { id } of find === findIssue ? issueIds : inspectionIds) {      const call = buildAuthorizationCall(user, action, await find(id));      const a = decide(call, attributePolicySet);      const t = decide(call, templatePolicySet);      compared++;      if (a !== t) differences.push(`user ${userId} ${action} ${id}: attributes=${a} templates=${t}`);    }  }}console.log(`decisions compared: ${compared}, differences: ${differences.length}`);for (const d of differences) console.log('  ', d); // Revocation: remove Alice's building_admin role at building 10 from the database facts only.const alice = await findUserById(1);alice.access = await loadAccess(1);alice.access.assignments = alice.access.assignments.filter((a) => !(a.building_id === 10 && a.role === 'building_admin'));const call = buildAuthorizationCall(alice, 'DeleteIssue', await findIssue(101));console.log('after revoking alice building_admin@10 in the database only:');console.log('  attributes:', decide(call, attributePolicySet));console.log('  templates (links not yet updated):', decide(call, templatePolicySet)); await pool.end();

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/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-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.2