Caretaker Express · PostgreSQL · Cedar

Module 7 · RBAC, ABAC, scoped roles and policy management

7.2 Policy templates, compared

Build a real template-linked version of the read and admin rights, check that it decides exactly like our attribute policies, and see what happens to each design when a role is revoked.

≈ 25 min 5 steps 85 lines of code Replay verified

Starting point

Nine static policies read role facts from user attributes (viewerBuildings, adminBuildings, ...) and follow parents. The policy store never changes when someone is granted a role; only database rows change.

Outcome

Text
scripts/template-demo.js    (new: a standalone comparison, not used by the app)

You can explain the third modelling option, template-linked policies, show that it reproduces our decisions for read and admin rights, and say when you would choose it.

The problem

Our design puts each assignment into the entity data for every request. Another common design puts each assignment into the policy store: one small policy per grant, such as "Alice may administer building 10". Writing those by hand would be absurd; Cedar offers templates, policies with placeholders that are linked to concrete values. Managed services that host Cedar policies often encourage this style.

Which is right for Caretaker? Build a small real version and compare, instead of guessing. See Policy templates in the Cedar documentation.

Build it

Create scripts/template-demo.js:

Create filescripts/template-demo.jsJavaScript
// 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();

What the script does:

  • Two templates. principal == ?principal and resource in ?resource are slots. A template is not a policy until it is linked.
  • buildLinks reads the same rows loadAccess reads, and creates one link per grant: a read link for every assignment, plus an admin link for building_admin, plus both for each organisation admin (with ?resource set to the organisation, so parents carry them to every building).
  • The comparison runs each request twice with the same entities: once with our nine static policies, once with only the template links (plus the forbid). Because the template policies never read user attributes, the attributes in the entities are simply ignored by them.
  • The last part simulates a revocation by removing the fact from the user's loaded access, the way a database UPDATE would on the next request, without touching the links.

Run and inspect

Run and comparecaretaker/
node --env-file=.env scripts/template-demo.js
template links generated: 9
example link: {"templateId":"admin-template","newId":"admin-template:user-1:Building-10","values":{"?principal":{"type":"Caretaker::User","id":"1"},"?resource":{"type":"Caretaker::Building","id":"10"}}}
decisions compared: 432, differences: 0
after revoking alice building_admin@10 in the database only:
  attributes: deny
  templates (links not yet updated): allow

Read the output:

  • 9 links: a read link for each of the five active assignments, an admin link for each of the two building_admin assignments (Alice at 10, Bob at 30), and both kinds for Carol's organisation. Each link is a policy, with its own ID.
  • The example link shows the filled slots: ?principal is User::"1", ?resource is Building::"10".
  • All 432 comparisons agree. Templates can express our read and admin rights exactly, including Carol's organisation inheritance (through resource in ?resource with an organisation) and the forbid.
  • After the revocation, the attribute design denies at once; the template design still allows. The link for "Alice administers building 10" is still in the policy set.

Choosing between the designs

Attributes on entities (Caretaker) Template-linked policies
Where a grant lives A database row; mapped into entities per request A link in the policy store
What a grant changes Data only; policies never change The policy store, on every grant and revoke
Revocation takes effect On the next request, from the database When the link is deleted; database and policy store must be kept in step
Policy store size Constant (nine policies) Grows with every grant (9 links here; thousands in a large company)
Entities per request Must include the user's role sets Can be smaller: just principal and resource with parents
Inspecting "who can do X?" Query the database Read the links
Good fit Roles already stored in your own database A separate service owns the policies and stores grants as policies

Templates are not wrong; they move the source of truth. For Caretaker the database already holds the grants, with history and constraints, so a second copy in a policy store would mean two systems to keep consistent. We keep the attribute design, and remember the key property: granting or revoking a role changes rows, not policies.

Experiment

Both designs can express a rule that no grant mentions. Try it with the template design:

