fix(db): stop losing secrets and notes to the boot and migration paths

An unreadable or empty encryption-key file was treated the same as a missing
one: regenerate and overwrite. That is the one case where regenerating is
the worst possible move - every secret already at rest becomes undecryptable,
permanently. Both now refuse to start and say which file to fix.

The key-rotation script advertised re-encrypting all stored secrets while its
hardcoded column lists had drifted: the AirTrail key, the per-user LLM key
and the plugin OAuth tokens were never migrated, so they silently stopped
decrypting after a rotation. The parity test now pins the full set against
what the code actually encrypts, rather than two tables of it.

The schema_version bump ran outside the migration's transaction, so a crash
in between left the schema advanced and the version stale - the next boot
replayed a non-idempotent step and exited, turning one crash into a boot
loop. And the TICKETJSON receipt migration matched with LIKE, which SQLite
treats case-insensitively, so a note somebody had typed starting 'ticketjson:'
was cut up and its text dropped.

Also: APP_VERSION was interpolated into migration SQL instead of bound, the
capture-metadata backfill passed (photoId, userId) to a (userId, photoId)
signature and its mock keyed on the wrong argument, TRUST_PROXY=0 was
accepted and silently coerced to 1, demo-reset hardcoded the db path instead
of honouring TREK_DB_FILE, and a demo instance with no DEMO_ADMIN_PASS set
now says out loud that its admin password is the published default.
This commit is contained in:
Maurice
2026-08-23 09:48:12 +02:00
committed by Maurice
parent 8e5fdaa877
commit a7aaa29c16
17 changed files with 699 additions and 16 deletions
@@ -0,0 +1,57 @@
/**
* Boot migration: move the itemized receipt out of budget_items.note (#1658).
*
* The costs UI stored the receipt as a `TICKETJSON:` prefix on the note, so the
* migration lifts it into its own column and clears the note. The match has to
* be case-SENSITIVE: LIKE is not, which would swallow a hand-written note that
* happens to start with the same word.
*/
import { describe, it, expect } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function makeDbWithNotes(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
// Minimal FK chain: user -> trip -> budget_items rows.
db.prepare("INSERT INTO users (id, username, email, password_hash) VALUES (1, 'u', 'u@example.test', 'x')").run();
db.prepare("INSERT INTO trips (id, user_id, title) VALUES (1, 1, 'T')").run();
db.prepare(
'INSERT INTO budget_items (id, trip_id, name, note) VALUES (1, 1, ?, ?), (2, 1, ?, ?)',
).run('Dinner', 'TICKETJSON:{"items":[]}', 'Museum', 'ticketjson: buy at the door');
return db;
}
describe('budget_items ticket_json migration', () => {
it('moves a real receipt into ticket_json and clears the note', () => {
const db = makeDbWithNotes();
try {
runMigrations(db);
const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 1').get() as {
note: string | null;
ticket_json: string | null;
};
expect(row).toEqual({ note: null, ticket_json: '{"items":[]}' });
} finally {
db.close();
}
});
it('leaves a lowercase note alone (LIKE would have eaten it)', () => {
const db = makeDbWithNotes();
try {
runMigrations(db);
const row = db.prepare('SELECT note, ticket_json FROM budget_items WHERE id = 2').get() as {
note: string | null;
ticket_json: string | null;
};
expect(row).toEqual({ note: 'ticketjson: buy at the door', ticket_json: null });
} finally {
db.close();
}
});
});
@@ -12,6 +12,7 @@
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { execFileSync } from 'node:child_process';
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -47,6 +48,40 @@ const storageBackendsSection = (() => {
return script.slice(start, end);
})();
// The users loop only, bounded by its own marker and the next section.
const usersSection = (() => {
const start = script.indexOf('--- users:');
expect(start).toBeGreaterThan(-1);
const end = script.indexOf('--- app_settings: storage.backends ---', start);
expect(end).toBeGreaterThan(start);
return script.slice(start, end);
})();
// The per-user settings loop only.
const settingsSection = (() => {
const start = script.indexOf('--- settings:');
expect(start).toBeGreaterThan(-1);
const end = script.indexOf('--- plugins:', start);
expect(end).toBeGreaterThan(start);
return script.slice(start, end);
})();
// ENCRYPTED_SETTING_KEYS is module-private in settings.service.ts, so the
// canonical list is read off the source rather than imported.
const canonicalSettingKeys = (() => {
const source = fs.readFileSync(path.join(SERVER_ROOT, 'src', 'nest', 'settings', 'settings.service.ts'), 'utf8');
const marker = 'const ENCRYPTED_SETTING_KEYS = new Set([';
const start = source.indexOf(marker);
expect(start).toBeGreaterThan(-1);
const end = source.indexOf(']', start + marker.length);
return source
.slice(start + marker.length, end)
.split(',')
.map((part) => part.trim())
.filter(Boolean)
.map((quoted) => quoted.slice(1, -1));
})();
describe('migrate-encryption.ts app_settings parity', () => {
it('ROTPAR-001: rotates every instance-wide API key', () => {
for (const name of INSTANCE_API_KEY_NAMES) {
@@ -71,6 +106,36 @@ describe('migrate-encryption.ts app_settings parity', () => {
expect(storageBackendsSection).toContain(`'${field}'`);
}
});
// airtrail.service.ts stores the key with maybe_encrypt_api_key, i.e. the same
// enc:v1: scheme; missed by a rotation the integration reads back as unset.
it('ROTPAR-006: rotates the per-user AirTrail key', () => {
const airtrail = fs.readFileSync(
path.join(SERVER_ROOT, 'src', 'nest', 'integrations', 'airtrail.service.ts'),
'utf8',
);
expect(airtrail).toContain('maybe_encrypt_api_key');
expect(airtrail).toContain('airtrail_api_key');
expect(usersSection).toContain("'airtrail_api_key'");
});
it('ROTPAR-007: rotates every encrypted per-user setting key', () => {
expect(canonicalSettingKeys.length).toBeGreaterThan(0);
for (const key of canonicalSettingKeys) {
expect(settingsSection).toContain(`'${key}'`);
}
});
// Both plugin secret stores use the same scheme: OAuth tokens encrypted by
// plugin-oauth.service, and the config fields a manifest marked secret.
it('ROTPAR-008: rotates the plugin OAuth tokens and both config stores', () => {
expect(script).toContain('plugin_oauth_tokens');
expect(script).toContain('access_token');
expect(script).toContain('refresh_token');
expect(script).toContain('plugin_settings_fields');
expect(script).toContain("UPDATE plugins SET config = ?");
expect(script).toContain('plugin_user_config');
});
});
describe('migrate-encryption.ts storage.backends: malformed shape', () => {
@@ -132,3 +197,117 @@ describe('migrate-encryption.ts storage.backends: malformed shape', () => {
expect(output).toContain('app_settings.storage.backends: not an array — skipping');
}, 30000);
});
// The same enc:v1: scheme the app and the script share, so a fixture can be
// written under the OLD key and read back under the NEW one.
const ENCRYPTED_PREFIX = 'enc:v1:';
const apiKeyFor = (key: string) => crypto.createHash('sha256').update(`${key}:api_keys:v1`).digest();
function encryptWith(key: string, plain: string): string {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', apiKeyFor(key), iv);
const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, cipher.getAuthTag(), enc]).toString('base64')}`;
}
function decryptWith(key: string, value: string): string | null {
if (!value.startsWith(ENCRYPTED_PREFIX)) return null;
try {
const buf = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64');
const decipher = crypto.createDecipheriv('aes-256-gcm', apiKeyFor(key), buf.subarray(0, 12));
decipher.setAuthTag(buf.subarray(12, 28));
return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8');
} catch {
return null;
}
}
const BASE_SCHEMA = `
CREATE TABLE users (
id INTEGER PRIMARY KEY,
maps_api_key TEXT, unsplash_api_key TEXT, openweather_api_key TEXT,
immich_api_key TEXT, synology_password TEXT, synology_sid TEXT,
synology_did TEXT, airtrail_api_key TEXT, mfa_secret TEXT
);
CREATE TABLE app_settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE settings (user_id INTEGER, key TEXT, value TEXT);
CREATE TABLE trip_album_links (id INTEGER PRIMARY KEY, passphrase TEXT);
CREATE TABLE trek_photos (id INTEGER PRIMARY KEY, passphrase TEXT);
CREATE TABLE plugins (id TEXT PRIMARY KEY, config TEXT);
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);
CREATE TABLE plugin_oauth_tokens (
plugin_id TEXT, user_id INTEGER, access_token TEXT, refresh_token TEXT,
PRIMARY KEY (plugin_id, user_id)
);
CREATE TABLE plugin_user_config (plugin_id TEXT, user_id INTEGER, config TEXT);
`;
describe('migrate-encryption.ts rotates the stores the app writes', () => {
let tmpDir: string;
let dbPath: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-migrate-encryption-plugins-'));
dbPath = path.join(tmpDir, 'travel.db');
});
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('ROTPAR-009: re-encrypts AirTrail, llm_api_key, plugin OAuth tokens and plugin configs', () => {
const seed = new Database(dbPath);
seed.exec(BASE_SCHEMA);
seed.prepare('INSERT INTO users (id, airtrail_api_key) VALUES (1, ?)').run(encryptWith('old-key', 'at-token'));
seed.prepare('INSERT INTO settings (user_id, key, value) VALUES (1, ?, ?)').run('llm_api_key', encryptWith('old-key', 'sk-llm'));
seed.prepare('INSERT INTO plugins (id, config) VALUES (?, ?)').run(
'koffi',
JSON.stringify({ api_key: encryptWith('old-key', 'plugin-secret'), server: 'https://h' }),
);
seed.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)').run('koffi', 'api_key', 'instance', 1);
seed.prepare('INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES (?, ?, ?, ?)').run('koffi', 'token', 'user', 1);
seed.prepare('INSERT INTO plugin_user_config (plugin_id, user_id, config) VALUES (?, ?, ?)').run(
'koffi',
1,
JSON.stringify({ token: encryptWith('old-key', 'user-secret') }),
);
seed.prepare('INSERT INTO plugin_oauth_tokens (plugin_id, user_id, access_token, refresh_token) VALUES (?, ?, ?, ?)').run(
'koffi',
1,
encryptWith('old-key', 'access'),
encryptWith('old-key', 'refresh'),
);
seed.close();
execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {
cwd: SERVER_ROOT,
env: { ...process.env, DB_PATH: dbPath },
input: ['old-key', 'new-key', 'yes', ''].join(String.fromCharCode(10)),
stdio: 'pipe',
encoding: 'utf8',
});
const after = new Database(dbPath, { readonly: true });
const airtrail = (after.prepare('SELECT airtrail_api_key AS v FROM users WHERE id = 1').get() as { v: string }).v;
expect(decryptWith('new-key', airtrail)).toBe('at-token');
const llm = (after.prepare("SELECT value AS v FROM settings WHERE key = 'llm_api_key'").get() as { v: string }).v;
expect(decryptWith('new-key', llm)).toBe('sk-llm');
const tokens = after.prepare('SELECT access_token, refresh_token FROM plugin_oauth_tokens').get() as {
access_token: string;
refresh_token: string;
};
expect(decryptWith('new-key', tokens.access_token)).toBe('access');
expect(decryptWith('new-key', tokens.refresh_token)).toBe('refresh');
const pluginConfig = JSON.parse((after.prepare("SELECT config AS v FROM plugins WHERE id = 'koffi'").get() as { v: string }).v);
expect(decryptWith('new-key', pluginConfig.api_key)).toBe('plugin-secret');
// A non-secret field is left exactly as it was.
expect(pluginConfig.server).toBe('https://h');
const userConfig = JSON.parse((after.prepare('SELECT config AS v FROM plugin_user_config').get() as { v: string }).v);
expect(decryptWith('new-key', userConfig.token)).toBe('user-secret');
after.close();
}, 30000);
});
@@ -0,0 +1,55 @@
/**
* The schema_version bump must commit with the migration that earned it.
*
* If it lands in a statement of its own, a crash between the two leaves the
* schema advanced and the version stale, and the next boot replays a step that
* is not idempotent (an INSERT INTO app_settings, say) and exits 1 forever.
*/
import { describe, it, expect, vi } from 'vitest';
import Database from 'better-sqlite3';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
function migratedDb(): Database.Database {
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA busy_timeout = 5000');
db.exec('PRAGMA foreign_keys = ON');
createTables(db);
runMigrations(db);
return db;
}
describe('migration version bump atomicity', () => {
it('MIGRATE-ATOMIC-001: writes schema_version inside the migration transaction', () => {
const db = migratedDb();
try {
const { version } = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number };
// Rewind one slot so exactly the last migration replays.
db.prepare('UPDATE schema_version SET version = ?').run(version - 1);
const realPrepare = db.prepare.bind(db);
const inTransaction: boolean[] = [];
vi.spyOn(db, 'prepare').mockImplementation(((sql: string) => {
const stmt = realPrepare(sql);
if (sql.includes('UPDATE schema_version SET version')) {
const realRun = stmt.run.bind(stmt);
stmt.run = ((...args: unknown[]) => {
inTransaction.push(db.inTransaction);
return realRun(...(args as never[]));
}) as typeof stmt.run;
}
return stmt;
}) as typeof db.prepare);
runMigrations(db);
expect(inTransaction).toEqual([true]);
const after = db.prepare('SELECT version FROM schema_version LIMIT 1').get() as { version: number };
expect(after.version).toBe(version);
} finally {
vi.restoreAllMocks();
db.close();
}
});
});