Caretaker Express · PostgreSQL · Cedar

Module 9 · Trust boundaries and architecture

9.3 Defence in depth, stale data and races

See what PostgreSQL itself can refuse (least-privilege roles, an append-only log, row-level security), why Cedar cannot do this, and how stale data, caches and races affect any authorization design.

≈ 25 min 7 steps 45 lines of code Replay verified

Starting point

The app authorizes every action with Cedar. It connects to PostgreSQL as caretaker, the user created by the Docker image, which owns every table and can do anything.

Outcome

No application code changes in this lesson. In psql, inside transactions that roll back, you will:

  • create a least-privilege role and watch PostgreSQL refuse an UPDATE of the audit log and a DROP TABLE;
  • enable row-level security on issues and watch the database itself return only a tenant's rows;
  • understand where stale data and races can make a correct policy give a wrong answer, and how Caretaker's design limits them.

The problem

Lesson 9.2 ended with an uncomfortable fact: a compromised web process holds the database password. Cedar runs inside that process and is only asked when the process chooses to ask. Cedar does not control access to the database. If we want a limit that survives a compromised application, it must be enforced by something the application cannot bypass, and for data, that is the database.

Build it

1. Least privilege: an app role that cannot change history

Run this in psql. It is wrapped in BEGIN and ends with a statement that must fail, so nothing is kept:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
BEGIN;CREATE ROLE caretaker_app NOLOGIN;GRANT SELECT, INSERT, UPDATE, DELETE  ON organisations, buildings, users, memberships, building_role_assignments,     issues, inspections, inspection_status_changes, session  TO caretaker_app;-- The audit log: read and append only.GRANT SELECT, INSERT ON permission_changes TO caretaker_app;GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO caretaker_app; SET ROLE caretaker_app;SELECT current_user;INSERT INTO permission_changes (actor_id, target_user_id, organisation_id, change, role)VALUES (1, 4, 1, 'grant_role', 'viewer') RETURNING id;UPDATE permission_changes SET role = 'building_admin';
BEGIN
CREATE ROLE
GRANT
GRANT
GRANT
SET
 current_user  
---------------
 caretaker_app
(1 row)

 id 
----
  1
(1 row)

INSERT 0 1
ERROR:  permission denied for table permission_changes

SET ROLE makes the rest of the session run with that role's privileges. The insert works; the update is refused with permission denied. If the app connected as caretaker_app, a compromised process could still append false log entries, but it could not rewrite or delete the history of who granted what. Try schema changes too:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
BEGIN;CREATE ROLE caretaker_app NOLOGIN;GRANT SELECT, INSERT, UPDATE, DELETE ON issues TO caretaker_app;SET ROLE caretaker_app;DROP TABLE issues;
BEGIN
CREATE ROLE
GRANT
SET
ERROR:  must be owner of table issues

Only the owner can drop or alter a table. This is why production systems use separate database users: a migration user that owns the schema, and an application user with only the privileges the app needs.

2. Row-level security: the database filters by tenant

PostgreSQL can attach a policy to a table: a condition every row must meet before the current role may see it. This demonstration copies our visibleBuildingCondition into such a policy. The user ID comes from a setting, app.user_id, that an application would set at the start of each transaction:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
BEGIN;CREATE ROLE caretaker_rls NOLOGIN;GRANT SELECT ON issues, buildings, building_role_assignments, memberships TO caretaker_rls;ALTER TABLE issues ENABLE ROW LEVEL SECURITY;CREATE POLICY tenant_isolation ON issues FOR SELECT TO caretaker_rlsUSING (  building_id IN (SELECT building_id FROM building_role_assignments              WHERE user_id = current_setting('app.user_id')::int AND revoked_at IS NULL)  OR building_id IN (SELECT s.id FROM buildings s JOIN memberships m ON m.organisation_id = s.organisation_id                 WHERE m.user_id = current_setting('app.user_id')::int AND m.role = 'org_admin')); SET ROLE caretaker_rls;SET app.user_id = '2';SELECT count(*) AS rows_for_bob FROM issues;SET app.user_id = '3';SELECT count(*) AS rows_for_carol FROM issues;SET app.user_id = '5';SELECT count(*) AS rows_for_nora FROM issues; RESET ROLE;SELECT count(*) AS rows_for_the_owner FROM issues;ROLLBACK;
BEGIN
CREATE ROLE
GRANT
ALTER TABLE
CREATE POLICY
SET
SET
 rows_for_bob 
