Module 6 · Introduce Cedar
6.2 A schema, and policies that are checked before they run
Describe Caretaker's entities and actions in a Cedar schema, keep one policy per file, and validate every policy against the schema in a script and a test.
Starting point
scripts/cedar-hello.js evaluates one hand-written policy against hand-written entities. Nothing checks that the policy refers to attributes that exist.
Outcome
src/authz/├── schema.cedarschema (new: entity types, attributes, actions)├── policies/│ └── view-issue.cedar (new: one policy per file; file name = policy id)├── policy-store.js (new: loads the schema and policies)└── rules.jsscripts/validate-policies.js (new: npm run authz:validate)test/policies.test.js (new)A misspelt attribute, a type mismatch, or an action applied to the wrong kind of resource is reported before the application runs.
The problem
Change one letter in the hello policy, so that it reads principal.issueViewrBuildings, and evaluate it:
node --input-type=module -e "
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
const ref = (type, id) => ({ type: 'Caretaker::' + type, id: String(id) });
const answer = cedar.isAuthorized({
principal: ref('User', 1), action: { type: 'Caretaker::Action', id: 'ViewIssue' }, resource: ref('Issue', 101), context: {},
policies: { staticPolicies: { 'view-issue': 'permit (principal, action == Caretaker::Action::\"ViewIssue\", resource) when { principal.issueViewrBuildings.contains(resource.building) };' } },
entities: [
{ uid: ref('User', 1), attrs: { issueViewerBuildings: [ref('Building', 10)] }, parents: [] },
{ uid: ref('Issue', 101), attrs: { building: ref('Building', 10) }, parents: [] },
],
});
console.log(answer.response.decision, JSON.stringify(answer.response.diagnostics.errors[0].error.message));
"
deny "`Caretaker::User::\"1\"` does not have the attribute `issueViewrBuildings`"
The answer is deny, with an evaluation error that nobody would see unless they looked. Deployed, this typo would silently lock every user out of every issue. Worse mistakes are possible: a condition that compares a building with a status string is always false, and also only fails at runtime.
Cedar's answer is a schema: a declaration of every entity type, its attributes and their types, and which actions apply to which principals and resources. With a schema, Cedar can validate policies statically, before any request, and reject the ones that could never evaluate correctly. See Schema and Policy validation in the Cedar documentation.
Build it
1. The schema
Create src/authz/schema.cedarschema. This first version describes only what ViewIssue needs; the schema grows with the policies:
// 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], };}Read it as a contract between our code and our policies:
namespace Caretaker { ... }puts every type underCaretaker::, as in our entity references.entity Building in [Organisation]says that a building may have organisations as parents.Issue in [Building]says the same for issues and buildings. Parents describe membership in a hierarchy; we start using them in Module 7.- Attributes have types.
building: Buildingis a reference to aBuildingentity.Set<Building>is a set of such references.Stringis text.reportedBy?: Useris optional (the?): some issues have no known reporter, and a policy must check withhasbefore reading it. action ViewIssue appliesTosaysViewIssuetakes aUseras principal and anIssueas resource. A request to view aBuildingis now an error, not a deny.
2. One policy per file
// 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) };We keep each policy in its own file and use the file name as the policy ID. Lesson 6.1 showed that the response lists the IDs of the policies that decided; with one file per policy, a decision reason such as view-issue points to exactly one file. (Cedar can also read many policies from one string, but then it numbers them policy0, policy1, and an @id annotation does not change those numbers in this API.)
3. Load the policy store
Create src/authz/policy-store.js:
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 };}The schema and the policies are the policy store: the rules, kept in files in the repository, reviewed and versioned like code. They are not data in the database.
4. A validation command
Create scripts/validate-policies.js:
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`);result.type === 'failure'means Cedar could not even parse the schema or a policy.validationErrorsare policies that parse but do not type-check against the schema.mode: 'strict'is Cedar's standard validation mode.
npm pkg set scripts.authz:validate="node scripts/validate-policies.js"
5. A test, so it can never be forgotten
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}`), []);});Run and inspect
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
1 policies are valid against the schema
Now break the policy on purpose, the same way as at the start of the lesson:
when { principal.issueViewerBuildings.contains(resource.building) };when { principal.issueViewrBuildings.contains(resource.building) };
Show the whole src/authz/policies/view-issue.cedar after this change
// Users may view an issue at any building where they can view issues.permit ( principal, action == Caretaker::Action::"ViewIssue", resource)when { principal.issueViewrBuildings.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.issueViewrBuildings.contains(resource.building) };
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
view-issue: for policy `view-issue`, attribute `issueViewrBuildings` on entity type `Caretaker::User` not found (did you mean `issueViewerBuildings`?)
The validator found the typo without any request, and suggested the fix. Restore the policy:
when { principal.issueViewrBuildings.contains(resource.building) };when { principal.issueViewerBuildings.contains(resource.building) };
Show the whole src/authz/policies/view-issue.cedar after this change
// 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) };
The schema also checks requests and entity data, when you pass it to isAuthorized with validateRequest: true. Two mistakes our code could make, caught before evaluation:
node --input-type=module -e "
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
import { loadPolicyStore } from './src/authz/policy-store.js';
const { schema, policies } = loadPolicyStore();
const ref = (type, id) => ({ type: 'Caretaker::' + type, id: String(id) });
const base = { action: { type: 'Caretaker::Action', id: 'ViewIssue' }, context: {}, schema, validateRequest: true, policies: { staticPolicies: policies } };
const wrongType = cedar.isAuthorized({ ...base, principal: ref('User', 1), resource: ref('Building', 10), entities: [] });
console.log('wrong resource type:', wrongType.type, '-', wrongType.errors[0].message);
const badAttr = cedar.isAuthorized({ ...base, principal: ref('User', 1), resource: ref('Issue', 101), entities: [
{ uid: ref('User', 1), attrs: { issueViewerBuildings: ['10'] }, parents: [] },
] });
console.log('building id as plain string:', badAttr.type, '-', badAttr.errors[0].message);
"
wrong resource type: failure - resource type `Caretaker::Building` is not valid for `Caretaker::Action::"ViewIssue"`
building id as plain string: failure - error during entity deserialization: in attribute `issueViewerBuildings` on `Caretaker::User::"1"`, expected a literal entity reference, but got `"10"`
Both are "type": "failure", not deny. Cedar refused to evaluate, because the input does not match the schema. In the second case the attribute holds the string "10" instead of a reference to Building::"10"; without a schema, Cedar would have accepted it and the comparison would simply never match.
Experiment
principal.issueViewerBuildings.contains(resource.status). The attribute names are all correct. Will validation pass?when { principal.issueViewerBuildings.contains(resource.building) };when { principal.issueViewerBuildings.contains(resource.status) };
Show the whole src/authz/policies/view-issue.cedar after this change
// 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.status) };// 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.status) };
npm run authz:validate
> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js
view-issue: the types String and Caretaker::Building are not compatible (for policy `view-issue`, elements of the first operand and the second operand to a `contains` expression must have compatible types. Types must be exactly equal to be compatible)
Reveal Answer
No. issueViewerBuildings is a Set<Building>, and status is a String; a set of buildings can never contain a string. The validator reports incompatible types. Without the schema this policy would quietly deny every request forever.
when { principal.issueViewerBuildings.contains(resource.status) };when { principal.issueViewerBuildings.contains(resource.building) };
Show the whole src/authz/policies/view-issue.cedar after this change
// 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) };
Checkpoint
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) (5520.871625ms)
✔ edit issue 101 (24.170709ms)
✔ view issue 103 (building 20) (18.002875ms)
✔ edit issue 103 (reported by dave) (21.13725ms)
✔ report an issue at building 20 (21.16175ms)
✔ view issue 105 (building 30) (15.689583ms)
✔ view issue 106 (building 40, reported by bob) (18.456334ms)
✔ approve inspection 201 (created by dave) (18.313625ms)
✔ approve inspection 202 (created by alice) (26.584459ms)
✔ update organisation 1 (19.18875ms)
✔ issues in each user's list come only from the expected buildings (99.16425ms)
✔ the scenario loads exactly as specified (213.746666ms)
✔ only one active assignment per user, building and role (0.847833ms)
✔ a revoked role can be granted again (1.214959ms)
✔ the My access page shows what the server loaded (77.835666ms)
✔ a correct login creates a session and shows the user (264.662459ms)
✔ a wrong password or unknown email gets the same 401 (53.27ms)
✔ registration validates, creates a user, and logs them in (43.682625ms)
✔ registering an existing email is a field error (29.29025ms)
✔ logout destroys the session (50.155333ms)
✔ a building can be created inside an organisation (282.173792ms)
✔ a duplicate building name in the same organisation is a field error (4.79625ms)
✔ the same building name is allowed in another organisation (9.563875ms)
✔ a building with issues cannot be deleted (11.456ms)
✔ an empty building can be deleted (8.741ms)
✔ an organisation with buildings cannot be deleted, an empty one can (21.504459ms)
✔ a logged-in POST without a token is refused with 403 (261.990041ms)
✔ a token from another session is refused (37.402208ms)
✔ the right token in the form field works (9.121875ms)
✔ every POST form on every page carries the token (39.684792ms)
✔ the dashboard counts match the database (269.933958ms)
✔ only the buildings carol can see appear (6.296333ms)
✔ create a draft, edit it, submit it, approve it (329.157ms)
✔ invalid transitions are refused with 409 and change nothing (9.188333ms)
✔ only drafts can be edited (4.247791ms)
✔ returning a submitted inspection makes it editable again (6.4775ms)
Show 61 more lines
✔ concurrent approvals: exactly one wins (24.427708ms)
✔ unknown actions are 404 (3.139291ms)
✔ the issues list contains only issues from visible buildings (534.616875ms)
✔ a filter for another tenant's building returns nothing (4.085959ms)
✔ the inspections list is scoped too (11.540916ms)
✔ organisations are listed for their members only (11.184708ms)
✔ the dashboard counts only visible data (8.727125ms)
✔ view issue 101 (building 10) (467.588375ms)
✔ open the edit form for issue 101 (22.291541ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (25.022167ms)
✔ view issue 105 (building 30) and 106 (building 40) (35.713792ms)
✔ report an issue at building 20 (20.471542ms)
✔ a reporter cannot edit their own issue once it is closed (6.609792ms)
✔ only building admins may delete; refusals change nothing (13.580583ms)
✔ the edit form cannot move an issue to another building (3.389375ms)
✔ the list pages 10 at a time and reports the total (334.379833ms)
✔ pages do not overlap (24.261417ms)
✔ filters combine with AND (6.988958ms)
✔ sorting by priority puts critical first when descending (6.6295ms)
✔ unknown sort keys and SQL in the query string are ignored (35.7135ms)
✔ GET /issues lists issues from the database (263.147375ms)
✔ GET /issues/101 shows one issue with its building (7.92225ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (14.669791ms)
✔ POST /issues re-renders the form with errors (4.677583ms)
✔ POST /issues stores the issue and redirects to it (8.222125ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (4.455708ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.483084ms)
✔ an issue time in the future is rejected (4.329792ms)
✔ GET /issues/101/edit shows the current values (4.280667ms)
✔ POST /issues/:id/edit changes the status and updated_at (4.172ms)
✔ POST /issues/:id/delete removes the issue (9.189875ms)
✔ GET /organisations lists organisations with building counts (273.328875ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (4.900833ms)
✔ POST /organisations validates and creates (11.242541ms)
✔ POST /organisations/:id/edit renames the organisation (8.560917ms)
✔ unknown organisations are 404 (6.138667ms)
✔ every policy is valid against the schema (25.66475ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (340.831ms)
✔ anonymous requests are redirected to the login page (207.211708ms)
✔ anonymous writes are refused and change nothing (10.597583ms)
✔ login and register pages stay public (5.751167ms)
✔ login issues a new session id (no session fixation) (31.867333ms)
✔ returnTo only follows local paths (27.750833ms)
✔ new issues and transitions record the logged-in user (75.843ms)
✔ the session cookie has the attributes we chose (29.418792ms)
✔ organisation 1: view and update (485.123ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (6.068959ms)
✔ building 10: view, update, delete (45.397875ms)
✔ creating buildings needs org_admin (17.783ms)
✔ creating an organisation makes the creator its admin (8.391125ms)
✔ inspections: view 201, open the edit form for draft 203 (40.554834ms)
✔ approve inspection 201 (dave's): only building admins (15.074042ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (9.774458ms)
ℹ tests 89
ℹ suites 0
ℹ pass 89
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 13665.394333
git add -A
git commit -m "Cedar schema and policy validation"
[main 13f647d] Cedar schema and policy validation
6 files changed, 80 insertions(+), 1 deletion(-)
create mode 100644 scripts/validate-policies.js
create mode 100644 src/authz/policies/view-issue.cedar
create mode 100644 src/authz/policy-store.js
create mode 100644 src/authz/schema.cedarschema
create mode 100644 test/policies.test.js
Symptom could not parse: ... unexpected token
Check the punctuation in the schema: attributes are separated by commas, entity declarations end with ;, and each appliesTo block ends with };.
Symptom ENOENT: no such file or directory, scandir '.../src/authz/policies'
The policies folder must be inside src/authz, next to schema.cedarschema.
Recap and next step
The schema declares entity types, attributes with types, parent relationships and which actions apply to which entities. Policies live one per file, named by their ID, and are validated against the schema by a script and a test. Three kinds of problem now have three different symptoms: a validation error (caught before running), a request or entity failure (refused at evaluation time), and an evaluation error (a policy skipped, so usually a deny).
Our entities are still typed by hand. Next we build them from the database rows that our app already loads, and trace exactly where every attribute comes from.
Open the checkpoint files for lesson 6.2 (separate page; only files from this lesson and earlier)