Caretaker Express · PostgreSQL · Cedar

Module 9 · Trust boundaries and architecture

9.2 PDP, PIP, PEP and PAP, and a separate decision service

Name the four parts of Caretaker's authorization with the standard terms, then build an optional decision service that loads its own facts, authenticates its callers, and ignores attributes they send.

≈ 35 min 13 steps 99 lines of code Replay verified

Starting point

Authorization runs inside the app process: routes call can(), which builds entities from the database and evaluates them with Cedar.

Outcome

Text
services/authz-service.js         (new: an optional decision service)services/start-authz-service.js   (new: starts it on port 4000)test/authz-service.test.js        (new)

You can point at each part of the architecture by its standard name, and explain what changes, and what must not change, when the decision moves to another process.

The problem

As systems grow, teams often move authorization decisions into a shared service, so that several applications ask one place. That can be a good idea, and it is easy to do badly: the most common mistake is a service that decides on attributes its caller sends. Then any caller (or anyone who can impersonate one) can send adminBuildings: [30] and receive allow, exactly as lesson 9.1 showed.

Before moving anything, we need words for the parts. The terms come from the XACML standard and are used widely:

PEP, PDP, PIP and PAP in Caretaker The routes and templates are the policy enforcement point. They call can, which uses the entity mapper and loaders as the policy information point, and the Cedar engine as the policy decision point. Policy files in Git and the access management pages are the policy administration point. PEPenforcement point routes: load → can() → acttemplates: can() for buttonslist guard per rowdecides nothing; obeys PDPdecision point src/authz/cedar.jsCedar WASM evaluate()fails closedreads no data of its own PIPinformation point loadAccess(), findIssue() …entities.js (mapper)request.jsfacts from PostgreSQL PAPadministration point policies/*.cedar in Gitmembers + building access pagesrules change by review; grants by data can() entities policies grants (rows)
Caretaker's authorization architecture with the standard names.
Term Meaning In Caretaker
PEP, policy enforcement point Intercepts the action and obeys the decision Each route (load → can() → act), template buttons, the list guard
PDP, policy decision point Evaluates policies against a request and facts; returns a decision src/authz/cedar.js and the Cedar engine
PIP, policy information point Supplies the facts the PDP needs loadAccess, the model finders, entities.js, request.js
PAP, policy administration point Where rules and grants are managed Policy files in Git (rules); members and building access pages (grants, as data)

The security of the whole rests on two properties: the PEP must ask before every action and obey, and the PIP must supply only true facts.

Build it

1. The service

Create services/authz-service.js:

Create fileservices/authz-service.jsJavaScript
// An optional, separate decision service: a PDP with its own PIP. The app does not use it.// Callers say WHO (a user id), WHAT (an action) and WHICH (a resource id).// The service loads every fact itself and ignores any attributes in the request.import express from 'express';import crypto from 'node:crypto';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 { findBuilding } from '../src/models/buildings.js';import { findOrganisation } from '../src/models/organisations.js';import { RESOURCE_TYPES, buildAuthorizationCall } from '../src/authz/request.js';import { evaluate } from '../src/authz/cedar.js';import { ref } from '../src/authz/entities.js';import { parseId } from '../src/lib/ids.js'; const FINDERS = { Issue: findIssue, Inspection: findInspection, Building: findBuilding, Organisation: findOrganisation };const ROLES = ['viewer', 'reporter', 'inspector', 'building_admin', 'member', 'org_admin']; export const authzService = express();authzService.disable('x-powered-by');authzService.use(express.json({ limit: '10kb' })); // Only known callers may ask. Each caller holds a secret token.authzService.use((req, res, next) => {  const expected = `Bearer ${process.env.AUTHZ_SERVICE_TOKEN ?? ''}`;  const sent = req.get('authorization') ?? '';  const ok = expected.length > 'Bearer '.length && sent.length === expected.length    && crypto.timingSafeEqual(Buffer.from(sent), Buffer.from(expected));  if (!ok) return res.status(401).json({ error: 'unknown caller' });  next();}); authzService.post('/v1/decisions', async (req, res) => {  const { userId, action, resourceId, context = {} } = req.body ?? {};  const type = RESOURCE_TYPES[action];  const user = parseId(String(userId)) && (await findUserById(Number(userId)));  const row = type && parseId(String(resourceId)) && (await FINDERS[type](Number(resourceId)));  if (!user || !row) {    return res.status(404).json({ error: 'unknown user, action or resource' });  }  user.access = await loadAccess(user.id);   // Context: accept only the two fields our actions use, and check them against the database.  let cedarContext = {};  if (action === 'ManageBuildingRoles' || action === 'ManageMembers') {    const target = parseId(String(context.targetUserId)) && (await findUserById(Number(context.targetUserId)));    if (!target || !ROLES.includes(context.role)) {      return res.status(400).json({ error: 'context needs an existing targetUserId and a known role' });    }    cedarContext = { targetUser: ref('User', target.id), role: context.role };  }   const result = evaluate(buildAuthorizationCall(user, action, row, cedarContext));  res.json({ decision: result.allowed ? 'allow' : 'deny', reasons: result.reasons });});

Read the contract it offers:

  • Authenticated callers only. A bearer token shared with each calling application, compared in constant time. (Real deployments use stronger service identity, such as mutual TLS; the principle is the same.)
  • Identifiers in, facts loaded inside. The request names the user, action and resource. The service loads the user's access and the resource row from its own connection to the database. Any other field in the body (attributes, adminBuildings, ...) is simply never read.
  • Context is validated, exactly as in the app: an existing target user and an allowlisted role.
  • The same PDP code (evaluate, the same policies) as the app, so decisions are identical.

Notice what the service trusts: it believes the caller about which user is acting. The app authenticated that user; the service did not. That is the trust relationship between the two, and the reason callers must be authenticated.

2. Start it on its own port

Create fileservices/start-authz-service.jsJavaScript
import { authzService } from './authz-service.js'; const port = Number(process.env.AUTHZ_SERVICE_PORT ?? 4000);authzService.listen(port, () => {  console.log(`authz service listening on http://localhost:${port}`);});

Give the service a token. Generate one into .env the same way as the session secret, and give tests a fixed one:

Runcaretaker/
echo "AUTHZ_SERVICE_TOKEN=$(node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))")" >> .env
npm pkg set scripts.authz:service="node --env-file=.env services/start-authz-service.js"
Edit.env.test.env
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
LOGIN_RATE_LIMIT=5AUTHZ_SERVICE_TOKEN=test-only-service-token
Show the whole .env.test after this change
# Settings for automated tests. Local learning values only; safe to commit.NODE_ENV=testDATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_testPORT=3001LOG_SQL=0SESSION_SECRET=test-only-secret-never-use-this-anywhere-realLOGIN_RATE_LIMIT=5AUTHZ_SERVICE_TOKEN=test-only-service-token
Edit.env.example.env
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
SESSION_SECRET=# Only for the optional decision service in services/. Generate like SESSION_SECRET.AUTHZ_SERVICE_TOKEN=
Show the whole .env.example after this change
# Copy this file to .env and adjust if needed. Never commit .env.DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretakerPORT=3000# Set to 1 to print every SQL statement the app runs.LOG_SQL=0# Required. Generate with:# node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"SESSION_SECRET=# Only for the optional decision service in services/. Generate like SESSION_SECRET.AUTHZ_SERVICE_TOKEN=

3. Tests

Create filetest/authz-service.test.jsJavaScript
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { pool } from '../src/db.js';import { authzService } from '../services/authz-service.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); const ask = (body, token = 'test-only-service-token') =>  request(authzService).post('/v1/decisions').set('Authorization', `Bearer ${token}`).send(body); test('unknown callers are refused', async () => {  assert.equal((await ask({ userId: 1, action: 'ViewIssue', resourceId: 101 }, 'wrong')).status, 401);  assert.equal((await request(authzService).post('/v1/decisions').send({})).status, 401);}); test('decisions match the app', async () => {  assert.deepEqual((await ask({ userId: 1, action: 'ViewIssue', resourceId: 101 })).body, { decision: 'allow', reasons: ['building-read'] });  assert.equal((await ask({ userId: 1, action: 'ViewIssue', resourceId: 105 })).body.decision, 'deny');  assert.equal((await ask({ userId: 1, action: 'ApproveInspection', resourceId: 202 })).body.reasons[0], 'forbid-self-approval');}); test('attributes sent by the caller are ignored', async () => {  const res = await ask({ userId: 1, action: 'ViewIssue', resourceId: 105, attributes: { adminBuildings: [{ type: 'Caretaker::Building', id: '30' }] }, adminBuildings: ['30'] });  assert.equal(res.body.decision, 'deny');}); test('context is validated and used', async () => {  assert.equal((await ask({ userId: 1, action: 'ManageBuildingRoles', resourceId: 10, context: { targetUserId: 4, role: 'building_admin' } })).body.decision, 'deny');  assert.equal((await ask({ userId: 1, action: 'ManageBuildingRoles', resourceId: 10, context: { targetUserId: 4, role: 'viewer' } })).body.decision, 'allow');  assert.equal((await ask({ userId: 1, action: 'ManageBuildingRoles', resourceId: 10, context: { targetUserId: 99, role: 'viewer' } })).status, 400);});

Run and inspect

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) (465.347792ms)
✔ edit issue 101 (26.891416ms)
✔ view issue 103 (building 20) (32.75775ms)
✔ edit issue 103 (reported by dave) (21.529291ms)
✔ report an issue at building 20 (34.604958ms)
✔ view issue 105 (building 30) (20.078334ms)
✔ view issue 106 (building 40, reported by bob) (16.723ms)
✔ approve inspection 201 (created by dave) (17.398208ms)
✔ approve inspection 202 (created by alice) (18.6795ms)
✔ update organisation 1 (22.779208ms)
✔ change own role at building 10 (5.004583ms)
✔ grant building_admin at building 10 to dave (21.236042ms)
✔ grant viewer at building 10 to dave (16.640958ms)
✔ issues in each user's list come only from the expected buildings (130.431916ms)
✔ the scenario loads exactly as specified (206.004125ms)
✔ only one active assignment per user, building and role (0.890084ms)
✔ a revoked role can be granted again (0.909875ms)
✔ the My access page shows what the server loaded (73.226917ms)
✔ a correct login creates a session and shows the user (261.070209ms)
✔ a wrong password or unknown email gets the same 401 (55.533042ms)
✔ registration validates, creates a user, and logs them in (44.604333ms)
✔ registering an existing email is a field error (27.056417ms)
✔ logout destroys the session (52.113375ms)
✔ allow: a permit matched and nothing forbade it (211.24525ms)
✔ explicit deny: a forbid overrides a matching permit (2.52825ms)
✔ implicit deny: no permit matched (2.168417ms)
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 (3.248125ms)
Show 109 more lines✔ unknown actions throw instead of deciding (1.231875ms) ✔ unknown callers are refused (203.107417ms) ✔ decisions match the app (26.237ms) ✔ attributes sent by the caller are ignored (3.358583ms) ✔ context is validated and used (9.847958ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (378.688167ms) ✔ a revoked assignment cannot be revoked again (5.918208ms) ✔ an assignment id from another building is not found here (6.188958ms) ✔ alice cannot revoke her own building_admin role; carol can (11.530875ms) ✔ grants are limited to members of the building's organisation (7.211042ms) ✔ a building can be created inside an organisation (278.343708ms) ✔ a duplicate building name in the same organisation is a field error (5.252417ms) ✔ the same building name is allowed in another organisation (9.605292ms) ✔ a building with issues cannot be deleted (13.431ms) ✔ an empty building can be deleted (10.094041ms) ✔ an organisation with buildings cannot be deleted, an empty one can (23.967291ms) ✔ a logged-in POST without a token is refused with 403 (276.88375ms) ✔ a token from another session is refused (35.18925ms) ✔ the right token in the form field works (31.033875ms) ✔ every POST form on every page carries the token (53.723958ms) ✔ the dashboard counts match the database (269.645625ms) ✔ only the buildings carol can see appear (4.574541ms) ✔ headers that claim another identity are ignored (255.36325ms) ✔ query strings and form fields that claim roles are ignored (10.951459ms) ✔ a forged reporter or status in an edit form does not reach the database (5.356958ms) ✔ a forged grant context cannot make dave a building admin (6.137166ms) ✔ create a draft, edit it, submit it, approve it (329.802292ms) ✔ invalid transitions are refused with 409 and change nothing (11.886584ms) ✔ only drafts can be edited (5.428959ms) ✔ returning a submitted inspection makes it editable again (7.478667ms) ✔ concurrent approvals: exactly one wins (23.138333ms) ✔ unknown actions are 404 (2.8245ms) ✔ the issues list contains only issues from visible buildings (584.340625ms) ✔ a filter for another tenant's building returns nothing (3.888ms) ✔ the inspections list is scoped too (9.990667ms) ✔ organisations are listed for their members only (8.146625ms) ✔ the dashboard counts only visible data (7.244583ms) ✔ view issue 101 (building 10) (483.647375ms) ✔ open the edit form for issue 101 (27.82675ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (25.867875ms) ✔ view issue 105 (building 30) and 106 (building 40) (41.460625ms) ✔ report an issue at building 20 (29.592083ms) ✔ a reporter cannot edit their own issue once it is closed (12.653625ms) ✔ only building admins may delete; refusals change nothing (16.011542ms) ✔ the edit form cannot move an issue to another building (5.717ms) ✔ the list pages 10 at a time and reports the total (311.156667ms) ✔ pages do not overlap (23.523041ms) ✔ filters combine with AND (7.112292ms) ✔ sorting by priority puts critical first when descending (7.05625ms) ✔ unknown sort keys and SQL in the query string are ignored (40.693375ms) ✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (344.37075ms) ✔ dave may update his own issue 103 but is not a reporter at building 10 (6.392625ms) ✔ dave cannot move issue 101: he may not update it where it is (4.926958ms) ✔ carol moves 101 to building 20, but never to another organisation (10.2555ms) ✔ a forged building id on create is refused and creates nothing (29.089958ms) ✔ GET /issues lists issues from the database (285.05075ms) ✔ GET /issues/101 shows one issue with its building (10.408292ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (13.649125ms) ✔ POST /issues re-renders the form with errors (5.004875ms) ✔ POST /issues stores the issue and redirects to it (8.669542ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.338167ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.580667ms) ✔ an issue time in the future is rejected (4.4285ms) ✔ GET /issues/101/edit shows the current values (5.048333ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.319833ms) ✔ POST /issues/:id/delete removes the issue (12.04075ms) ✔ the issues list contains exactly the issues Cedar lets each user view (340.986167ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (20.441666ms) ✔ only organisation admins can open the members page (403.608ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (21.9655ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.495ms) ✔ nobody changes their own membership (4.076875ms) ✔ unknown emails and roles are form errors (12.118708ms) ✔ a member cannot add members, even with a well-formed request (3.213667ms) ✔ GET /organisations lists organisations with building counts (274.510833ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (14.585292ms) ✔ POST /organisations validates and creates (14.186458ms) ✔ POST /organisations/:id/edit renames the organisation (11.325792ms) ✔ unknown organisations are 404 (6.349292ms) ✔ every policy is valid against the schema (32.3305ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.420709ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (356.702292ms) ✔ anonymous requests are redirected to the login page (214.787958ms) ✔ anonymous writes are refused and change nothing (14.517958ms) ✔ login and register pages stay public (5.98375ms) ✔ login issues a new session id (no session fixation) (33.094459ms) ✔ returnTo only follows local paths (31.508042ms) ✔ new issues and transitions record the logged-in user (91.087125ms) ✔ the session cookie has the attributes we chose (25.932792ms) ✔ organisation 1: view and update (489.790042ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.2015ms) ✔ building 10: view, update, delete (61.709833ms) ✔ creating buildings needs org_admin (16.232791ms) ✔ creating an organisation makes the creator its admin (9.158791ms) ✔ inspections: view 201, open the edit form for draft 203 (47.331625ms) ✔ approve inspection 201 (dave's): only building admins (15.228833ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (14.969583ms) ✔ bob gets 404 for every Liffey route, and nothing changes (487.404292ms) ✔ ravi gets 404 for every Liffey route, and nothing changes (106.395666ms) ✔ nora gets 404 for every Liffey route, and nothing changes (79.574875ms) ✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (59.022083ms) ℹ tests 128 ℹ suites 0 ℹ pass 128 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 14195.962
Server terminal (leave it running)caretaker/
npm run authz:service
> caretaker@1.0.0 authz:service
> node --env-file=.env services/start-authz-service.js

authz service listening on http://localhost:4000

Ask it about Alice and issue 101, as an application would:

Run and comparecaretaker/
TOKEN=$(grep '^AUTHZ_SERVICE_TOKEN=' .env | cut -d= -f2)
curl -s http://localhost:4000/v1/decisions -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"userId":1,"action":"ViewIssue","resourceId":101}'
{"decision":"allow","reasons":["building-read"]}

And as an attacker who stole nothing but tries to describe Alice as an admin of building 30:

Run and comparecaretaker/
TOKEN=$(grep '^AUTHZ_SERVICE_TOKEN=' .env | cut -d= -f2)
curl -s http://localhost:4000/v1/decisions -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" -d '{"userId":1,"action":"ViewIssue","resourceId":105,"adminBuildings":["30"]}'
{"decision":"deny","reasons":[]}

deny. The service read the facts from the database and never looked at adminBuildings.

Ctrl+C Stop the server in the server terminal.

Experiment

The service decides. It does not enforce.

Predict An attacker gains control of a Caretaker web process, which holds the database password in its environment. What does the separate decision service prevent?
Reveal Answer

Nothing. A compromised PEP simply does not ask, and with direct database credentials it can read or change any row. Moving the PDP to another process does not move enforcement; it adds a dependency (and latency, and a new failure mode: what does the app do when the service is down? It must deny). Cedar, in-process or remote, never touches the database. Limiting what a compromised process can do is a database question: the next lesson gives the app less power and lets PostgreSQL itself refuse.

Checkpoint

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) (447.325959ms)
✔ edit issue 101 (24.537708ms)
✔ view issue 103 (building 20) (23.054167ms)
✔ edit issue 103 (reported by dave) (25.34575ms)
✔ report an issue at building 20 (26.899834ms)
✔ view issue 105 (building 30) (17.969375ms)
✔ view issue 106 (building 40, reported by bob) (15.225042ms)
✔ approve inspection 201 (created by dave) (15.299208ms)
✔ approve inspection 202 (created by alice) (22.512166ms)
✔ update organisation 1 (19.210334ms)
✔ change own role at building 10 (4.662333ms)
✔ grant building_admin at building 10 to dave (19.922542ms)
✔ grant viewer at building 10 to dave (15.877417ms)
✔ issues in each user's list come only from the expected buildings (108.261708ms)
✔ the scenario loads exactly as specified (211.546375ms)
✔ only one active assignment per user, building and role (0.949667ms)
✔ a revoked role can be granted again (0.90375ms)
✔ the My access page shows what the server loaded (71.40725ms)
✔ a correct login creates a session and shows the user (270.111166ms)
✔ a wrong password or unknown email gets the same 401 (55.698334ms)
✔ registration validates, creates a user, and logs them in (53.648ms)
✔ registering an existing email is a field error (32.974125ms)
✔ logout destroys the session (52.962583ms)
✔ allow: a permit matched and nothing forbade it (219.153375ms)
✔ explicit deny: a forbid overrides a matching permit (2.766542ms)
✔ implicit deny: no permit matched (2.573375ms)
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 (3.419666ms)
Show 109 more lines✔ unknown actions throw instead of deciding (1.255875ms) ✔ unknown callers are refused (194.881167ms) ✔ decisions match the app (25.224084ms) ✔ attributes sent by the caller are ignored (3.022083ms) ✔ context is validated and used (10.148ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (388.673417ms) ✔ a revoked assignment cannot be revoked again (4.734292ms) ✔ an assignment id from another building is not found here (3.952875ms) ✔ alice cannot revoke her own building_admin role; carol can (14.341292ms) ✔ grants are limited to members of the building's organisation (6.261792ms) ✔ a building can be created inside an organisation (287.800458ms) ✔ a duplicate building name in the same organisation is a field error (5.633042ms) ✔ the same building name is allowed in another organisation (8.661333ms) ✔ a building with issues cannot be deleted (17.153042ms) ✔ an empty building can be deleted (10.900916ms) ✔ an organisation with buildings cannot be deleted, an empty one can (26.839334ms) ✔ a logged-in POST without a token is refused with 403 (275.327125ms) ✔ a token from another session is refused (34.424667ms) ✔ the right token in the form field works (17.949416ms) ✔ every POST form on every page carries the token (54.120916ms) ✔ the dashboard counts match the database (260.350708ms) ✔ only the buildings carol can see appear (4.857917ms) ✔ headers that claim another identity are ignored (254.56825ms) ✔ query strings and form fields that claim roles are ignored (15.364375ms) ✔ a forged reporter or status in an edit form does not reach the database (5.608209ms) ✔ a forged grant context cannot make dave a building admin (4.583875ms) ✔ create a draft, edit it, submit it, approve it (345.852041ms) ✔ invalid transitions are refused with 409 and change nothing (12.204625ms) ✔ only drafts can be edited (5.472583ms) ✔ returning a submitted inspection makes it editable again (8.025709ms) ✔ concurrent approvals: exactly one wins (26.194583ms) ✔ unknown actions are 404 (3.109875ms) ✔ the issues list contains only issues from visible buildings (582.880333ms) ✔ a filter for another tenant's building returns nothing (3.623959ms) ✔ the inspections list is scoped too (9.271958ms) ✔ organisations are listed for their members only (8.089291ms) ✔ the dashboard counts only visible data (6.376333ms) ✔ view issue 101 (building 10) (484.004459ms) ✔ open the edit form for issue 101 (22.798792ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (26.80725ms) ✔ view issue 105 (building 30) and 106 (building 40) (43.487416ms) ✔ report an issue at building 20 (28.885125ms) ✔ a reporter cannot edit their own issue once it is closed (8.498083ms) ✔ only building admins may delete; refusals change nothing (16.188125ms) ✔ the edit form cannot move an issue to another building (3.895458ms) ✔ the list pages 10 at a time and reports the total (301.357708ms) ✔ pages do not overlap (30.605875ms) ✔ filters combine with AND (8.132625ms) ✔ sorting by priority puts critical first when descending (7.356083ms) ✔ unknown sort keys and SQL in the query string are ignored (40.813875ms) ✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (360.563875ms) ✔ dave may update his own issue 103 but is not a reporter at building 10 (6.520292ms) ✔ dave cannot move issue 101: he may not update it where it is (5.119666ms) ✔ carol moves 101 to building 20, but never to another organisation (10.594709ms) ✔ a forged building id on create is refused and creates nothing (22.405208ms) ✔ GET /issues lists issues from the database (284.002375ms) ✔ GET /issues/101 shows one issue with its building (7.227834ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.157333ms) ✔ POST /issues re-renders the form with errors (5.404042ms) ✔ POST /issues stores the issue and redirects to it (9.220584ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.535625ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.658625ms) ✔ an issue time in the future is rejected (4.289959ms) ✔ GET /issues/101/edit shows the current values (4.915875ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.181291ms) ✔ POST /issues/:id/delete removes the issue (11.430208ms) ✔ the issues list contains exactly the issues Cedar lets each user view (330.373167ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (20.299584ms) ✔ only organisation admins can open the members page (460.280458ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (17.197417ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (16.619959ms) ✔ nobody changes their own membership (5.763417ms) ✔ unknown emails and roles are form errors (11.55175ms) ✔ a member cannot add members, even with a well-formed request (3.6725ms) ✔ GET /organisations lists organisations with building counts (254.546125ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (14.462583ms) ✔ POST /organisations validates and creates (14.211ms) ✔ POST /organisations/:id/edit renames the organisation (11.581208ms) ✔ unknown organisations are 404 (6.099333ms) ✔ every policy is valid against the schema (32.365208ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.304208ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (353.037584ms) ✔ anonymous requests are redirected to the login page (215.88475ms) ✔ anonymous writes are refused and change nothing (10.516625ms) ✔ login and register pages stay public (6.271375ms) ✔ login issues a new session id (no session fixation) (32.36175ms) ✔ returnTo only follows local paths (29.559708ms) ✔ new issues and transitions record the logged-in user (84.619417ms) ✔ the session cookie has the attributes we chose (26.375917ms) ✔ organisation 1: view and update (480.721792ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.986209ms) ✔ building 10: view, update, delete (67.335166ms) ✔ creating buildings needs org_admin (18.470542ms) ✔ creating an organisation makes the creator its admin (9.283166ms) ✔ inspections: view 201, open the edit form for draft 203 (47.357ms) ✔ approve inspection 201 (dave's): only building admins (17.476333ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (14.748584ms) ✔ bob gets 404 for every Liffey route, and nothing changes (450.11625ms) ✔ ravi gets 404 for every Liffey route, and nothing changes (93.797167ms) ✔ nora gets 404 for every Liffey route, and nothing changes (82.235292ms) ✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (67.753833ms) ℹ tests 128 ℹ suites 0 ℹ pass 128 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 14190.2125
Run and comparecaretaker/
git add -A
git commit -m "Optional decision service with its own information point"
[main 604098e] Optional decision service with its own information point
 6 files changed, 101 insertions(+), 1 deletion(-)
 create mode 100644 services/authz-service.js
 create mode 100644 services/start-authz-service.js
 create mode 100644 test/authz-service.test.js
Symptom The service answers 401 to your curl command

Your shell variable TOKEN is empty: the .env file has no AUTHZ_SERVICE_TOKEN line. Run the echo ... >> .env step again.

Recap and next step

PEP, PDP, PIP and PAP name the parts we already had: routes enforce, Cedar decides, loaders and the mapper inform, policy files and access pages administer. A separate decision service is safe only if it authenticates callers, accepts identifiers rather than attributes, and loads facts itself. Even then, enforcement stays with the caller, and a compromised caller with database credentials bypasses everything.

Next: defence in depth inside PostgreSQL, and the time-based risks (stale data, caches, races) that every authorization system must face.