--------------
            1
(1 row)

SET
 rows_for_carol 
----------------
             28
(1 row)

SET
 rows_for_nora 
---------------
             0
(1 row)

RESET
 rows_for_the_owner 
--------------------
                 30
(1 row)

ROLLBACK

Bob sees 1 row, Carol 28, Nora 0: the database applied the tenant rule to a plain SELECT count(*) that has no WHERE clause at all. The last count shows the catch: RESET ROLE returns to caretaker, which owns the table, and owners (and superusers) bypass row-level security. The ROLLBACK removed the role, the policy and the setting.

What it would take to use this in the app, and why this course stops at the demonstration:

  • The app must connect as a non-owner role, and set app.user_id inside every transaction, on the connection that runs the queries (SET LOCAL), or a pooled connection could carry the previous user's ID.
  • Every list query would then be filtered twice (our SQL and the RLS policy): a third copy of the visibility rule to keep aligned.
  • In return, a forgotten WHERE clause, or an SQL injection, can no longer read another tenant's rows.

That trade-off is often worth it in production. It is a database feature, not a Cedar feature, and it complements Cedar rather than replacing it: Cedar decides actions with rich rules; RLS puts a hard floor under data access.

3. Time: stale data, caches and races

A policy can be right and the decision still wrong if the facts are out of date. Three situations, and where Caretaker stands:

Situation Risk Caretaker
Caching a user's access between requests A revoked role keeps working until the cache expires No cache: loadAccess runs on every request (lesson 7.4 proved next-request revocation). The price is two small queries per request. A cache would need explicit invalidation on every grant, revoke and membership change.
Time between the decision and the action A role revoked, or a record moved, after the check but before the write Writes are conditional where it matters: transitionInspection ... WHERE status = $expected, moveIssue ... WHERE building_id = $from, revokeBuildingRole ... WHERE revoked_at IS NULL. A request that checked stale state changes nothing.
Long-lived sessions A user's password changes, but old sessions stay valid Not handled: the session lasts up to 8 hours. A production system should delete a user's other sessions on password change and on account removal.

The general rule: authorize as close to the action as possible, with facts read at the time of the action, and make the action itself conditional on the facts you checked.

Run and inspect

Nothing was kept from the psql blocks. Confirm it:

In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT rolname FROM pg_roles WHERE rolname LIKE 'caretaker_%';
 rolname 
---------
(0 rows)
In psqldatabase caretaker
Open psql with docker compose exec db psql -U caretaker caretaker, then paste the SQL.
SELECT relrowsecurity FROM pg_class WHERE relname = 'issues';
 relrowsecurity 
----------------
 f
(1 row)

No extra roles, and row-level security is off again.

Experiment

Predict In the RLS demonstration, which policy-like statement in Caretaker is the database copy of, and what would you add to the list-parity test if you enabled RLS in the app?
Reveal Answer

It is a copy of visibleBuildingCondition (lesson 5.3), which itself mirrors the building-read Cedar policy. If RLS were enabled, the list-parity test from lesson 8.1 should also run the list query as the restricted role with app.user_id set, and compare. Three implementations of one rule need one test that checks all three.

Checkpoint

No application code changed, so the suite is unchanged:

