Caretaker Express · PostgreSQL · Cedar

Module 10 · Complete, test and operate the application

10.1 Hardening, logging and configuration

Remove the framework banner, add security headers and request IDs, keep decision logs useful and safe, refuse unsafe production settings at startup, and add a guarded reset command.

≈ 45 min 19 steps 99 lines of code Replay verified

Starting point

All features exist and 128 tests pass. Responses still say X-Powered-By: Express (lesson 1.1 promised to remove it), error pages give no way to find the matching log line, and nothing stops someone from starting the app in production with insecure cookies.

Outcome

Text
src/middleware/security-headers.js   (new)src/config.js                        (production checks, TRUST_PROXY)scripts/reset.js                     (new: npm run db:reset)test/hardening.test.js               (new)
  • Every response carries security headers and an X-Request-Id; error pages show that ID as a reference.
  • NODE_ENV=production with insecure settings stops the app at startup with a list of problems.
  • npm run db:reset rebuilds a local database from scratch, and refuses anything that is not a Caretaker learning database.
  • npm run check validates the policies and runs every test.

The problem

Operating an app is mostly about the bad day: something fails, a user reports "it says Something went wrong", and you must find out what happened without having logged anything dangerous. And the most common production security bugs are not clever: a debug setting left on, a cookie sent over plain HTTP, a header that helps an attacker.

Build it

1. Security headers

Create src/middleware/security-headers.js:

Create filesrc/middleware/security-headers.jsJavaScript
// A small, explicit set of security headers. Each line is one decision.export function securityHeaders(req, res, next) {  // Only load scripts, styles, images and form targets from our own origin; never be framed.  res.set('Content-Security-Policy', "default-src 'self'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none'; base-uri 'none'; object-src 'none'");  // Do not guess content types (a text file must not run as a script).  res.set('X-Content-Type-Options', 'nosniff');  // Send only our origin, not full URLs with ids, to other websites.  res.set('Referrer-Policy', 'same-origin');  // Older browsers' equivalent of frame-ancestors 'none'.  res.set('X-Frame-Options', 'DENY');  next();}
  • Content Security Policy. Our pages use only external files from our own origin (/css/style.css, /js/app.js) and no inline scripts, so a strict policy costs nothing. If an XSS bug ever slipped through, an injected <script> would be refused by the browser.
  • frame-ancestors 'none' stops other websites from embedding our pages in a frame to trick users into clicking (clickjacking).

A library such as Helmet sets similar headers. We write them out to see each one; either choice is fine.

2. Request IDs and the error page

Change the request logger in src/app.js so that every request gets a random ID, sent back in a header and printed in the log, and register the headers middleware:

Editsrc/app.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
Change 1 of 4
import express from 'express';import path from 'node:path';import crypto from 'node:crypto';import { securityHeaders } from './middleware/security-headers.js';
Change 2 of 4
export const app = express();app.disable('x-powered-by');
Change 3 of 4
app.use((req, res, next) => {  req.id = crypto.randomUUID().slice(0, 8);  res.set('X-Request-Id', req.id);  if (process.env.NODE_ENV === 'test') {    return next();  }  const started = Date.now();  res.on('finish', () => {    console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);    console.log(`${req.id} ${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();});app.use(securityHeaders);
Change 4 of 4
  const status = err.status ?? 500;  if (status >= 500) {    console.error(err);    console.error(`${req.id} unhandled error`, err);  }  const message = err.expose ? err.message : 'Something went wrong';  res.status(status).render('error', { title: 'Error', status, message });  res.status(status).render('error', { title: 'Error', status, message, requestId: req.id });
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import crypto from 'node:crypto';import { securityHeaders } from './middleware/security-headers.js';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { can } from './authz/rules.js';import { csrf } from './middleware/csrf.js';import { authRouter } from './routes/auth.js';import { accountRouter } from './routes/account.js';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.js'; export const app = express();app.disable('x-powered-by'); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });app.locals.currentUser = null;app.locals.flash = null;app.locals.csrfToken = ''; const PgSession = connectPgSimple(session); app.use((req, res, next) => {  req.id = crypto.randomUUID().slice(0, 8);  res.set('X-Request-Id', req.id);  if (process.env.NODE_ENV === 'test') {    return next();  }  const started = Date.now();  res.on('finish', () => {    console.log(`${req.id} ${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();});app.use(securityHeaders); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false }));app.use(session({  store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }),  name: 'caretaker.sid',  secret: config.sessionSecret,  resave: false,  saveUninitialized: false,  cookie: {    httpOnly: true,    sameSite: 'lax',    secure: config.cookieSecure,    maxAge: 8 * 60 * 60 * 1000,  },}));app.use(loadUser);app.use(flash);app.use(csrf); app.use(authRouter);app.use(requireLogin);app.use((req, res, next) => {  res.locals.can = (action, resource) => can(req.user, action, resource);  next();}); app.get('/', async (req, res) => {  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard(req.user.id) });}); app.use('/account', accountRouter);app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => {  res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(`${req.id} unhandled error`, err);  }  const message = err.expose ? err.message : 'Something went wrong';  res.status(status).render('error', { title: 'Error', status, message, requestId: req.id });});

