Module 6 · Introduce Cedar
6.1 The first Cedar decision
Check a package before you trust it, install the official Cedar WebAssembly engine, and make the smallest real authorization request, seeing every byte that goes in and comes out.
Starting point
All authorization runs through can(user, action, resource) in src/authz/rules.js, and test/access-matrix.test.js describes the required behaviour. 88 tests pass.
Outcome
scripts/cedar-hello.js (new: a standalone script, not part of the app yet)You have the Cedar engine installed and can explain the five inputs of a Cedar request (principal, action, resource, context, and entities), the policies it evaluates, and the exact shape of the answer.
The problem
Lesson 5.5 ended with a list of problems: rules buried in a switch, exceptions woven into each case, no way to check that a rule refers to real data, decisions without reasons. Cedar is an open-source policy language and evaluation engine, published under the Apache 2.0 licence, designed for exactly this: you write permissions as small declarative policies, and an engine evaluates them for each request. Cedar is used by AWS services, but the language and engine are independent of AWS and run entirely on your machine. The official documentation is at docs.cedarpolicy.com.
Two facts to fix in your mind before writing any Cedar:
- Cedar does not read your database. It evaluates a request against policies and a list of entities that your code builds and passes in. If the list is wrong, the decision is wrong.
- Cedar answers one question at a time: may this principal perform this action on this resource, in this context? It does not list "everything Alice can see". Module 8 deals with lists.
Build it
1. Check the package before you install it
Cedar's engine is written in Rust. The npm package @cedar-policy/cedar-wasm contains it compiled to WebAssembly, plus JavaScript bindings. Before adding any dependency, look at what you are about to install. npm view reads the registry without installing anything:
npm view @cedar-policy/cedar-wasm@4.14.1 dist.fileCount dist.unpackedSize
dist.fileCount = 2
dist.unpackedSize = 6138
npm view @cedar-policy/cedar-wasm@4.14.0 dist.fileCount dist.unpackedSize
dist.fileCount = 21
dist.unpackedSize = 13545292
Version 4.14.1 contains two files and about 6 kB: a README and a package.json, no engine. It is a broken publish. Version 4.14.0 contains 21 files and about 13.5 MB, including three builds of the engine. If we had typed npm install @cedar-policy/cedar-wasm@4.14.1, npm would have succeeded, and our first import would have failed. Checking takes seconds; pinning the version we checked makes the result repeatable.
2. Install it
npm install @cedar-policy/cedar-wasm@4.14.0
added 1 package, and audited 125 packages in 628ms
38 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
The package offers three builds: @cedar-policy/cedar-wasm (ES module, for bundlers), /web (browsers) and /nodejs (Node.js, which loads the .wasm file synchronously from disk). We use /nodejs. Ask the engine which versions it implements:
node --input-type=module -e "
import * as cedar from '@cedar-policy/cedar-wasm/nodejs';
console.log('SDK', cedar.getCedarSDKVersion(), '| language', cedar.getCedarLangVersion());
"
SDK 4.14.0 | language 4.6
3. The smallest real request
Create scripts/cedar-hello.js. Read the comments; every input is spelled out by hand so nothing is hidden:
// The smallest real Cedar decision. Usage: node scripts/cedar-hello.js [userId] [issueId]import * as cedar from '@cedar-policy/cedar-wasm/nodejs'; const [userId = '1', issueId = '101'] = process.argv.slice(2); // A reference to an entity: its type and its id. Ids are always strings.const ref = (type, id) => ({ type: `Caretaker::${type}`, id: String(id) }); // Policies: Cedar source text, keyed by an id that we choose.const policies = { 'view-issue': ` permit ( principal, action == Caretaker::Action::"ViewIssue", resource ) when { principal.issueViewerBuildings.contains(resource.building) }; `,}; // Entities: the facts Cedar may look at. Here they are typed by hand.// In the app they will be built from database rows.const entities = [ { uid: ref('User', 1), attrs: { issueViewerBuildings: [ref('Building', 10), ref('Building', 20)] }, parents: [] }, { uid: ref('User', 2), attrs: { issueViewerBuildings: [ref('Building', 30)] }, parents: [] }, { uid: ref('Issue', 101), attrs: { building: ref('Building', 10) }, parents: [] }, { uid: ref('Issue', 105), attrs: { building: ref('Building', 30) }, parents: [] },]; // The request: who, what, which, and any extra facts about this request.const call = { principal: ref('User', userId), action: { type: 'Caretaker::Action', id: 'ViewIssue' }, resource: ref('Issue', issueId), context: {}, policies: { staticPolicies: policies }, entities,}; const answer = cedar.isAuthorized(call); console.log('REQUEST', JSON.stringify({ principal: call.principal, action: call.action, resource: call.resource, context: call.context }));console.log('ANSWER ', JSON.stringify(answer, null, 2));Line by line:
ref(type, id)builds an entity reference:{ type: 'Caretaker::User', id: '1' }.Caretaker::is a namespace, so ourUsercannot collide with anyone else's. Entity IDs are strings in Cedar, even when the database uses integers.- The policy reads: permit any principal to perform
ViewIssueon any resource, when the principal'sissueViewerBuildingscontains the resource'sbuilding.permit (...)is the scope (who, what, which);when { ... }is a condition. entitiesis a plain array. Each entity has auid,attrs(its attributes), andparents(entities it belongs to; empty for now). An attribute whose value is{ type, id }is a reference to another entity.callhas the four parts of every request, plus the policies and entities to evaluate them with.isAuthorizedis synchronous and pure: same inputs, same answer. It does no I/O at all.
Run and inspect
node scripts/cedar-hello.js 1 101
REQUEST {"principal":{"type":"Caretaker::User","id":"1"},"action":{"type":"Caretaker::Action","id":"ViewIssue"},"resource":{"type":"Caretaker::Issue","id":"101"},"context":{}}
ANSWER {
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"view-issue"
],
"errors": []
}
},
"warnings": []
}
Read the answer:
"type": "success": the engine understood the input."decision": "allow"."reason": ["view-issue"]: the IDs of the policies that determined the decision. Here the one permit that matched."errors": []: no policy failed while being evaluated.
Cedar's rule for combining policies is short, and worth memorising (see Authorization in the documentation):
- If any
forbidpolicy matches, the decision is deny. - Otherwise, if any
permitpolicy matches, the decision is allow. - Otherwise the decision is deny: nothing permitted it. This is called implicit deny, and it means you never write "deny by default"; it is built in.
Now ask about issue 105, at building 30:
node scripts/cedar-hello.js 1 105
REQUEST {"principal":{"type":"Caretaker::User","id":"1"},"action":{"type":"Caretaker::Action","id":"ViewIssue"},"resource":{"type":"Caretaker::Issue","id":"105"},"context":{}}
ANSWER {
"type": "success",
"response": {
"decision": "deny",
"diagnostics": {
"reason": [],
"errors": []
}
},
"warnings": []
}
deny, with an empty reason. No policy permitted it and none forbade it: implicit deny. Bob, whose issueViewerBuildings contains building 30, gets the opposite answers:
node scripts/cedar-hello.js 2 105
REQUEST {"principal":{"type":"Caretaker::User","id":"2"},"action":{"type":"Caretaker::Action","id":"ViewIssue"},"resource":{"type":"Caretaker::Issue","id":"105"},"context":{}}
ANSWER {
"type": "success",
"response": {
"decision": "allow",
"diagnostics": {
"reason": [
"view-issue"
],
"errors": []
}
},
"warnings": []
}
Try the same request in the playground below. It runs the same engine, version 4.14.0, in your browser. Change Alice's issueViewerBuildings in the entities pane and evaluate again.
Experiment
The request names user 99, which is not in the entities list.
node scripts/cedar-hello.js 99 101
REQUEST {"principal":{"type":"Caretaker::User","id":"99"},"action":{"type":"Caretaker::Action","id":"ViewIssue"},"resource":{"type":"Caretaker::Issue","id":"101"},"context":{}}
ANSWER {
"type": "success",
"response": {
"decision": "deny",
"diagnostics": {
"reason": [],
"errors": [
{
"policyId": "view-issue",
"error": {
"message": "entity `Caretaker::User::\"99\"` does not exist",
"help": null,
"code": null,
"url": null,
"severity": null,
"sourceLocations": [
{
"label": null,
"start": 111,
"end": 120
}
],
"related": []
}
}
]
}
},
"warnings": []
}
Reveal What happened
"decision": "deny", and this time errors is not empty: the policy view-issue could not be evaluated because entity Caretaker::User::"99" does not exist, so Cedar could not read its issueViewerBuildings. A policy that hits an error while evaluating is skipped. With no permit left, the result is deny. That is safe for a permit. Lesson 6.6 shows why it is dangerous for a forbid, and how our app must treat errors.
Checkpoint
The app is unchanged; the tests still pass:
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) (492.391458ms)
✔ edit issue 101 (22.415416ms)
✔ view issue 103 (building 20) (17.370458ms)
✔ edit issue 103 (reported by dave) (18.349125ms)
✔ report an issue at building 20 (19.166167ms)
✔ view issue 105 (building 30) (14.5145ms)
✔ view issue 106 (building 40, reported by bob) (18.722167ms)
✔ approve inspection 201 (created by dave) (17.3115ms)
✔ approve inspection 202 (created by alice) (21.596209ms)
✔ update organisation 1 (16.161792ms)
✔ issues in each user's list come only from the expected buildings (94.580584ms)
✔ the scenario loads exactly as specified (240.856042ms)
✔ only one active assignment per user, building and role (0.922292ms)
✔ a revoked role can be granted again (1.490125ms)
✔ the My access page shows what the server loaded (76.072167ms)
✔ a correct login creates a session and shows the user (275.07725ms)
✔ a wrong password or unknown email gets the same 401 (54.018917ms)
✔ registration validates, creates a user, and logs them in (53.08425ms)
✔ registering an existing email is a field error (39.904083ms)
✔ logout destroys the session (47.112541ms)
✔ a building can be created inside an organisation (286.434834ms)
✔ a duplicate building name in the same organisation is a field error (4.4685ms)
✔ the same building name is allowed in another organisation (8.779125ms)
✔ a building with issues cannot be deleted (13.305333ms)
✔ an empty building can be deleted (9.346916ms)
✔ an organisation with buildings cannot be deleted, an empty one can (22.979583ms)
✔ a logged-in POST without a token is refused with 403 (284.869ms)
✔ a token from another session is refused (40.676584ms)
✔ the right token in the form field works (13.030083ms)
✔ every POST form on every page carries the token (52.823792ms)
✔ the dashboard counts match the database (280.488291ms)
✔ only the buildings carol can see appear (5.922083ms)
✔ create a draft, edit it, submit it, approve it (347.483583ms)
✔ invalid transitions are refused with 409 and change nothing (9.808792ms)
✔ only drafts can be edited (4.342333ms)
✔ returning a submitted inspection makes it editable again (6.699625ms)
Show 60 more lines
✔ concurrent approvals: exactly one wins (27.772583ms)
✔ unknown actions are 404 (3.657208ms)
✔ the issues list contains only issues from visible buildings (565.956084ms)
✔ a filter for another tenant's building returns nothing (3.962792ms)
✔ the inspections list is scoped too (11.683583ms)
✔ organisations are listed for their members only (9.186917ms)
✔ the dashboard counts only visible data (7.712334ms)
✔ view issue 101 (building 10) (494.456666ms)
✔ open the edit form for issue 101 (25.129875ms)
✔ open the edit form for issue 103 (reported by dave, building 20) (23.932417ms)
✔ view issue 105 (building 30) and 106 (building 40) (38.9595ms)
✔ report an issue at building 20 (20.812333ms)
✔ a reporter cannot edit their own issue once it is closed (7.909208ms)
✔ only building admins may delete; refusals change nothing (16.482ms)
✔ the edit form cannot move an issue to another building (4.814833ms)
✔ the list pages 10 at a time and reports the total (290.251958ms)
✔ pages do not overlap (17.044917ms)
✔ filters combine with AND (5.290625ms)
✔ sorting by priority puts critical first when descending (5.085292ms)
✔ unknown sort keys and SQL in the query string are ignored (33.394917ms)
✔ GET /issues lists issues from the database (265.899459ms)
✔ GET /issues/101 shows one issue with its building (5.53575ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (13.458875ms)
✔ POST /issues re-renders the form with errors (4.471792ms)
✔ POST /issues stores the issue and redirects to it (6.99ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (3.640292ms)
✔ the stored row has the cleaned values and ignores a client-sent status (4.078292ms)
✔ an issue time in the future is rejected (3.701541ms)
✔ GET /issues/101/edit shows the current values (3.910416ms)
✔ POST /issues/:id/edit changes the status and updated_at (3.833458ms)
✔ POST /issues/:id/delete removes the issue (8.08625ms)
✔ GET /organisations lists organisations with building counts (269.660416ms)
✔ GET /organisations/1 shows its buildings, not other organisations' buildings (5.424416ms)
✔ POST /organisations validates and creates (11.119667ms)
✔ POST /organisations/:id/edit renames the organisation (8.3295ms)
✔ unknown organisations are 404 (6.082375ms)
✔ failed logins are limited per client; the limit then blocks even correct passwords (351.061083ms)
✔ anonymous requests are redirected to the login page (218.718958ms)
✔ anonymous writes are refused and change nothing (10.921584ms)
✔ login and register pages stay public (6.114459ms)
✔ login issues a new session id (no session fixation) (31.758625ms)
✔ returnTo only follows local paths (27.681ms)
✔ new issues and transitions record the logged-in user (75.741667ms)
✔ the session cookie has the attributes we chose (25.726959ms)
✔ organisation 1: view and update (468.830042ms)
✔ ravi is still a member of organisation 2 but can see none of its buildings (7.341333ms)
✔ building 10: view, update, delete (52.257667ms)
✔ creating buildings needs org_admin (15.439708ms)
✔ creating an organisation makes the creator its admin (8.948ms)
✔ inspections: view 201, open the edit form for draft 203 (35.046292ms)
✔ approve inspection 201 (dave's): only building admins (15.998083ms)
✔ creating an inspection needs inspector or building_admin at the chosen building (10.253875ms)
ℹ tests 88
ℹ suites 0
ℹ pass 88
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8745.583458
git add -A
git commit -m "First Cedar decision"
[main 948610a] First Cedar decision
3 files changed, 51 insertions(+)
create mode 100644 scripts/cedar-hello.js
Symptom Cannot find module '@cedar-policy/cedar-wasm/nodejs'
The package is missing or broken. Run ls node_modules/@cedar-policy/cedar-wasm; you should see esm, nodejs and web folders. If you see only README.md and package.json, you installed 4.14.1. Install 4.14.0 exactly.
Symptom "type": "failure" with failed to parse policies
The policy text has a syntax error. The message includes sourceLocations with character offsets into the policy.
Recap and next step
Cedar takes a request (principal, action, resource, context), a set of policies, and a set of entities with attributes and parents. It returns allow or deny, the IDs of the policies that decided, and any evaluation errors. It reads nothing else. Without a matching permit the answer is deny.
Our policy referred to issueViewerBuildings and building, and Cedar simply trusted that those attributes existed. Next we give Cedar a schema, so that a typo in a policy is caught before it ever runs.
Open the checkpoint files for lesson 6.1 (separate page; only files from this lesson and earlier)