Checkpoint · Lesson 6.2
A schema, and policies that are checked before they run: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m06-l02 -- src.
Files changed in this lesson
package.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"
},
"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" }, "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" }}scripts/validate-policies.js added
scripts/validate-policies.jsimport * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { loadPolicyStore } from '../src/authz/policy-store.js';
const { schema, policies } = loadPolicyStore();
const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });
if (result.type === 'failure') {
for (const error of result.errors) console.error(`could not parse: ${error.message}`);
process.exit(1);
}
for (const { policyId, error } of result.validationErrors) {
console.error(`${policyId}: ${error.message}${error.help ? ` (${error.help})` : ''}`);
}
for (const { policyId, error } of result.validationWarnings) {
console.warn(`warning in ${policyId}: ${error.message}`);
}
if (result.validationErrors.length > 0) {
process.exit(1);
}
console.log(`${Object.keys(policies).length} policies are valid against the schema`);
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { loadPolicyStore } from '../src/authz/policy-store.js'; const { schema, policies } = loadPolicyStore();const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } }); if (result.type === 'failure') { for (const error of result.errors) console.error(`could not parse: ${error.message}`); process.exit(1);}for (const { policyId, error } of result.validationErrors) { console.error(`${policyId}: ${error.message}${error.help ? ` (${error.help})` : ''}`);}for (const { policyId, error } of result.validationWarnings) { console.warn(`warning in ${policyId}: ${error.message}`);}if (result.validationErrors.length > 0) { process.exit(1);}console.log(`${Object.keys(policies).length} policies are valid against the schema`);src/authz/policies/view-issue.cedar added
src/authz/policies/view-issue.cedar// Users may view an issue at any building where they can view issues.
permit (
principal,
action == Caretaker::Action::"ViewIssue",
resource
)
when { principal.issueViewerBuildings.contains(resource.building) };
// Users may view an issue at any building where they can view issues.permit ( principal, action == Caretaker::Action::"ViewIssue", resource)when { principal.issueViewerBuildings.contains(resource.building) };src/authz/policy-store.js added
src/authz/policy-store.jsimport fs from 'node:fs';
import path from 'node:path';
const AUTHZ_DIR = import.meta.dirname;
// Reads the schema and every policies/*.cedar file. The policy id is the file name.
export function loadPolicyStore() {
const schema = fs.readFileSync(path.join(AUTHZ_DIR, 'schema.cedarschema'), 'utf8');
const policies = {};
const files = fs.readdirSync(path.join(AUTHZ_DIR, 'policies')).filter((f) => f.endsWith('.cedar')).sort();
for (const file of files) {
policies[path.basename(file, '.cedar')] = fs.readFileSync(path.join(AUTHZ_DIR, 'policies', file), 'utf8');
}
return { schema, policies };
}
import fs from 'node:fs';import path from 'node:path'; const AUTHZ_DIR = import.meta.dirname; // Reads the schema and every policies/*.cedar file. The policy id is the file name.export function loadPolicyStore() { const schema = fs.readFileSync(path.join(AUTHZ_DIR, 'schema.cedarschema'), 'utf8'); const policies = {}; const files = fs.readdirSync(path.join(AUTHZ_DIR, 'policies')).filter((f) => f.endsWith('.cedar')).sort(); for (const file of files) { policies[path.basename(file, '.cedar')] = fs.readFileSync(path.join(AUTHZ_DIR, 'policies', file), 'utf8'); } return { schema, policies };}src/authz/schema.cedarschema added
src/authz/schema.cedarschema// What Cedar may see in Caretaker, and in what shape.
namespace Caretaker {
entity Organisation;
entity Building in [Organisation] = {
organisation: Organisation,
};
entity User = {
issueViewerBuildings: Set<Building>,
};
entity Issue in [Building] = {
building: Building,
status: String,
priority: String,
reportedBy?: User,
};
action ViewIssue appliesTo {
principal: [User],
resource: [Issue],
};
}
// What Cedar may see in Caretaker, and in what shape.namespace Caretaker { entity Organisation; entity Building in [Organisation] = { organisation: Organisation, }; entity User = { issueViewerBuildings: Set<Building>, }; entity Issue in [Building] = { building: Building, status: String, priority: String, reportedBy?: User, }; action ViewIssue appliesTo { principal: [User], resource: [Issue], };}test/policies.test.js added
test/policies.test.jsimport { test } from 'node:test';
import assert from 'node:assert/strict';
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { loadPolicyStore } from '../src/authz/policy-store.js';
test('every policy is valid against the schema', () => {
const { schema, policies } = loadPolicyStore();
assert.ok(Object.keys(policies).length > 0, 'there are policies');
const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } });
assert.equal(result.type, 'success', JSON.stringify(result.errors));
assert.deepEqual(result.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`), []);
});
import { test } from 'node:test';import assert from 'node:assert/strict';import * as cedar from '@cedar-policy/cedar-wasm/nodejs';import { loadPolicyStore } from '../src/authz/policy-store.js'; test('every policy is valid against the schema', () => { const { schema, policies } = loadPolicyStore(); assert.ok(Object.keys(policies).length > 0, 'there are policies'); const result = cedar.validate({ schema, policies: { staticPolicies: policies }, validationSettings: { mode: 'strict' } }); assert.equal(result.type, 'success', JSON.stringify(result.errors)); assert.deepEqual(result.validationErrors.map((e) => `${e.policyId}: ${e.error.message}`), []);});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/cedar-hello.js
scripts/migrate.js
scripts/seed.js
scripts/validate-policies.js
src/app.js
src/authz/policies/view-issue.cedar
src/authz/policy-store.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