Eight hexadecimal characters are plenty to find one line in a day's log; the ID carries no information about the user.

Editviews/error.ejsEJS
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
<p><%= message %></p><% if (typeof requestId !== 'undefined' && requestId) { %><p class="muted">Reference: <code><%= requestId %></code></p><% } %>
Show the whole views/error.ejs after this change
<%- include('partials/head') %><h1><%= status === 500 ? 'Something went wrong' : 'Request failed' %></h1><p><%= message %></p><% if (typeof requestId !== 'undefined' && requestId) { %><p class="muted">Reference: <code><%= requestId %></code></p><% } %><p><a href="/issues">Go to the issues list</a></p><%- include('partials/foot') %>

3. What decision logs should contain

Our authorize() already follows the rule from lesson 6.4; here it is written down, because logs outlive code reviews:

Log Do log Never log
Decisions (AUTHZ_LOG=1) user ID, action, resource type and ID, decision, policy IDs entity attributes, emails, names, titles
Authorization problems (always) the above plus Cedar's error messages request bodies
Requests request ID, method, path, status, time cookies, CSRF tokens, passwords, query values you did not design
SQL (LOG_SQL=1, development only) statement text and parameter values anything in production

LOG_SQL prints parameter values, which include emails at login and every value users type. That is why the next step refuses it in production.

4. Refuse unsafe production settings

Add the checks to src/config.js:

Editsrc/config.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
  loginRateLimit: Number(process.env.LOGIN_RATE_LIMIT ?? 10),  // Set TRUST_PROXY=1 behind a TLS-terminating proxy, so req.secure and req.ip are correct.  trustProxy: process.env.TRUST_PROXY === '1',}; // Settings that are fine on a laptop and dangerous in production.export function productionProblems(c) {  if (c.env !== 'production') return [];  const problems = [];  if (!c.cookieSecure) problems.push('COOKIE_SECURE must be 1: session cookies must only travel over HTTPS.');  if (c.sessionSecret.length < 32) problems.push('SESSION_SECRET must be at least 32 random characters.');  if (c.logSql) problems.push('LOG_SQL must be off: it logs parameter values such as emails.');  return problems;} const problems = productionProblems(config);if (problems.length > 0) {  throw new Error(`Refusing to start with unsafe production settings:\n- ${problems.join('\n- ')}`);}
Show the whole src/config.js after this change
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),  // Set TRUST_PROXY=1 behind a TLS-terminating proxy, so req.secure and req.ip are correct.  trustProxy: process.env.TRUST_PROXY === '1',}; // Settings that are fine on a laptop and dangerous in production.export function productionProblems(c) {  if (c.env !== 'production') return [];  const problems = [];  if (!c.cookieSecure) problems.push('COOKIE_SECURE must be 1: session cookies must only travel over HTTPS.');  if (c.sessionSecret.length < 32) problems.push('SESSION_SECRET must be at least 32 random characters.');  if (c.logSql) problems.push('LOG_SQL must be off: it logs parameter values such as emails.');  return problems;} const problems = productionProblems(config);if (problems.length > 0) {  throw new Error(`Refusing to start with unsafe production settings:\n- ${problems.join('\n- ')}`);}

And tell Express about a proxy when there is one, right after creating the app:

