Checkpoint · Lesson 9.2
PDP, PIP, PEP and PAP, and a separate decision service: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m09-l02 -- src.
Files changed in this lesson
.env.example changed
.env.example# Copy this file to .env and adjust if needed. Never commit .env.
DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker
PORT=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=
# 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=.env.test changed
.env.test# Settings for automated tests. Local learning values only; safe to commit.
NODE_ENV=test
DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_test
PORT=3001
LOG_SQL=0
SESSION_SECRET=test-only-secret-never-use-this-anywhere-real
LOGIN_RATE_LIMIT=5
AUTHZ_SERVICE_TOKEN=test-only-service-token
# 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-tokenpackage.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",
"authz:service": "node --env-file=.env services/start-authz-service.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"
}
}
{ "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", "authz:service": "node --env-file=.env services/start-authz-service.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" }}services/authz-service.js added
services/authz-service.js// 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 });
});
// 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 });});services/start-authz-service.js added
services/start-authz-service.jsimport { 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}`);
});
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}`);});test/authz-service.test.js added
test/authz-service.test.jsimport { 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);
});
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);});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
migrations/006_create_permission_changes.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/authz-bench.js
scripts/authz-explain.js
scripts/cedar-errors-demo.js
scripts/cedar-hello.js
scripts/forged-entity-demo.js
scripts/migrate.js
scripts/partial-demo.js
scripts/seed.js
scripts/template-demo.js
scripts/validate-policies.js
services/authz-service.js
services/start-authz-service.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-building-admin-grants.cedar
src/authz/policies/forbid-self-approval.cedar
src/authz/policies/forbid-self-membership-change.cedar
src/authz/policies/forbid-self-role-change.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/assignments.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/members.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/authz-service.test.js
test/building-access.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/forged-input.test.js
test/helpers.js
test/inspections.test.js
test/isolation.test.js
test/issue-authz.test.js
test/issue-list.test.js
test/issue-moves.test.js
test/issues.test.js
test/list-parity.test.js
test/members.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
test/tenant-isolation.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
views/buildings/access.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/move.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/members.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs