Checkpoint · Lesson 6.6
Forbid, precedence, errors and failures: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m06-l06 -- src.
Files changed in this lesson
scripts/cedar-errors-demo.js added
scripts/cedar-errors-demo.js// What happens when a forbid policy cannot be evaluated? Standalone; no schema on purpose.
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
const ref = (type, id) => ({ type: `Caretaker::${type}`, id: String(id) });
const policies = {
'view-anything': 'permit (principal, action == Caretaker::Action::"ViewIssue", resource);',
'forbid-suspended': 'forbid (principal, action, resource) when { principal.suspended };',
};
for (const [label, attrs] of [['suspended: true', { suspended: true }], ['suspended: false', { suspended: false }], ['attribute missing', {}]]) {
const answer = cedar.isAuthorized({
principal: ref('User', 1),
action: { type: 'Caretaker::Action', id: 'ViewIssue' },
resource: ref('Issue', 101),
context: {},
policies: { staticPolicies: policies },
entities: [{ uid: ref('User', 1), attrs, parents: [] }, { uid: ref('Issue', 101), attrs: {}, parents: [] }],
});
const { decision, diagnostics } = answer.response;
console.log(`${label.padEnd(18)} decision=${decision} reason=${diagnostics.reason.join(',')} errors=${diagnostics.errors.map((e) => e.policyId).join(',') || '-'}`);
}
// What happens when a forbid policy cannot be evaluated? Standalone; no schema on purpose.import * as cedar from '@cedar-policy/cedar-wasm/nodejs'; const ref = (type, id) => ({ type: `Caretaker::${type}`, id: String(id) });const policies = { 'view-anything': 'permit (principal, action == Caretaker::Action::"ViewIssue", resource);', 'forbid-suspended': 'forbid (principal, action, resource) when { principal.suspended };',}; for (const [label, attrs] of [['suspended: true', { suspended: true }], ['suspended: false', { suspended: false }], ['attribute missing', {}]]) { const answer = cedar.isAuthorized({ principal: ref('User', 1), action: { type: 'Caretaker::Action', id: 'ViewIssue' }, resource: ref('Issue', 101), context: {}, policies: { staticPolicies: policies }, entities: [{ uid: ref('User', 1), attrs, parents: [] }, { uid: ref('Issue', 101), attrs: {}, parents: [] }], }); const { decision, diagnostics } = answer.response; console.log(`${label.padEnd(18)} decision=${decision} reason=${diagnostics.reason.join(',')} errors=${diagnostics.errors.map((e) => e.policyId).join(',') || '-'}`);}src/authz/policies/administer-building-data.cedar changed
src/authz/policies/administer-building-data.cedar// Building admins may change any issue or inspection at their buildings.
permit (
principal,
action in [
Caretaker::Action::"UpdateIssue",
Caretaker::Action::"DeleteIssue",
Caretaker::Action::"UpdateInspection",
Caretaker::Action::"SubmitInspection",
Caretaker::Action::"ApproveInspection",
Caretaker::Action::"ReturnInspection"
],
resource
)
when { principal.adminBuildings.contains(resource.building) };
// Building admins may change any issue or inspection at their buildings.permit ( principal, action in [ Caretaker::Action::"UpdateIssue", Caretaker::Action::"DeleteIssue", Caretaker::Action::"UpdateInspection", Caretaker::Action::"SubmitInspection", Caretaker::Action::"ApproveInspection", Caretaker::Action::"ReturnInspection" ], resource)when { principal.adminBuildings.contains(resource.building) };src/authz/policies/approve-inspection.cedar deleted
src/authz/policies/forbid-self-approval.cedar added
src/authz/policies/forbid-self-approval.cedar// Separation of duties: nobody approves an inspection they created,
// whatever other policies permit.
forbid (principal, action == Caretaker::Action::"ApproveInspection", resource)
when { resource has createdBy && resource.createdBy == principal };
// Separation of duties: nobody approves an inspection they created,// whatever other policies permit.forbid (principal, action == Caretaker::Action::"ApproveInspection", resource)when { resource has createdBy && resource.createdBy == principal };test/authz-decisions.test.js added
test/authz-decisions.test.jsimport { 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: ['administer-building-data'] });
});
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/);
});
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: ['administer-building-data'] });}); 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/helpers.js changed
test/helpers.jsimport request from 'supertest';
import { app } from '../src/app.js';
import { pool } from '../src/db.js';
import { config } from '../src/config.js';
import { migrate } from '../src/migrate.js';
import { seed, SEED_PASSWORD } from '../src/seed.js';
import { query } from '../src/db.js';
import { findUserById } from '../src/models/users.js';
import { loadAccess } from '../src/models/access.js';
// Loads a seeded user and their access, like loadUser does for a request.
export async function loadUserNamed(name) {
const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]);
const user = await findUserById(rows[0].id);
user.access = await loadAccess(user.id);
return user;
}
export function csrfTokenFrom(html) {
const match = html.match(/<meta name="csrf-token" content="([^"]+)">/);
if (!match) {
throw new Error('No CSRF token on the page');
}
return match[1];
}
// An agent that has visited the login page and sends its CSRF token on every request.
export async function anonymousAgent() {
const agent = request.agent(app);
const page = await agent.get('/login');
agent.set('X-CSRF-Token', csrfTokenFrom(page.text));
return agent;
}
// Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.
export async function loginAs(name, password = SEED_PASSWORD) {
const agent = await anonymousAgent();
const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password });
if (res.status !== 303) {
throw new Error(`Login as ${name} failed with status ${res.status}`);
}
// Login regenerated the session, so the token changed. Read the new one.
const home = await agent.get('/');
agent.set('X-CSRF-Token', csrfTokenFrom(home.text));
return agent;
}
export async function resetDatabase() {
if (!config.databaseUrl.endsWith('/caretaker_test')) {
throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`);
}
await migrate(config.databaseUrl, { log: () => {} });
const client = await pool.connect();
try {
await seed(client);
} finally {
client.release();
}
}
import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { config } from '../src/config.js';import { migrate } from '../src/migrate.js';import { seed, SEED_PASSWORD } from '../src/seed.js';import { query } from '../src/db.js';import { findUserById } from '../src/models/users.js';import { loadAccess } from '../src/models/access.js'; // Loads a seeded user and their access, like loadUser does for a request.export async function loadUserNamed(name) { const { rows } = await query('SELECT id FROM users WHERE email = $1', [`${name}@example.test`]); const user = await findUserById(rows[0].id); user.access = await loadAccess(user.id); return user;} export function csrfTokenFrom(html) { const match = html.match(/<meta name="csrf-token" content="([^"]+)">/); if (!match) { throw new Error('No CSRF token on the page'); } return match[1];} // An agent that has visited the login page and sends its CSRF token on every request.export async function anonymousAgent() { const agent = request.agent(app); const page = await agent.get('/login'); agent.set('X-CSRF-Token', csrfTokenFrom(page.text)); return agent;} // Returns a Supertest agent (it keeps cookies) that is logged in as e.g. 'alice'.export async function loginAs(name, password = SEED_PASSWORD) { const agent = await anonymousAgent(); const res = await agent.post('/login').type('form').send({ email: `${name}@example.test`, password }); if (res.status !== 303) { throw new Error(`Login as ${name} failed with status ${res.status}`); } // Login regenerated the session, so the token changed. Read the new one. const home = await agent.get('/'); agent.set('X-CSRF-Token', csrfTokenFrom(home.text)); return agent;} export async function resetDatabase() { if (!config.databaseUrl.endsWith('/caretaker_test')) { throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`); } await migrate(config.databaseUrl, { log: () => {} }); const client = await pool.connect(); try { await seed(client); } finally { client.release(); }}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/administer-building-data.cedar
src/authz/policies/administer-organisation.cedar
src/authz/policies/create-inspection.cedar
src/authz/policies/create-issue.cedar
src/authz/policies/delete-building.cedar
src/authz/policies/forbid-self-approval.cedar
src/authz/policies/own-inspections.cedar
src/authz/policies/update-building.cedar
src/authz/policies/update-own-issue.cedar
src/authz/policies/view-building-data.cedar
src/authz/policies/view-building.cedar
src/authz/policies/view-organisation.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