Editsrc/app.jsJavaScript
Remove the lines marked − and add the lines marked +. Unmarked lines stay as they are; they show you where the change goes.
app.disable('x-powered-by');if (config.trustProxy) {  app.set('trust proxy', 1);}
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import crypto from 'node:crypto';import { securityHeaders } from './middleware/security-headers.js';import session from 'express-session';import connectPgSimple from 'connect-pg-simple';import { config } from './config.js';import { pool } from './db.js';import { loadUser, requireLogin } from './middleware/auth.js';import { flash } from './middleware/flash.js';import { can } from './authz/rules.js';import { csrf } from './middleware/csrf.js';import { authRouter } from './routes/auth.js';import { accountRouter } from './routes/account.js';import { issuesRouter } from './routes/issues.js';import { organisationsRouter } from './routes/organisations.js';import { buildingsRouter } from './routes/buildings.js';import { inspectionsRouter } from './routes/inspections.js';import { getDashboard } from './models/dashboard.js'; export const app = express();app.disable('x-powered-by');if (config.trustProxy) {  app.set('trust proxy', 1);} app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (value) => new Date(value).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });app.locals.currentUser = null;app.locals.flash = null;app.locals.csrfToken = ''; const PgSession = connectPgSimple(session); app.use((req, res, next) => {  req.id = crypto.randomUUID().slice(0, 8);  res.set('X-Request-Id', req.id);  if (process.env.NODE_ENV === 'test') {    return next();  }  const started = Date.now();  res.on('finish', () => {    console.log(`${req.id} ${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);  });  next();});app.use(securityHeaders); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false }));app.use(session({  store: new PgSession({ pool, tableName: 'session', pruneSessionInterval: config.env === 'test' ? false : 900 }),  name: 'caretaker.sid',  secret: config.sessionSecret,  resave: false,  saveUninitialized: false,  cookie: {    httpOnly: true,    sameSite: 'lax',    secure: config.cookieSecure,    maxAge: 8 * 60 * 60 * 1000,  },}));app.use(loadUser);app.use(flash);app.use(csrf); app.use(authRouter);app.use(requireLogin);app.use((req, res, next) => {  res.locals.can = (action, resource) => can(req.user, action, resource);  next();}); app.get('/', async (req, res) => {  res.render('dashboard', { title: 'Dashboard', dashboard: await getDashboard(req.user.id) });}); app.use('/account', accountRouter);app.use('/issues', issuesRouter);app.use('/organisations', organisationsRouter);app.use('/buildings', buildingsRouter);app.use('/inspections', inspectionsRouter); app.use((req, res) => {  res.status(404).render('not-found', { title: 'Not found', path: req.originalUrl });}); app.use((err, req, res, next) => {  const status = err.status ?? 500;  if (status >= 500) {    console.error(`${req.id} unhandled error`, err);  }  const message = err.expose ? err.message : 'Something went wrong';  res.status(status).render('error', { title: 'Error', status, message, requestId: req.id });});

Behind a TLS-terminating proxy, Express otherwise sees plain HTTP from the proxy and would refuse to set Secure cookies, and req.ip (used by the login rate limit) would be the proxy's address for every user.

5. A guarded reset, and one check command

Create scripts/reset.js:

Create filescripts/reset.jsJavaScript
// Rebuilds a LOCAL learning database: drop everything, migrate, seed.import pg from 'pg';import { migrate } from '../src/migrate.js';import { seed } from '../src/seed.js'; const url = process.env.DATABASE_URL ?? '';if (process.env.NODE_ENV === 'production' || !/\/caretaker(_test)?$/.test(url)) {  console.error(`Refusing to reset ${url || '(no DATABASE_URL)'}: only the local caretaker and caretaker_test databases can be reset.`);  process.exit(1);} const client = new pg.Client({ connectionString: url });await client.connect();try {  await client.query('DROP SCHEMA public CASCADE; CREATE SCHEMA public AUTHORIZATION pg_database_owner; GRANT USAGE ON SCHEMA public TO PUBLIC;');  await migrate(url, { log: () => {} });  await seed(client);} finally {  await client.end();}console.log('database reset: schema dropped, migrations applied, scenario seeded');

The schema is recreated the way PostgreSQL's initdb makes it: owned by pg_database_owner, usable by everyone. Resetting also removes the session table's rows, so everyone is logged out.

Runcaretaker/
npm pkg set scripts.db:reset="node --env-file=.env scripts/reset.js"
npm pkg set scripts.check="npm run authz:validate && npm test"

6. Tests

Create filetest/hardening.test.jsJavaScript
import { test, before, after } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js';import { pool } from '../src/db.js';import { productionProblems } from '../src/config.js';import { resetDatabase, loginAs } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('responses carry security headers and a request id, and no framework banner', async () => {  const res = await request(app).get('/login');  assert.equal(res.headers['x-powered-by'], undefined);  assert.match(res.headers['content-security-policy'], /default-src 'self'/);  assert.match(res.headers['content-security-policy'], /frame-ancestors 'none'/);  assert.equal(res.headers['x-content-type-options'], 'nosniff');  assert.equal(res.headers['x-frame-options'], 'DENY');  assert.match(res.headers['x-request-id'], /^[0-9a-f]{8}$/);}); test('error pages show the request id as a reference', async () => {  const alice = await loginAs('alice');  const res = await alice.post('/issues/101/delete').set('X-CSRF-Token', 'wrong');  assert.equal(res.status, 403);  assert.match(res.text, new RegExp(`Reference: <code>${res.headers['x-request-id']}</code>`));}); test('unsafe production settings are reported', () => {  const base = { env: 'production', cookieSecure: true, sessionSecret: 'x'.repeat(64), logSql: false };  assert.deepEqual(productionProblems(base), []);  assert.equal(productionProblems({ ...base, cookieSecure: false }).length, 1);  assert.equal(productionProblems({ ...base, sessionSecret: 'short' }).length, 1);  assert.equal(productionProblems({ ...base, logSql: true }).length, 1);  assert.deepEqual(productionProblems({ ...base, env: 'development', cookieSecure: false }), []);});

Run and inspect

Run and comparecaretaker/
npm run check

> caretaker@1.0.0 check
> npm run authz:validate && npm test


> caretaker@1.0.0 authz:validate
> node scripts/validate-policies.js

12 policies are valid against the schema

> 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) (475.063625ms)
✔ edit issue 101 (25.0885ms)
✔ view issue 103 (building 20) (25.107958ms)
✔ edit issue 103 (reported by dave) (25.84025ms)
✔ report an issue at building 20 (27.080334ms)
✔ view issue 105 (building 30) (17.54375ms)
✔ view issue 106 (building 40, reported by bob) (20.222875ms)
✔ approve inspection 201 (created by dave) (15.948083ms)
✔ approve inspection 202 (created by alice) (20.574125ms)
✔ update organisation 1 (18.120167ms)
✔ change own role at building 10 (4.321875ms)
✔ grant building_admin at building 10 to dave (20.77625ms)
✔ grant viewer at building 10 to dave (17.75925ms)
✔ issues in each user's list come only from the expected buildings (118.226167ms)
✔ the scenario loads exactly as specified (211.803ms)
✔ only one active assignment per user, building and role (0.913417ms)
✔ a revoked role can be granted again (0.89275ms)
✔ the My access page shows what the server loaded (71.099291ms)
✔ a correct login creates a session and shows the user (259.733541ms)
✔ a wrong password or unknown email gets the same 401 (53.353541ms)
✔ registration validates, creates a user, and logs them in (44.019625ms)
✔ registering an existing email is a field error (33.170083ms)
✔ logout destroys the session (49.654291ms)
✔ allow: a permit matched and nothing forbade it (286.287792ms)
✔ explicit deny: a forbid overrides a matching permit (3.621334ms)
✔ implicit deny: no permit matched (2.220709ms)
authz problem {
Show 121 more lines 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.441833ms) ✔ unknown actions throw instead of deciding (1.321583ms) ✔ unknown callers are refused (213.7135ms) ✔ decisions match the app (27.4795ms) ✔ attributes sent by the caller are ignored (3.164541ms) ✔ context is validated and used (10.628459ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (425.150708ms) ✔ a revoked assignment cannot be revoked again (4.565584ms) ✔ an assignment id from another building is not found here (4.032459ms) ✔ alice cannot revoke her own building_admin role; carol can (12.785583ms) ✔ grants are limited to members of the building's organisation (6.0045ms) ✔ a building can be created inside an organisation (289.995541ms) ✔ a duplicate building name in the same organisation is a field error (6.1165ms) ✔ the same building name is allowed in another organisation (10.812166ms) ✔ a building with issues cannot be deleted (13.617959ms) ✔ an empty building can be deleted (10.942292ms) ✔ an organisation with buildings cannot be deleted, an empty one can (27.731042ms) ✔ a logged-in POST without a token is refused with 403 (273.682666ms) ✔ a token from another session is refused (36.980542ms) ✔ the right token in the form field works (18.839208ms) ✔ every POST form on every page carries the token (56.176333ms) ✔ the dashboard counts match the database (275.651208ms) ✔ only the buildings carol can see appear (4.813125ms) ✔ headers that claim another identity are ignored (282.624083ms) ✔ query strings and form fields that claim roles are ignored (11.969208ms) ✔ a forged reporter or status in an edit form does not reach the database (6.354125ms) ✔ a forged grant context cannot make dave a building admin (4.539625ms) ✔ responses carry security headers and a request id, and no framework banner (213.248084ms) ✔ error pages show the request id as a reference (68.211041ms) ✔ unsafe production settings are reported (0.322ms) ✔ create a draft, edit it, submit it, approve it (353.576792ms) ✔ invalid transitions are refused with 409 and change nothing (11.787ms) ✔ only drafts can be edited (5.828333ms) ✔ returning a submitted inspection makes it editable again (8.786625ms) ✔ concurrent approvals: exactly one wins (27.131666ms) ✔ unknown actions are 404 (3.166875ms) ✔ the issues list contains only issues from visible buildings (584.22975ms) ✔ a filter for another tenant's building returns nothing (4.236041ms) ✔ the inspections list is scoped too (9.469959ms) ✔ organisations are listed for their members only (8.906917ms) ✔ the dashboard counts only visible data (6.881667ms) ✔ view issue 101 (building 10) (476.0755ms) ✔ open the edit form for issue 101 (23.986125ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (21.825583ms) ✔ view issue 105 (building 30) and 106 (building 40) (37.310084ms) ✔ report an issue at building 20 (23.5875ms) ✔ a reporter cannot edit their own issue once it is closed (8.129583ms) ✔ only building admins may delete; refusals change nothing (15.249792ms) ✔ the edit form cannot move an issue to another building (3.909375ms) ✔ the list pages 10 at a time and reports the total (300.545042ms) ✔ pages do not overlap (24.53875ms) ✔ filters combine with AND (7.309125ms) ✔ sorting by priority puts critical first when descending (7.018583ms) ✔ unknown sort keys and SQL in the query string are ignored (42.030666ms) ✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (351.12725ms) ✔ dave may update his own issue 103 but is not a reporter at building 10 (6.470042ms) ✔ dave cannot move issue 101: he may not update it where it is (5.078667ms) ✔ carol moves 101 to building 20, but never to another organisation (9.998417ms) ✔ a forged building id on create is refused and creates nothing (27.422917ms) ✔ GET /issues lists issues from the database (289.646833ms) ✔ GET /issues/101 shows one issue with its building (6.907375ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (14.6695ms) ✔ POST /issues re-renders the form with errors (4.913ms) ✔ POST /issues stores the issue and redirects to it (9.011459ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.495791ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.31175ms) ✔ an issue time in the future is rejected (4.388083ms) ✔ GET /issues/101/edit shows the current values (5.053583ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.174708ms) ✔ POST /issues/:id/delete removes the issue (11.233167ms) ✔ the issues list contains exactly the issues Cedar lets each user view (320.685875ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (21.036958ms) ✔ only organisation admins can open the members page (441.723ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (16.611ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.198666ms) ✔ nobody changes their own membership (3.694375ms) ✔ unknown emails and roles are form errors (8.915958ms) ✔ a member cannot add members, even with a well-formed request (6.841917ms) ✔ GET /organisations lists organisations with building counts (271.665667ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (14.72575ms) ✔ POST /organisations validates and creates (13.872542ms) ✔ POST /organisations/:id/edit renames the organisation (10.958625ms) ✔ unknown organisations are 404 (7.0555ms) ✔ every policy is valid against the schema (32.210375ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.438959ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (348.56925ms) ✔ anonymous requests are redirected to the login page (220.328792ms) ✔ anonymous writes are refused and change nothing (10.783125ms) ✔ login and register pages stay public (6.248875ms) ✔ login issues a new session id (no session fixation) (32.151833ms) ✔ returnTo only follows local paths (28.704459ms) ✔ new issues and transitions record the logged-in user (96.020708ms) ✔ the session cookie has the attributes we chose (26.241875ms) ✔ organisation 1: view and update (486.075625ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (7.8205ms) ✔ building 10: view, update, delete (59.967375ms) ✔ creating buildings needs org_admin (19.816125ms) ✔ creating an organisation makes the creator its admin (9.49525ms) ✔ inspections: view 201, open the edit form for draft 203 (46.943875ms) ✔ approve inspection 201 (dave's): only building admins (17.285875ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (13.429709ms) ✔ bob gets 404 for every Liffey route, and nothing changes (448.44175ms) ✔ ravi gets 404 for every Liffey route, and nothing changes (90.430333ms) ✔ nora gets 404 for every Liffey route, and nothing changes (93.460083ms) ✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (71.017625ms) ℹ tests 131 ℹ suites 0 ℹ pass 131 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 14862.492625
Server terminal (leave it running)caretaker/
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js

Caretaker listening on http://localhost:3000
Run and comparecaretaker/
curl -si http://localhost:3000/login | sed -n '1,12p'
HTTP/1.1 200 OK
X-Request-Id: 3ccdd6b7
Content-Security-Policy: default-src 'self'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none'; base-uri 'none'; object-src 'none'
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
X-Frame-Options: DENY
Content-Type: text/html; charset=utf-8
Content-Length: 1631
ETag: W/"65f-umaExt1BjNAZ3udMBhtiiPGD2dY"
Set-Cookie: caretaker.sid=s%3A0Ecxh6Vg5zz6pNVGsbh8ojDJqNULdvyk.NPLbQv0CH0i2kq5cdsJshBpLWNYZX0pOx1XH6ZxBhNE; Path=/; Expires=Sat, 28 Nov 2026 22:51:36 GMT; HttpOnly; SameSite=Lax
Date: Sat, 28 Nov 2026 14:51:36 GMT
Connection: keep-alive

No X-Powered-By; a policy for scripts and frames; a request ID. Now a server-side failure, as a user would see it, and the matching log line. A request with a wrong CSRF token gives a 403 whose page carries the reference:

Run and comparecaretaker/
curl -s -X POST http://localhost:3000/issues/101/delete -d _csrf=wrong | grep -E "<h1>|Reference"
<h1>Request failed</h1>
<p class="muted">Reference: <code>3fdc7f6b</code></p>
Server terminal output
3fdc7f6b POST /issues/101/delete -> 403 (8 ms)

The ID in the page and in the log line is the same: a user can quote it, and you can find the request.

Ctrl+C Stop the server in the server terminal.

Try a production start with development settings:

Run and comparecaretaker/exit code 1 (expected)
NODE_ENV=production LOG_SQL=1 node --env-file=.env src/server.js
file:///Users/you/code/caretaker/src/config.js:35
  throw new Error(`Refusing to start with unsafe production settings:\n- ${problems.join('\n- ')}`);
        ^

Error: Refusing to start with unsafe production settings:
- COOKIE_SECURE must be 1: session cookies must only travel over HTTPS.
- LOG_SQL must be off: it logs parameter values such as emails.
    at file:///Users/you/code/caretaker/src/config.js:35:9
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

Node.js v22.23.1

Reset the development database:

Run and comparecaretaker/
npm run db:reset

> caretaker@1.0.0 db:reset
> node --env-file=.env scripts/reset.js

database reset: schema dropped, migrations applied, scenario seeded

Experiment

Predict What does DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/postgres npm run db:reset do?
Run and comparecaretaker/exit code 1 (expected)
DATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/postgres npm run db:reset

> caretaker@1.0.0 db:reset
> node --env-file=.env scripts/reset.js

Refusing to reset postgres://caretaker:caretaker_dev_password@localhost:5433/postgres: only the local caretaker and caretaker_test databases can be reset.
Reveal Answer

It refuses. The variable on the command line wins over the value in .env, the guard sees a database named postgres, and exits. Only URLs that end in /caretaker or /caretaker_test can be reset, and never with NODE_ENV=production. A destructive command should name exactly what it may destroy, not trust that you typed the right URL.

Checkpoint

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) (509.343292ms)
✔ edit issue 101 (26.965291ms)
✔ view issue 103 (building 20) (26.683ms)
✔ edit issue 103 (reported by dave) (27.426792ms)
✔ report an issue at building 20 (25.91575ms)
✔ view issue 105 (building 30) (19.406458ms)
✔ view issue 106 (building 40, reported by bob) (21.276083ms)
✔ approve inspection 201 (created by dave) (20.501542ms)
✔ approve inspection 202 (created by alice) (21.678875ms)
✔ update organisation 1 (19.418708ms)
✔ change own role at building 10 (4.784792ms)
✔ grant building_admin at building 10 to dave (26.181125ms)
✔ grant viewer at building 10 to dave (22.488834ms)
✔ issues in each user's list come only from the expected buildings (135.231417ms)
✔ the scenario loads exactly as specified (211.266625ms)
✔ only one active assignment per user, building and role (0.974ms)
✔ a revoked role can be granted again (0.987292ms)
✔ the My access page shows what the server loaded (75.312458ms)
✔ a correct login creates a session and shows the user (254.975792ms)
✔ a wrong password or unknown email gets the same 401 (52.803291ms)
✔ registration validates, creates a user, and logs them in (42.182667ms)
✔ registering an existing email is a field error (34.434958ms)
✔ logout destroys the session (53.711667ms)
✔ allow: a permit matched and nothing forbade it (212.995916ms)
✔ explicit deny: a forbid overrides a matching permit (2.770375ms)
✔ implicit deny: no permit matched (2.285625ms)
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.087042ms)
Show 112 more lines✔ unknown actions throw instead of deciding (1.407333ms) ✔ unknown callers are refused (214.230583ms) ✔ decisions match the app (26.322417ms) ✔ attributes sent by the caller are ignored (3.081583ms) ✔ context is validated and used (10.248125ms) ✔ revoking dave's inspector role at building 10 takes effect on his next request (399.637375ms) ✔ a revoked assignment cannot be revoked again (5.00925ms) ✔ an assignment id from another building is not found here (4.348667ms) ✔ alice cannot revoke her own building_admin role; carol can (13.300167ms) ✔ grants are limited to members of the building's organisation (6.453958ms) ✔ a building can be created inside an organisation (294.536167ms) ✔ a duplicate building name in the same organisation is a field error (6.654125ms) ✔ the same building name is allowed in another organisation (11.354959ms) ✔ a building with issues cannot be deleted (14.8395ms) ✔ an empty building can be deleted (11.058709ms) ✔ an organisation with buildings cannot be deleted, an empty one can (25.901583ms) ✔ a logged-in POST without a token is refused with 403 (279.122833ms) ✔ a token from another session is refused (37.232208ms) ✔ the right token in the form field works (19.435917ms) ✔ every POST form on every page carries the token (60.73175ms) ✔ the dashboard counts match the database (278.534125ms) ✔ only the buildings carol can see appear (5.0785ms) ✔ headers that claim another identity are ignored (276.789666ms) ✔ query strings and form fields that claim roles are ignored (11.863708ms) ✔ a forged reporter or status in an edit form does not reach the database (5.539333ms) ✔ a forged grant context cannot make dave a building admin (5.11075ms) ✔ responses carry security headers and a request id, and no framework banner (210.651458ms) ✔ error pages show the request id as a reference (66.310666ms) ✔ unsafe production settings are reported (0.372959ms) ✔ create a draft, edit it, submit it, approve it (345.28975ms) ✔ invalid transitions are refused with 409 and change nothing (11.9395ms) ✔ only drafts can be edited (5.655167ms) ✔ returning a submitted inspection makes it editable again (7.987625ms) ✔ concurrent approvals: exactly one wins (29.370958ms) ✔ unknown actions are 404 (3.395958ms) ✔ the issues list contains only issues from visible buildings (591.927209ms) ✔ a filter for another tenant's building returns nothing (3.79425ms) ✔ the inspections list is scoped too (9.797958ms) ✔ organisations are listed for their members only (9.381458ms) ✔ the dashboard counts only visible data (9.943708ms) ✔ view issue 101 (building 10) (478.935667ms) ✔ open the edit form for issue 101 (26.968917ms) ✔ open the edit form for issue 103 (reported by dave, building 20) (25.802458ms) ✔ view issue 105 (building 30) and 106 (building 40) (42.164209ms) ✔ report an issue at building 20 (28.067917ms) ✔ a reporter cannot edit their own issue once it is closed (9.084625ms) ✔ only building admins may delete; refusals change nothing (19.778833ms) ✔ the edit form cannot move an issue to another building (4.231167ms) ✔ the list pages 10 at a time and reports the total (302.312917ms) ✔ pages do not overlap (24.847208ms) ✔ filters combine with AND (7.21975ms) ✔ sorting by priority puts critical first when descending (7.955834ms) ✔ unknown sort keys and SQL in the query string are ignored (42.908708ms) ✔ alice may update 101 at building 10 but may not create at building 20, so she cannot move it there (352.001917ms) ✔ dave may update his own issue 103 but is not a reporter at building 10 (6.514792ms) ✔ dave cannot move issue 101: he may not update it where it is (7.164958ms) ✔ carol moves 101 to building 20, but never to another organisation (10.138292ms) ✔ a forged building id on create is refused and creates nothing (25.449875ms) ✔ GET /issues lists issues from the database (284.24125ms) ✔ GET /issues/101 shows one issue with its building (7.084959ms) ✔ GET /issues/:id answers 404 for unknown or malformed ids (15.464834ms) ✔ POST /issues re-renders the form with errors (5.308041ms) ✔ POST /issues stores the issue and redirects to it (8.468541ms) ✔ POST /issues with a building that does not exist is a form error, not a 500 (4.408167ms) ✔ the stored row has the cleaned values and ignores a client-sent status (4.354041ms) ✔ an issue time in the future is rejected (4.423083ms) ✔ GET /issues/101/edit shows the current values (5.122917ms) ✔ POST /issues/:id/edit changes the status and updated_at (5.671916ms) ✔ POST /issues/:id/delete removes the issue (11.788875ms) ✔ the issues list contains exactly the issues Cedar lets each user view (336.528ms) ✔ the inspections list contains exactly the inspections Cedar lets each user view (21.298125ms) ✔ only organisation admins can open the members page (430.633583ms) ✔ controlled onboarding: carol adds nora; nora sees the organisation but no building (17.694958ms) ✔ promoting dave to org_admin gives him the organisation's admin rights on his next request (12.286417ms) ✔ nobody changes their own membership (5.445625ms) ✔ unknown emails and roles are form errors (9.929667ms) ✔ a member cannot add members, even with a well-formed request (3.89275ms) ✔ GET /organisations lists organisations with building counts (266.249208ms) ✔ GET /organisations/1 shows its buildings, not other organisations' buildings (15.597208ms) ✔ POST /organisations validates and creates (15.418667ms) ✔ POST /organisations/:id/edit renames the organisation (10.736ms) ✔ unknown organisations are 404 (6.364292ms) ✔ every policy is valid against the schema (32.919916ms) ✔ every action used by the app is mentioned by a policy, directly or through its group (9.324125ms) ✔ failed logins are limited per client; the limit then blocks even correct passwords (358.380625ms) ✔ anonymous requests are redirected to the login page (219.698166ms) ✔ anonymous writes are refused and change nothing (11.057709ms) ✔ login and register pages stay public (5.808458ms) ✔ login issues a new session id (no session fixation) (31.8815ms) ✔ returnTo only follows local paths (28.859542ms) ✔ new issues and transitions record the logged-in user (86.920916ms) ✔ the session cookie has the attributes we chose (26.267417ms) ✔ organisation 1: view and update (493.044791ms) ✔ ravi is still a member of organisation 2 but can see none of its buildings (8.525ms) ✔ building 10: view, update, delete (56.0575ms) ✔ creating buildings needs org_admin (15.527708ms) ✔ creating an organisation makes the creator its admin (9.123084ms) ✔ inspections: view 201, open the edit form for draft 203 (41.546375ms) ✔ approve inspection 201 (dave's): only building admins (22.118333ms) ✔ creating an inspection needs inspector or building_admin at the chosen building (14.6065ms) ✔ bob gets 404 for every Liffey route, and nothing changes (459.182208ms) ✔ ravi gets 404 for every Liffey route, and nothing changes (98.159792ms) ✔ nora gets 404 for every Liffey route, and nothing changes (92.729667ms) ✔ inside one tenant: alice, a viewer at building 20, cannot change anything there (63.570208ms) ℹ tests 131 ℹ suites 0 ℹ pass 131 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 14890.493042
Run and comparecaretaker/
git add -A
git commit -m "Hardening, request ids, production checks, db:reset"
[main 6016c12] Hardening, request ids, production checks, db:reset
 7 files changed, 102 insertions(+), 4 deletions(-)
 create mode 100644 scripts/reset.js
 create mode 100644 src/middleware/security-headers.js
 create mode 100644 test/hardening.test.js
Symptom The page loses its styling after adding the headers

The Content Security Policy blocks inline styles and scripts. Our templates have none; if you added style="..." attributes or <script> blocks, move them into public/css/style.css or public/js/app.js.

Recap and next step

Responses no longer advertise the framework and carry headers that limit what injected content could do. Request IDs connect what users see to what we logged, and logs follow explicit rules about what they may contain. Production refuses unsafe settings, and the destructive reset names what it may touch.

Next lesson walks through the finished application as each of our six users, and runs the whole test matrix.