Checkpoint · Lesson 6.4
Cedar behind can(): the first route: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m06-l04 -- src.
Files changed in this lesson
src/authz/authorize.js added
src/authz/authorize.jsimport { config } from '../config.js';
import { buildAuthorizationCall } from './request.js';
import { evaluate } from './cedar.js';
// Builds the Cedar call for this user, action and database row, evaluates it, and logs.
export function authorize(user, action, row) {
const call = buildAuthorizationCall(user, action, row);
const result = evaluate(call);
const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`;
if (result.decision === 'failure' || result.errors.length > 0) {
console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors });
}
if (config.authzLog) {
console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`);
}
return result;
}
import { config } from '../config.js';import { buildAuthorizationCall } from './request.js';import { evaluate } from './cedar.js'; // Builds the Cedar call for this user, action and database row, evaluates it, and logs.export function authorize(user, action, row) { const call = buildAuthorizationCall(user, action, row); const result = evaluate(call); const resource = `${call.resource.type.replace('Caretaker::', '')}::${call.resource.id}`; if (result.decision === 'failure' || result.errors.length > 0) { console.error('authz problem', { user: user.id, action, resource, decision: result.decision, errors: result.errors }); } if (config.authzLog) { console.log(`authz user=${user.id} action=${action} resource=${resource} decision=${result.decision} reasons=${result.reasons.join(',') || '-'}`); } return result;}src/authz/cedar.js added
src/authz/cedar.jsimport * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { loadPolicyStore } from './policy-store.js';
// Loaded and validated once, the first time this module is imported.
// If the policy store is invalid, importing this module throws and the app does not start.
const { schema, policies } = loadPolicyStore();
const validation = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });
if (validation.type !== 'success' || validation.validationErrors.length > 0) {
const problems = validation.type === 'success'
? validation.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`)
: validation.errors.map((e) => e.message);
throw new Error(`The Cedar policy store is invalid:\n${problems.join('\n')}`);
}
export const policyIds = Object.keys(policies);
// Evaluates one call against the policy store.
// Fails closed: only a successful "allow" without evaluation errors is allowed.
export function evaluate(call) {
const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } });
if (answer.type === 'failure') {
return { allowed: false, decision: 'failure', reasons: [], errors: answer.errors.map((e) => e.message) };
}
const { decision, diagnostics } = answer.response;
const errors = diagnostics.errors.map((e) => `${e.policyId}: ${e.error.message}`);
return { allowed: decision === 'allow' && errors.length === 0, decision, reasons: diagnostics.reason, errors };
}
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { loadPolicyStore } from './policy-store.js'; // Loaded and validated once, the first time this module is imported.// If the policy store is invalid, importing this module throws and the app does not start.const { schema, policies } = loadPolicyStore();const validation = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });if (validation.type !== 'success' || validation.validationErrors.length > 0) { const problems = validation.type === 'success' ? validation.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`) : validation.errors.map((e) => e.message); throw new Error(`The Cedar policy store is invalid:\n${problems.join('\n')}`);} export const policyIds = Object.keys(policies); // Evaluates one call against the policy store.// Fails closed: only a successful "allow" without evaluation errors is allowed.export function evaluate(call) { const answer = cedar.isAuthorized({ ...call, schema, validateRequest: true, policies: { staticPolicies: policies } }); if (answer.type === 'failure') { return { allowed: false, decision: 'failure', reasons: [], errors: answer.errors.map((e) => e.message) }; } const { decision, diagnostics } = answer.response; const errors = diagnostics.errors.map((e) => `${e.policyId}: ${e.error.message}`); return { allowed: decision === 'allow' && errors.length === 0, decision, reasons: diagnostics.reason, errors };}src/authz/rules.js changed
src/authz/rules.js// Authorization rules. Every route asks can(user, action, resource).
// Actions are moving from JavaScript (Module 5) to Cedar policies (Module 6).
import { authorize } from './authorize.js';
const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin'];
// The roles a user effectively holds at one building: the roles assigned there,
// plus building_admin if they are org_admin of the organisation that owns the building.
export function rolesAtBuilding(user, buildingId, organisationId) {
const roles = new Set();
for (const assignment of user.access.assignments) {
if (assignment.building_id === buildingId) {
roles.add(assignment.role);
}
}
if (isOrgAdmin(user, organisationId)) {
roles.add('building_admin');
}
return roles;
}
function isMember(user, organisationId) {
return user.access.memberships.some((m) => m.organisation_id === organisationId);
}
function isOrgAdmin(user, organisationId) {
return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');
}
function hasAny(roles, wanted) {
return wanted.some((role) => roles.has(role));
}
export function can(user, action, resource) {
switch (action) {
// Organisations. resource: an organisation row { id, ... }
case 'ViewOrganisation':
return isMember(user, resource.id);
case 'UpdateOrganisation':
case 'DeleteOrganisation':
case 'CreateBuilding':
return isOrgAdmin(user, resource.id);
// Buildings. resource: a building row { id, organisation_id, ... }
case 'ViewBuilding':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateBuilding':
return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin');
case 'DeleteBuilding':
return isOrgAdmin(user, resource.organisation_id);
case 'CreateIssue':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']);
case 'CreateInspection':
return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']);
// Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... }
case 'ViewIssue':
return authorize(user, action, resource).allowed; // decided by Cedar
case 'UpdateIssue': {
const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);
if (roles.has('building_admin')) {
return true;
}
return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed';
}
case 'DeleteIssue':
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
// Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... }
case 'ViewInspection':
return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE);
case 'UpdateInspection':
case 'SubmitInspection': {
const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id);
if (roles.has('building_admin')) {
return true;
}
return roles.has('inspector') && resource.created_by === user.id;
}
case 'ApproveInspection':
// Separation of duties: nobody approves an inspection they created, whatever their role.
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin')
&& resource.created_by !== user.id;
case 'ReturnInspection':
return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin');
default:
// An action without a rule is a bug. Fail loudly rather than allow.
throw new Error(`No authorization rule for action ${action}`);
}
}
// Authorization rules. Every route asks can(user, action, resource).// Actions are moving from JavaScript (Module 5) to Cedar policies (Module 6).import { authorize } from './authorize.js'; const ANY_BUILDING_ROLE = ['viewer', 'reporter', 'inspector', 'building_admin']; // The roles a user effectively holds at one building: the roles assigned there,// plus building_admin if they are org_admin of the organisation that owns the building.export function rolesAtBuilding(user, buildingId, organisationId) { const roles = new Set(); for (const assignment of user.access.assignments) { if (assignment.building_id === buildingId) { roles.add(assignment.role); } } if (isOrgAdmin(user, organisationId)) { roles.add('building_admin'); } return roles;} function isMember(user, organisationId) { return user.access.memberships.some((m) => m.organisation_id === organisationId);} function isOrgAdmin(user, organisationId) { return user.access.memberships.some((m) => m.organisation_id === organisationId && m.role === 'org_admin');} function hasAny(roles, wanted) { return wanted.some((role) => roles.has(role));} export function can(user, action, resource) { switch (action) { // Organisations. resource: an organisation row { id, ... } case 'ViewOrganisation': return isMember(user, resource.id); case 'UpdateOrganisation': case 'DeleteOrganisation': case 'CreateBuilding': return isOrgAdmin(user, resource.id); // Buildings. resource: a building row { id, organisation_id, ... } case 'ViewBuilding': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateBuilding': return rolesAtBuilding(user, resource.id, resource.organisation_id).has('building_admin'); case 'DeleteBuilding': return isOrgAdmin(user, resource.organisation_id); case 'CreateIssue': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['reporter', 'building_admin']); case 'CreateInspection': return hasAny(rolesAtBuilding(user, resource.id, resource.organisation_id), ['inspector', 'building_admin']); // Issues. resource: an issue row { building_id, organisation_id, reported_by, status, ... } case 'ViewIssue': return authorize(user, action, resource).allowed; // decided by Cedar case 'UpdateIssue': { const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id); if (roles.has('building_admin')) { return true; } return roles.has('reporter') && resource.reported_by === user.id && resource.status !== 'closed'; } case 'DeleteIssue': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin'); // Inspections. resource: an inspection row { building_id, organisation_id, created_by, status, ... } case 'ViewInspection': return hasAny(rolesAtBuilding(user, resource.building_id, resource.organisation_id), ANY_BUILDING_ROLE); case 'UpdateInspection': case 'SubmitInspection': { const roles = rolesAtBuilding(user, resource.building_id, resource.organisation_id); if (roles.has('building_admin')) { return true; } return roles.has('inspector') && resource.created_by === user.id; } case 'ApproveInspection': // Separation of duties: nobody approves an inspection they created, whatever their role. return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin') && resource.created_by !== user.id; case 'ReturnInspection': return rolesAtBuilding(user, resource.building_id, resource.organisation_id).has('building_admin'); default: // An action without a rule is a bug. Fail loudly rather than allow. throw new Error(`No authorization rule for action ${action}`); }}src/config.js changed
src/config.jsfunction required(name) {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`);
}
return value;
}
export const config = {
port: Number(process.env.PORT ?? 3000),
databaseUrl: required('DATABASE_URL'),
logSql: process.env.LOG_SQL === '1',
authzLog: process.env.AUTHZ_LOG === '1',
env: process.env.NODE_ENV ?? 'development',
sessionSecret: required('SESSION_SECRET'),
// Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production).
cookieSecure: process.env.COOKIE_SECURE === '1',
loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),
};
function required(name) { const value = process.env[name]; if (!value) { throw new Error(`Missing required environment variable ${name}. Copy .env.example to .env.`); } return value;} export const config = { port: Number(process.env.PORT ?? 3000), databaseUrl: required('DATABASE_URL'), logSql: process.env.LOG_SQL === '1', authzLog: process.env.AUTHZ_LOG === '1', env: process.env.NODE_ENV ?? 'development', sessionSecret: required('SESSION_SECRET'), // Set COOKIE_SECURE=1 when the app is served over HTTPS (always, in production). cookieSecure: process.env.COOKIE_SECURE === '1', loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),};test/cedar-parity.test.js deleted
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-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/view-issue.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/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