Predict If the template design leaves out the forbid-self-approval policy, which comparisons will disagree?
Run and comparecaretaker/
WITHOUT_FORBID=1 node --env-file=.env scripts/template-demo.js
template links generated: 9
example link: {"templateId":"admin-template","newId":"admin-template:user-1:Building-10","values":{"?principal":{"type":"Caretaker::User","id":"1"},"?resource":{"type":"Caretaker::Building","id":"10"}}}
decisions compared: 432, differences: 3
   user 1 ApproveInspection 202: attributes=deny templates=allow
   user 2 ApproveInspection 204: attributes=deny templates=allow
   user 3 ApproveInspection 203: attributes=deny templates=allow
after revoking alice building_admin@10 in the database only:
  attributes: deny
  templates (links not yet updated): allow
Reveal Answer

Three: Alice on inspection 202, Bob on inspection 204 and Carol on inspection 203, each an admin approving an inspection they created. Without the forbid, the admin link permits all three. (Cedar answers the permission question only; inspections 203 and 204 are drafts, and the app's workflow would still refuse them with 409.) Exceptions such as separation of duties stay static forbid policies in either design.

Checkpoint

The script is a study aid; the app does not use it. Tests are unchanged:

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) (515.867375ms)
✔ edit issue 101 (64.559709ms)
✔ view issue 103 (building 20) (57.911459ms)
✔ edit issue 103 (reported by dave) (83.865417ms)
✔ report an issue at building 20 (98.706125ms)
✔ view issue 105 (building 30) (47.998166ms)
✔ view issue 106 (building 40, reported by bob) (37.773333ms)
✔ approve inspection 201 (created by dave) (39.790708ms)
✔ approve inspection 202 (created by alice) (55.24475ms)
✔ update organisation 1 (47.903042ms)
✔ issues in each user's list come only from the expected buildings (93.188292ms)
✔ the scenario loads exactly as specified (213.885167ms)
✔ only one active assignment per user, building and role (1.014333ms)
✔ a revoked role can be granted again (1.604791ms)
✔ the My access page shows what the server loaded (72.536167ms)
✔ a correct login creates a session and shows the user (268.354125ms)
✔ a wrong password or unknown email gets the same 401 (53.992583ms)
✔ registration validates, creates a user, and logs them in (36.130833ms)
✔ registering an existing email is a field error (31.762958ms)
✔ logout destroys the session (51.560084ms)
✔ allow: a permit matched and nothing forbade it (201.051667ms)
✔ explicit deny: a forbid overrides a matching permit (5.717125ms)
✔ implicit deny: no permit matched (5.241083ms)
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 (6.526083ms)
✔ unknown actions throw instead of deciding (1.963417ms)
✔ a building can be created inside an organisation (303.449167ms)
✔ a duplicate building name in the same organisation is a field error (15.096833ms)
Show 76 more lines✔ the same building name is allowed in another organisation (23.910875ms) ✔ a building with issues cannot be deleted (33.867833ms) ✔ an empty building can be deleted (26.756583ms) ✔ an organisation with buildings cannot be deleted, an empty one can (57.209625ms) ✔ a logged-in POST without a token is refused with 403 (272.914458ms) ✔ a token from another session is refused (36.028625ms) ✔ the right token in the form field works (33.044292ms) ✔ every POST form on every page carries the token (174.745084ms) ✔ the dashboard counts match the database (290.873583ms) ✔ only the buildings carol can see appear (4.933459ms) ✔ create a draft, edit it, submit it, approve it (382.9905ms) ✔ invalid transitions are refused with 409 and change nothing (39.077916ms) ✔ only drafts can be edited (21.898417ms) ✔ returning a submitted inspection makes it editable again (23.780958ms) ✔ concurrent approvals: exactly one wins (67.608333ms) ✔ unknown actions are 404 (3.441666ms) ✔ the issues list contains only issues from visible buildings (544.477584ms) ✔ a filter for another tenant's building returns nothing (4.418708ms) ✔ the inspections list is scoped too (9.609709ms) ✔ organisations are listed for their members only (8.872875ms) ✔ the dashboard counts only visible data (7.352041ms) ✔ view issue 101 (building 10) (506.391416ms) ✔ open the edit form for issue 101 (92.840167ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (68.964958ms) ✔ view issue 105 (building 30) and 106 (building 40) (93.413291ms) ✔ report an issue at building 20 (96.327125ms) ✔ a reporter cannot edit their own issue once it is closed (35.913875ms) ✔ only building admins may delete; refusals change nothing (37.824167ms) ✔ the edit form cannot move an issue to another building (10.055333ms) ✔ the list pages 10 at a time and reports the total (300.048208ms) ✔ pages do not overlap (16.557ms) ✔ filters combine with AND (5.458958ms) ✔ sorting by priority puts critical first when descending (4.671333ms) ✔ unknown sort keys and SQL in the query string are ignored (28.044041ms) ✔ GET /issues lists issues from the database (277.361583ms) ✔ GET /issues/101 shows one issue with its building (23.18525ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (17.61825ms) ✔ POST /issues re-renders the form with errors (17.003125ms) ✔ POST /issues stores the issue and redirects to it (20.785792ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (15.876ms) ✔ the stored row has the cleaned values and ignores a client-sent status (7.517083ms) ✔ an issue time in the future is rejected (15.573375ms) ✔ GET /issues/101/edit shows the current values (23.831542ms) ✔ POST /issues/:id/edit changes the status and updated_at (13.000708ms) ✔ POST /issues/:id/delete removes the issue (19.699208ms) ✔ GET /organisations lists organisations with building counts (267.607917ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (31.711791ms) ✔ POST /organisations validates and creates (29.48375ms) ✔ POST /organisations/:id/edit renames the organisation (32.409834ms) ✔ unknown organisations are 404 (14.188292ms) ✔ every policy is valid against the schema (31.532083ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (8.535208ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (367.088667ms) ✔ anonymous requests are redirected to the login page (216.125125ms) ✔ anonymous writes are refused and change nothing (11.120584ms) ✔ login and register pages stay public (7.441292ms) ✔ login issues a new session id (no session fixation) (33.3245ms) ✔ returnTo only follows local paths (30.237583ms) ✔ new issues and transitions record the logged-in user (110.687708ms) ✔ the session cookie has the attributes we chose (29.742ms) ✔ organisation 1: view and update (590.767292ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (31.993125ms) ✔ building 10: view, update, delete (148.418084ms) ✔ creating buildings needs org_admin (51.093333ms) ✔ creating an organisation makes the creator its admin (19.219375ms) ✔ inspections: view 201, open the edit form for draft 203 (113.198167ms) ✔ approve inspection 201 (dave's): only building admins (44.89325ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (45.2405ms) ℹ tests 95 ℹ suites 0 ℹ pass 95 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 11546.577667
Run and comparecaretaker/
git add -A
git commit -m "Compare policy templates with attribute-based policies"
[main 00d1bb8] Compare policy templates with attribute-based policies
 1 file changed, 85 insertions(+)
 create mode 100644 scripts/template-demo.js
Symptom template ... is not linked or slot ?resource not found

Each link needs a value for every slot in its template: ?principal and ?resource here, with exactly those keys including the question mark.

Symptom duplicate policy id failure

Every link's newId must be unique across the whole policy set, including static policy IDs.

Recap and next step

A template is a policy with slots; each link is one concrete policy. Template links reproduced our read and admin decisions exactly, but they put every grant into the policy store, which then has to change on every grant and revoke. Caretaker keeps grants as rows and rights as attributes, so a grant changes data, not policies.

So far grants only change through the seed or psql. Next we let people manage access through the app, starting with who belongs to an organisation.