Module 2 · Persistence and the relational data model
2.6 Safe writes and a test database
Give the tests their own database that resets before every test file, turn constraint violations into form errors, and see exactly what SQL injection does and why placeholders stop it.
Starting point
The app reads and writes issues in PostgreSQL. npm test runs five tests against the development database.
Outcome
caretaker/├── .env.test (committed: local test settings only)└── test/ ├── helpers.js (new: resetDatabase) └── issues.test.js- Tests run against
caretaker_test, which is migrated and re-seeded before every test file. Your development data is never touched. - Choosing a building that does not exist produces a form error, not a 500.
- You have watched an injected string break out of a query, and watched a placeholder stop it.
The problem
Look for the issue that the tests created in the last lesson, in your development database:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT id, title FROM issues WHERE title LIKE 'Water leak by%';
id | title
-----+----------------------------------
132 | Water leak by the staff entrance
(1 row)Every npm test adds another one. Tests that write into the database you develop with are a nuisance today and a disaster the day someone points them at real data. Tests also need a known starting state: lesson 1.5 showed what happens when one test's leftovers change another test's result.
There is a second, quieter problem. Post the form with a building ID that passes validation but does not exist:
npm run dev
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
curl -si http://localhost:3000/issues --data-urlencode "title=Ghost issue" --data-urlencode "building_id=999" --data-urlencode "priority=low" | head -1
HTTP/1.1 500 Internal Server Error
> caretaker@1.0.0 dev
> node --env-file=.env --watch src/server.js
Caretaker listening on http://localhost:3000
error: insert or update on table "issues" violates foreign key constraint "issues_building_id_fkey"
at /Users/you/code/caretaker/node_modules/pg-pool/index.js:45:11
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async query (file:///Users/you/code/caretaker/src/db.js:8:18)
at async createIssue (file:///Users/you/code/caretaker/src/models/issues.js:31:20)
at async file:///Users/you/code/caretaker/src/app.js:81:17 {
length: 264,
severity: 'ERROR',
code: '23503',
detail: 'Key (building_id)=(999) is not present in table "buildings".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'issues',
column: undefined,
dataType: undefined,
constraint: 'issues_building_id_fkey',
file: 'ri_triggers.c',
line: '2826',
routine: 'ri_ReportViolation'
}
POST /issues -> 500 (26 ms)
The foreign key protected the data, exactly as designed in lesson 2.2. But the user sees "Something went wrong" for what is really a mistake in their input.
Build it
1. Settings for tests
Create .env.test. It points at the test database and runs the test server port on 3001 in case you ever start it:
# Settings for automated tests. Local learning values only; safe to commit.NODE_ENV=testDATABASE_URL=postgres://caretaker:caretaker_dev_password@localhost:5433/caretaker_testPORT=3001LOG_SQL=0We commit this file because it contains nothing secret: the same local-only password that is already in compose.yaml. Real secrets never go into a committed file.
2. A reset helper
Create test/helpers.js:
import { pool } from '../src/db.js';import { config } from '../src/config.js';import { migrate } from '../src/migrate.js';import { seed } from '../src/seed.js'; export async function resetDatabase() { if (!config.databaseUrl.endsWith('/caretaker_test')) { throw new Error(`Refusing to reset ${config.databaseUrl}: tests only run against caretaker_test.`); } await migrate(config.databaseUrl, { log: () => {} }); const client = await pool.connect(); try { await seed(client); } finally { client.release(); }}- The guard at the top refuses to run unless the URL ends in
/caretaker_test. If somebody runs the tests with the wrong environment, nothing is deleted. migratebrings the test database's schema up to date, so you never have to remember to migrate it by hand.pool.connect()borrows one connection for the seed's transaction, andclient.release()returns it to the pool.seedrunsBEGIN, many inserts, andCOMMIT; those must all travel over the same connection, whichpool.querycannot promise.
3. Use it in the tests
Call it once before the tests in the file run:
import { test, after } from 'node:test';import { test, before, after } from 'node:test';
import { pool } from '../src/db.js';import { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end());
Show the whole test/issues.test.js after this change
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 { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('GET /issues lists issues from the database', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('GET /issues/101 shows one issue with its building', async () => { const res = await request(app).get('/issues/101'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/); assert.match(res.text, /Dublin Offices/);}); test('GET /issues/:id answers 404 for unknown or malformed ids', async () => { for (const id of ['999999', 'abc', '0', '99999999999']) { const res = await request(app).get(`/issues/${id}`); assert.equal(res.status, 404, `id ${id}`); }}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building_id: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('POST /issues stores the issue and redirects to it', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building_id: '10', priority: 'low' }); assert.equal(res.status, 303); const page = await request(app).get(res.headers.location); assert.equal(page.status, 200); assert.match(page.text, /Water leak by the staff entrance/);});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 { resetDatabase } from './helpers.js';
before(resetDatabase);
after(() => pool.end());
test('GET /issues lists issues from the database', async () => {
const res = await request(app).get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('GET /issues/101 shows one issue with its building', async () => {
const res = await request(app).get('/issues/101');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/);
assert.match(res.text, /Dublin Offices/);
});
test('GET /issues/:id answers 404 for unknown or malformed ids', async () => {
for (const id of ['999999', 'abc', '0', '99999999999']) {
const res = await request(app).get(`/issues/${id}`);
assert.equal(res.status, 404, `id ${id}`);
}
});
test('POST /issues re-renders the form with errors', async () => {
const res = await request(app).post('/issues').type('form').send({ title: '', building_id: '', priority: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Choose a building/);
});
test('POST /issues stores the issue and redirects to it', async () => {
const res = await request(app)
.post('/issues')
.type('form')
.send({ title: 'Water leak by the staff entrance', building_id: '10', priority: 'low' });
assert.equal(res.status, 303);
const page = await request(app).get(res.headers.location);
assert.equal(page.status, 200);
assert.match(page.text, /Water leak by the staff entrance/);
});
And point the test script at the new file:
npm pkg set scripts.test='node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"'
NODE_ENV=testnow comes from.env.test, so the prefix is gone."test/**/*.test.js"names the test files explicitly. Without a pattern, Node treats every.jsfile inside atestfolder as a test file, and would runhelpers.jsas a test of its own. The quotes stop your shell from expanding the pattern; Node expands it.--test-concurrency=1matters as soon as there is a second test file. By default Node runs test files in parallel, each in its own process. Two files that reset the same database at the same moment would delete each other's data halfway through a test. One file at a time keeps them independent.
Remove the test leftovers from your development database by re-seeding it:
npm run db:seed
> caretaker@1.0.0 db:seed
> node --env-file=.env scripts/seed.js
seeded the Caretaker scenario
4. Turn constraint violations into form errors
pg errors carry PostgreSQL's SQLSTATE code in err.code. Give the codes we care about readable names in src/db.js:
export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 }); // PostgreSQL error codes (SQLSTATE) that the app turns into user-facing messages.export const PG_ERRORS = { FOREIGN_KEY_VIOLATION: '23503', RESTRICT_VIOLATION: '23001', UNIQUE_VIOLATION: '23505', CHECK_VIOLATION: '23514',};
Show the whole src/db.js after this change
import pg from 'pg';import { config } from './config.js'; export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 }); // PostgreSQL error codes (SQLSTATE) that the app turns into user-facing messages.export const PG_ERRORS = { FOREIGN_KEY_VIOLATION: '23503', RESTRICT_VIOLATION: '23001', UNIQUE_VIOLATION: '23505', CHECK_VIOLATION: '23514',}; export async function query(text, params = []) { const started = Date.now(); const result = await pool.query(text, params); if (config.logSql) { console.log(`SQL ${Date.now() - started}ms ${text.replace(/\s+/g, ' ').trim()} ${JSON.stringify(params)}`); } return result;}import pg from 'pg';
import { config } from './config.js';
export const pool = new pg.Pool({ connectionString: config.databaseUrl, max: 10 });
// PostgreSQL error codes (SQLSTATE) that the app turns into user-facing messages.
export const PG_ERRORS = {
FOREIGN_KEY_VIOLATION: '23503',
RESTRICT_VIOLATION: '23001',
UNIQUE_VIOLATION: '23505',
CHECK_VIOLATION: '23514',
};
export async function query(text, params = []) {
const started = Date.now();
const result = await pool.query(text, params);
if (config.logSql) {
console.log(`SQL ${Date.now() - started}ms ${text.replace(/\s+/g, ' ').trim()} ${JSON.stringify(params)}`);
}
return result;
}
Now catch the foreign key violation in the POST /issues route:
import { listBuildings } from './models/buildings.js';import { PG_ERRORS } from './db.js';
const issue = await createIssue(values); let issue; try { issue = await createIssue(values); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path';import { listIssues, findIssue, createIssue } from './models/issues.js';import { listBuildings } from './models/buildings.js';import { PG_ERRORS } from './db.js'; export const app = express(); 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.use((req, res, next) => { 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)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.urlencoded({ extended: false })); const PRIORITIES = ['low', 'medium', 'high', 'critical'];const MAX_INTEGER = 2147483647; // Returns a positive integer that fits a PostgreSQL integer column, or null.function parseId(value) { if (typeof value !== 'string' || !/^[1-9][0-9]{0,9}$/.test(value)) { return null; } const id = Number(value); return id <= MAX_INTEGER ? id : null;} function validateIssue(input) { const errors = {}; const title = typeof input.title === 'string' ? input.title.trim() : ''; const description = typeof input.description === 'string' ? input.description.trim() : ''; const buildingId = parseId(input.building_id); if (title.length < 3 || title.length > 200) { errors.title = 'Title must be between 3 and 200 characters.'; } if (description.length > 2000) { errors.description = 'Description must be at most 2000 characters.'; } if (!PRIORITIES.includes(input.priority)) { errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`; } if (buildingId === null) { errors.building_id = 'Choose a building.'; } return { errors, values: { title, description, priority: input.priority, building_id: buildingId } };} async function renderIssueForm(res, status, { values = {}, errors = {} } = {}) { const buildings = await listBuildings(); res.status(status).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES, buildings });} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/issues', async (req, res) => { const issues = await listIssues(); res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', async (req, res) => { await renderIssueForm(res, 200);}); app.post('/issues', async (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return renderIssueForm(res, 400, { values, errors }); } let issue; try { issue = await createIssue(values); } catch (err) { if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) { return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } }); } throw err; } res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', async (req, res) => { const id = parseId(req.params.id); const issue = id === null ? null : await findIssue(id); if (!issue) { return res.status(404).render('not-found', { title: 'Not found', path: req.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { res.status(404).render('not-found', { title: 'Not found', path: req.path });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; res.status(status).render('error', { title: 'Error', status, message });});import express from 'express';
import path from 'node:path';
import { listIssues, findIssue, createIssue } from './models/issues.js';
import { listBuildings } from './models/buildings.js';
import { PG_ERRORS } from './db.js';
export const app = express();
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.use((req, res, next) => {
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)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.urlencoded({ extended: false }));
const PRIORITIES = ['low', 'medium', 'high', 'critical'];
const MAX_INTEGER = 2147483647;
// Returns a positive integer that fits a PostgreSQL integer column, or null.
function parseId(value) {
if (typeof value !== 'string' || !/^[1-9][0-9]{0,9}$/.test(value)) {
return null;
}
const id = Number(value);
return id <= MAX_INTEGER ? id : null;
}
function validateIssue(input) {
const errors = {};
const title = typeof input.title === 'string' ? input.title.trim() : '';
const description = typeof input.description === 'string' ? input.description.trim() : '';
const buildingId = parseId(input.building_id);
if (title.length < 3 || title.length > 200) {
errors.title = 'Title must be between 3 and 200 characters.';
}
if (description.length > 2000) {
errors.description = 'Description must be at most 2000 characters.';
}
if (!PRIORITIES.includes(input.priority)) {
errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;
}
if (buildingId === null) {
errors.building_id = 'Choose a building.';
}
return { errors, values: { title, description, priority: input.priority, building_id: buildingId } };
}
async function renderIssueForm(res, status, { values = {}, errors = {} } = {}) {
const buildings = await listBuildings();
res.status(status).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES, buildings });
}
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.get('/issues', async (req, res) => {
const issues = await listIssues();
res.render('issues/index', { title: 'Maintenance issues', issues });
});
app.get('/issues/new', async (req, res) => {
await renderIssueForm(res, 200);
});
app.post('/issues', async (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return renderIssueForm(res, 400, { values, errors });
}
let issue;
try {
issue = await createIssue(values);
} catch (err) {
if (err.code === PG_ERRORS.FOREIGN_KEY_VIOLATION) {
return renderIssueForm(res, 400, { values, errors: { building_id: 'Choose a building.' } });
}
throw err;
}
res.redirect(303, `/issues/${issue.id}`);
});
app.get('/issues/:id', async (req, res) => {
const id = parseId(req.params.id);
const issue = id === null ? null : await findIssue(id);
if (!issue) {
return res.status(404).render('not-found', { title: 'Not found', path: req.path });
}
res.render('issues/show', { title: issue.title, issue });
});
app.use((req, res) => {
res.status(404).render('not-found', { title: 'Not found', path: req.path });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
res.status(status).render('error', { title: 'Error', status, message });
});
- We do not ask "does building 999 exist?" before inserting. Between that check and the insert, another request could delete the building. The constraint is checked atomically by the insert itself, so we let the database decide and translate its answer.
- Any other error is re-thrown with
throw err, so it still reaches the error handler and the log. Never swallow errors you did not expect.
5. Tests for the new behaviour
Add two tests at the end of test/issues.test.js:
assert.match(page.text, /Water leak by the staff entrance/);}); test('POST /issues with a building that does not exist is a form error, not a 500', async () => { const res = await request(app).post('/issues').type('form').send({ title: 'Ghost issue', building_id: '999', priority: 'low' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('the stored row has the cleaned values', async () => { await request(app).post('/issues').type('form').send({ title: ' Spaces around ', building_id: '20', priority: 'medium', status: 'closed' }); const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'"); assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);});
Show the whole test/issues.test.js after this change
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 { resetDatabase } from './helpers.js'; before(resetDatabase);after(() => pool.end()); test('GET /issues lists issues from the database', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('GET /issues/101 shows one issue with its building', async () => { const res = await request(app).get('/issues/101'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/); assert.match(res.text, /Dublin Offices/);}); test('GET /issues/:id answers 404 for unknown or malformed ids', async () => { for (const id of ['999999', 'abc', '0', '99999999999']) { const res = await request(app).get(`/issues/${id}`); assert.equal(res.status, 404, `id ${id}`); }}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building_id: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('POST /issues stores the issue and redirects to it', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building_id: '10', priority: 'low' }); assert.equal(res.status, 303); const page = await request(app).get(res.headers.location); assert.equal(page.status, 200); assert.match(page.text, /Water leak by the staff entrance/);}); test('POST /issues with a building that does not exist is a form error, not a 500', async () => { const res = await request(app).post('/issues').type('form').send({ title: 'Ghost issue', building_id: '999', priority: 'low' }); assert.equal(res.status, 400); assert.match(res.text, /Choose a building/);}); test('the stored row has the cleaned values', async () => { await request(app).post('/issues').type('form').send({ title: ' Spaces around ', building_id: '20', priority: 'medium', status: 'closed' }); const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'"); assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);});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 { resetDatabase } from './helpers.js';
before(resetDatabase);
after(() => pool.end());
test('GET /issues lists issues from the database', async () => {
const res = await request(app).get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('GET /issues/101 shows one issue with its building', async () => {
const res = await request(app).get('/issues/101');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Lift stuck between floors 2 and 3<\/h1>/);
assert.match(res.text, /Dublin Offices/);
});
test('GET /issues/:id answers 404 for unknown or malformed ids', async () => {
for (const id of ['999999', 'abc', '0', '99999999999']) {
const res = await request(app).get(`/issues/${id}`);
assert.equal(res.status, 404, `id ${id}`);
}
});
test('POST /issues re-renders the form with errors', async () => {
const res = await request(app).post('/issues').type('form').send({ title: '', building_id: '', priority: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Choose a building/);
});
test('POST /issues stores the issue and redirects to it', async () => {
const res = await request(app)
.post('/issues')
.type('form')
.send({ title: 'Water leak by the staff entrance', building_id: '10', priority: 'low' });
assert.equal(res.status, 303);
const page = await request(app).get(res.headers.location);
assert.equal(page.status, 200);
assert.match(page.text, /Water leak by the staff entrance/);
});
test('POST /issues with a building that does not exist is a form error, not a 500', async () => {
const res = await request(app).post('/issues').type('form').send({ title: 'Ghost issue', building_id: '999', priority: 'low' });
assert.equal(res.status, 400);
assert.match(res.text, /Choose a building/);
});
test('the stored row has the cleaned values', async () => {
await request(app).post('/issues').type('form').send({ title: ' Spaces around ', building_id: '20', priority: 'medium', status: 'closed' });
const { rows } = await pool.query("SELECT title, building_id, status FROM issues WHERE title = 'Spaces around'");
assert.deepEqual(rows, [{ title: 'Spaces around', building_id: 20, status: 'open' }]);
});
The second test checks the database, not just the page: the title is trimmed, and the extra status: 'closed' field sent by the client was ignored because we only insert validated values.
Run and inspect
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ GET /issues lists issues from the database (85.646417ms)
✔ GET /issues/101 shows one issue with its building (3.610916ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (8.295917ms)
✔ POST /issues re-renders the form with errors (9.433834ms)
✔ POST /issues stores the issue and redirects to it (6.818208ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (10.102875ms)
✔ the stored row has the cleaned values (3.674917ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 296.717333
Prove that the development database was not touched:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT id, title FROM issues WHERE title LIKE 'Water leak by%';
id | title
----+-------
(0 rows)And the test database has exactly what the last test run left behind:
docker compose exec db psql -U caretaker caretaker_test, then paste the SQL.SELECT id, title FROM issues WHERE id > 130 ORDER BY id;
id | title
-----+----------------------------------
131 | Water leak by the staff entrance
133 | Spaces around
(2 rows)The next npm test resets it again before running.
Experiment
Why do we always write $1 instead of putting values into the SQL text? Create a throwaway script that does it both ways. It searches issue titles within building 30 only, the kind of tenant-scoped query this course is about:
import pg from 'pg'; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });const search = process.argv[2]; const unsafeSql = `SELECT id, building_id, title FROM issues WHERE building_id = 30 AND title ILIKE '%${search}%'`;console.log('unsafe SQL text:', unsafeSql);const unsafe = await pool.query(unsafeSql);console.log('unsafe rows:', unsafe.rowCount, 'buildings:', [...new Set(unsafe.rows.map((r) => r.building_id))].join(',')); const safe = await pool.query( "SELECT id, building_id, title FROM issues WHERE building_id = 30 AND title ILIKE '%' || $1 || '%'", [search],);console.log('safe rows:', safe.rowCount); await pool.end();An honest search first:
node --env-file=.env injection-demo.js boiler
unsafe SQL text: SELECT id, building_id, title FROM issues WHERE building_id = 30 AND title ILIKE '%boiler%'
unsafe rows: 1 buildings: 30
safe rows: 1
' OR true --. How many rows will each query return?node --env-file=.env injection-demo.js "' OR true --"
unsafe SQL text: SELECT id, building_id, title FROM issues WHERE building_id = 30 AND title ILIKE '%' OR true --%'
unsafe rows: 30 buildings: 10,20,30,40
safe rows: 0
Reveal What happened
Read the printed SQL. The quote in the input closed the string literal, OR true became SQL, and -- turned the rest of the line into a comment. The WHERE clause became (building_id = 30 AND title ILIKE '%') OR true: every issue from every building and every organisation. In a multi-tenant app that is a complete isolation failure, from one text box.
The parameterized query sent the same characters as a value. PostgreSQL compared titles with the literal text ' OR true -- and found nothing. The value never becomes SQL, whatever it contains. That is why every query in Caretaker uses placeholders for values, and why, for the table name in the seed, we used a fixed list in code.
Delete the demo file; it does not belong in the project:
rm injection-demo.js
Checkpoint
npm test
> caretaker@1.0.0 test
> node --env-file=.env.test --test --test-concurrency=1 --test-reporter=spec "test/**/*.test.js"
✔ GET /issues lists issues from the database (63.475375ms)
✔ GET /issues/101 shows one issue with its building (3.301833ms)
✔ GET /issues/:id answers 404 for unknown or malformed ids (7.481ms)
✔ POST /issues re-renders the form with errors (8.649875ms)
✔ POST /issues stores the issue and redirects to it (5.987167ms)
✔ POST /issues with a building that does not exist is a form error, not a 500 (9.221084ms)
✔ the stored row has the cleaned values (3.689167ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 243.851084
git add -A
git commit -m "Give tests their own database; map constraint errors to form errors"
[main b6803bb] Give tests their own database; map constraint errors to form errors
6 files changed, 56 insertions(+), 3 deletions(-)
create mode 100644 .env.test
create mode 100644 test/helpers.js
Symptom Refusing to reset postgres://.../caretaker
The tests read .env instead of .env.test. Check the test script in package.json.
Symptom database "caretaker_test" does not exist
The init script did not run (lesson 2.1). Recreate the volume with docker compose down -v && docker compose up -d --wait, then npm run db:migrate && npm run db:seed.
Symptom Tests hang for about 10 seconds after finishing
A test file does not call pool.end() in an after hook, so idle pooled connections keep Node alive.
Recap and next step
Tests now own a separate database that is migrated and seeded before each test file, with a guard that refuses any other database. Constraint violations become friendly form errors by checking err.code, while unexpected errors still reach the error handler. And you saw SQL injection turn a building-scoped query into a cross-tenant leak, and placeholders stop it.
Module 2 is complete: data persists, the schema enforces structure, and every query is parameterized. In Module 3 we build out the rest of the application (organisations, buildings, full issue CRUD, lists with paging and filters, and inspections with a real state machine).
Open the checkpoint files for lesson 2.6 (separate page; only files from this lesson and earlier)