Checkpoint · Lesson 10.1
Hardening, logging and configuration: checkpoint files
Compare your folder with the reference using Git, if you cloned it: git diff lesson/m10-l01 -- src.
Files changed in this lesson
package.json changed
package.json{
"name": "caretaker",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"",
"start": "node --env-file=.env src/server.js",
"dev": "node --env-file=.env --watch src/server.js",
"db:migrate": "node --env-file=.env scripts/migrate.js",
"db:seed": "node --env-file=.env scripts/seed.js",
"authz:validate": "node scripts/validate-policies.js",
"authz:explain": "node --env-file=.env scripts/authz-explain.js",
"authz:service": "node --env-file=.env services/start-authz-service.js",
"db:reset": "node --env-file=.env scripts/reset.js",
"check": "npm run authz:validate && npm test"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies": {
"@cedar-policy/cedar-wasm": "4.14.0",
"argon2": "0.45.2",
"connect-pg-simple": "10.0.0",
"ejs": "7.0.2",
"express": "5.3.0",
"express-rate-limit": "8.7.4",
"express-session": "1.19.0",
"pg": "8.23.1"
},
"devDependencies": {
"supertest": "7.3.2"
}
}
{ "name": "caretaker", "version": "1.0.0", "description": "", "scripts": { "test": "node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec \"test/**/*.test.js\"", "start": "node --env-file=.env src/server.js", "dev": "node --env-file=.env --watch src/server.js", "db:migrate": "node --env-file=.env scripts/migrate.js", "db:seed": "node --env-file=.env scripts/seed.js", "authz:validate": "node scripts/validate-policies.js", "authz:explain": "node --env-file=.env scripts/authz-explain.js", "authz:service": "node --env-file=.env services/start-authz-service.js", "db:reset": "node --env-file=.env scripts/reset.js", "check": "npm run authz:validate && npm test" }, "keywords": [], "author": "", "license": "ISC", "type": "module", "dependencies": { "@cedar-policy/cedar-wasm": "4.14.0", "argon2": "0.45.2", "connect-pg-simple": "10.0.0", "ejs": "7.0.2", "express": "5.3.0", "express-rate-limit": "8.7.4", "express-session": "1.19.0", "pg": "8.23.1" }, "devDependencies": { "supertest": "7.3.2" }}scripts/reset.js added
scripts/reset.js// 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');
// 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');src/app.js changed
src/app.jsimport 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 });
});
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 });});src/config.js changed
src/config.jsfunction 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- ')}`);
}
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- ')}`);}src/middleware/security-headers.js added
src/middleware/security-headers.js// 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();
}
// 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();}test/hardening.test.js added
test/hardening.test.jsimport { 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 }), []);
});
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 }), []);});views/error.ejs changed
views/error.ejs<%- 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') %>
<%- 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') %>Project tree at this checkpoint
.env.example
.env.test
.gitignore
.npmrc
compose.yaml
db/init/01-create-test-database.sql
migrations/001_create_organisations_buildings_issues.sql
migrations/002_create_inspections.sql
migrations/003_create_users.sql
migrations/004_create_session_table.sql
migrations/005_create_memberships_and_building_roles.sql
migrations/006_create_permission_changes.sql
package-lock.json
package.json
public/css/style.css
public/js/app.js
scripts/authz-bench.js
scripts/authz-explain.js
scripts/cedar-errors-demo.js
scripts/cedar-hello.js
scripts/forged-entity-demo.js
scripts/migrate.js
scripts/partial-demo.js
scripts/reset.js
scripts/seed.js
scripts/template-demo.js
scripts/validate-policies.js
services/authz-service.js
services/start-authz-service.js
src/app.js
src/authz/authorize.js
src/authz/cedar.js
src/authz/entities.js
src/authz/policies/building-admin.cedar
src/authz/policies/building-read.cedar
src/authz/policies/forbid-building-admin-grants.cedar
src/authz/policies/forbid-self-approval.cedar
src/authz/policies/forbid-self-membership-change.cedar
src/authz/policies/forbid-self-role-change.cedar
src/authz/policies/inspector-create-inspection.cedar
src/authz/policies/inspector-own-inspections.cedar
src/authz/policies/org-admin.cedar
src/authz/policies/org-member.cedar
src/authz/policies/reporter-create-issue.cedar
src/authz/policies/reporter-own-issues.cedar
src/authz/policy-store.js
src/authz/request.js
src/authz/rules.js
src/authz/schema.cedarschema
src/config.js
src/db.js
src/lib/http.js
src/lib/ids.js
src/lib/validation.js
src/middleware/auth.js
src/middleware/csrf.js
src/middleware/flash.js
src/middleware/rate-limit.js
src/middleware/security-headers.js
src/migrate.js
src/models/access.js
src/models/assignments.js
src/models/buildings.js
src/models/dashboard.js
src/models/inspections.js
src/models/issues.js
src/models/members.js
src/models/organisations.js
src/models/scope.js
src/models/users.js
src/routes/account.js
src/routes/auth.js
src/routes/buildings.js
src/routes/inspections.js
src/routes/issues.js
src/routes/organisations.js
src/seed.js
src/server.js
test/access-matrix.test.js
test/access.test.js
test/auth.test.js
test/authz-decisions.test.js
test/authz-service.test.js
test/building-access.test.js
test/buildings.test.js
test/csrf.test.js
test/dashboard.test.js
test/forged-input.test.js
test/hardening.test.js
test/helpers.js
test/inspections.test.js
test/isolation.test.js
test/issue-authz.test.js
test/issue-list.test.js
test/issue-moves.test.js
test/issues.test.js
test/list-parity.test.js
test/members.test.js
test/organisations.test.js
test/policies.test.js
test/rate-limit.test.js
test/require-login.test.js
test/resource-authz.test.js
test/tenant-isolation.test.js
views/account.ejs
views/auth/login.ejs
views/auth/register.ejs
views/buildings/access.ejs
views/buildings/form.ejs
views/buildings/show.ejs
views/dashboard.ejs
views/error.ejs
views/forbidden.ejs
views/inspections/form.ejs
views/inspections/index.ejs
views/inspections/show.ejs
views/issues/form.ejs
views/issues/index.ejs
views/issues/move.ejs
views/issues/show.ejs
views/not-found.ejs
views/organisations/form.ejs
views/organisations/index.ejs
views/organisations/members.ejs
views/organisations/show.ejs
views/partials/foot.ejs
views/partials/head.ejs
views/partials/nav.ejs