Run and comparecaretaker/
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) (5580.59725ms)
✔ edit issue 101 (25.379541ms)
✔ view issue 103 (building 20) (24.402583ms)
✔ edit issue 103 (reported by dave) (21.635ms)
✔ report an issue at building 20 (26.364ms)
✔ view issue 105 (building 30) (19.217ms)
✔ view issue 106 (building 40, reported by bob) (16.526125ms)
✔ approve inspection 201 (created by dave) (18.191125ms)
✔ approve inspection 202 (created by alice) (19.454917ms)
✔ update organisation 1 (21.591416ms)
✔ change own role at building 10 (4.518875ms)
✔ grant building_admin at building 10 to dave (26.596709ms)
✔ grant viewer at building 10 to dave (21.356291ms)
✔ issues in each user's list come only from the expected buildings (127.81325ms)
✔ the scenario loads exactly as specified (208.139917ms)
✔ only one active assignment per user, building and role (0.918625ms)
✔ a revoked role can be granted again (1.322959ms)
✔ the My access page shows what the server loaded (70.589625ms)
✔ a correct login creates a session and shows the user (266.869291ms)
✔ a wrong password or unknown email gets the same 401 (51.324334ms)
✔ registration validates, creates a user, and logs them in (36.100333ms)
✔ registering an existing email is a field error (26.036875ms)
✔ logout destroys the session (40.539708ms)
✔ allow: a permit matched and nothing forbade it (212.952083ms)
✔ explicit deny: a forbid overrides a matching permit (2.703958ms)
✔ implicit deny: no permit matched (2.573834ms)
authz problem {
  user: 1,
  action: 'ApproveInspection',
  resource: 'Inspection::201',
  decision: 'failure',
  errors: [
    'entity does not conform to the schema: in attribute `status` on `Caretaker::Inspection::"201"`, type mismatch: value was expected to have type string, but it actually has type long: `7`'
  ]
}
✔ failure: a row that does not fit the schema is never allowed (3.281916ms)
Show 109 more lines✔ unknown actions throw instead of deciding (1.42575ms) ✔ unknown callers are refused (204.797166ms) ✔ decisions match the app (26.932083ms) ✔ attributes sent by the caller are ignored (8.124875ms) ✔ context is validated and used (9.3615ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (397.140834ms) ✔ a revoked assignment cannot be revoked again (7.07825ms) ✔ an assignment id from another building is not found here (4.388458ms) ✔ alice cannot revoke her own building_admin role; carol can (12.421ms) ✔ grants are limited to members of the building's organisation (6.339542ms) ✔ a building can be created inside an organisation (303.566208ms) ✔ a duplicate building name in the same organisation is a field error (6.21725ms) ✔ the same building name is allowed in another organisation (10.139042ms) ✔ a building with issues cannot be deleted (14.408667ms) ✔ an empty building can be deleted (10.679708ms) ✔ an organisation with buildings cannot be deleted, an empty one can (23.608708ms) ✔ a logged-in POST without a token is refused with 403 (256.25725ms) ✔ a token from another session is refused (35.698583ms) ✔ the right token in the form field works (18.997416ms) ✔ every POST form on every page carries the token (59.07175ms) ✔ the dashboard counts match the database (291.340875ms) ✔ only the buildings carol can see appear (5.177167ms) ✔ headers that claim another identity are ignored (283.661708ms) ✔ query strings and form fields that claim roles are ignored (10.73825ms) ✔ a forged reporter or status in an edit form does not reach the database (5.851791ms) ✔ a forged grant context cannot make dave a building admin (4.898459ms) ✔ create a draft, edit it, submit it, approve it (340.93725ms) ✔ invalid transitions are refused with 409 and change nothing (11.972541ms) ✔ only drafts can be edited (5.375708ms) ✔ returning a submitted inspection makes it editable again (8.694917ms) ✔ concurrent approvals: exactly one wins (25.079375ms) ✔ unknown actions are 404 (3.034792ms) ✔ the issues list contains only issues from visible buildings (590.256542ms) ✔ a filter for another tenant's building returns nothing (3.692833ms) ✔ the inspections list is scoped too (9.886917ms) ✔ organisations are listed for their members only (7.936375ms) ✔ the dashboard counts only visible data (7.4415ms) ✔ view issue 101 (building 10) (481.981125ms) ✔ open the edit form for issue 101 (26.655ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (25.304291ms) ✔ view issue 105 (building 30) and 106 (building 40) (39.515666ms) ✔ report an issue at building 20 (25.34975ms) ✔ a reporter cannot edit their own issue once it is closed (8.441958ms) ✔ only building admins may delete; refusals change nothing (17.555625ms) ✔ the edit form cannot move an issue to another building (3.961708ms) ✔ the list pages 10 at a time and reports the total (296.45675ms) ✔ pages do not overlap (23.573875ms) ✔ filters combine with AND (7.318708ms) ✔ sorting by priority puts critical first when descending (7.752208ms) ✔ unknown sort keys and SQL in the query string are ignored (40.070375ms) ✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (347.414958ms) ✔ dave may update his own issue 103 but is not a reporter at building 10 (6.758417ms) ✔ dave cannot move issue 101: he may not update it where it is (4.87925ms) ✔ carol moves 101 to building 20, but never to another organisation (10.19775ms) ✔ a forged building id on create is refused and creates nothing (21.994208ms) ✔ GET /issues lists issues from the database (269.898125ms) ✔ GET /issues/101 shows one issue with its building (7.279375ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.625125ms) ✔ POST /issues re-renders the form with errors (5.369708ms) ✔ POST /issues stores the issue and redirects to it (8.232875ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.5095ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.8375ms) ✔ an issue time in the future is rejected (4.04975ms) ✔ GET /issues/101/edit shows the current values (4.834625ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.307791ms) ✔ POST /issues/:id/delete removes the issue (10.860667ms) ✔ the issues list contains exactly the issues Cedar lets each user view (331.594958ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (20.163ms) ✔ only organisation admins can open the members page (428.284708ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (17.658292ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.509875ms) ✔ nobody changes their own membership (4.004667ms) ✔ unknown emails and roles are form errors (11.293792ms) ✔ a member cannot add members, even with a well-formed request (3.342541ms) ✔ GET /organisations lists organisations with building counts (273.79125ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (13.544542ms) ✔ POST /organisations validates and creates (15.184833ms) ✔ POST /organisations/:id/edit renames the organisation (10.860375ms) ✔ unknown organisations are 404 (6.417583ms) ✔ every policy is valid against the schema (32.215042ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.291333ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (349.485791ms) ✔ anonymous requests are redirected to the login page (199.0165ms) ✔ anonymous writes are refused and change nothing (10.322417ms) ✔ login and register pages stay public (5.499667ms) ✔ login issues a new session id (no session fixation) (31.705541ms) ✔ returnTo only follows local paths (27.92275ms) ✔ new issues and transitions record the logged-in user (87.839ms) ✔ the session cookie has the attributes we chose (26.110083ms) ✔ organisation 1: view and update (503.565625ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.9215ms) ✔ building 10: view, update, delete (60.005417ms) ✔ creating buildings needs org_admin (15.061458ms) ✔ creating an organisation makes the creator its admin (10.227334ms) ✔ inspections: view 201, open the edit form for draft 203 (41.233417ms) ✔ approve inspection 201 (dave's): only building admins (17.071667ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (16.786041ms) ✔ bob gets 404 for every Liffey route, and nothing changes (444.318792ms) ✔ ravi gets 404 for every Liffey route, and nothing changes (103.392333ms) ✔ nora gets 404 for every Liffey route, and nothing changes (86.480583ms) ✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (58.798667ms) ℹ tests 128 ℹ suites 0 ℹ pass 128 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 19325.214125

There is nothing to commit; git status should be clean:

Run and comparecaretaker/
git status
On branch main
nothing to commit, working tree clean
Symptom role "caretaker_app" already exists

A previous attempt was committed instead of rolled back. Drop it: DROP ROLE caretaker_app; (as caretaker).

Recap and next step

Cedar decides; it does not touch the database. Defences that survive a compromised application live in PostgreSQL: least-privilege roles (no schema changes, an append-only log) and row-level security (tenant filtering below every query). Time matters as much as rules: Caretaker reloads facts per request and makes critical writes conditional on what it checked, and still has known gaps such as long sessions after a password change.

Module 10 puts everything together: hardening and logging, the complete test matrix, a run from a clean checkout, and a capstone feature for you to build.