7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(db-backup): restrict the backup blob and the restored database (#796)
OhOkThisIsFinef2ff8d38db78
diff --git a/server/src/__tests__/lib/db-backup.test.ts b/server/src/__tests__/lib/db-backup.test.tsindex 2c840772..6341cc02 100644--- a/server/src/__tests__/lib/db-backup.test.ts+++ b/server/src/__tests__/lib/db-backup.test.ts@@ -4,6 +4,7 @@ import path from 'path';import Database from 'better-sqlite3';import { afterEach, describe, expect, it } from 'vitest';import { backupDbNow, restoreDbBackupIfNeeded } from '../../lib/db-backup.js';+import { aclEntries } from '../helpers/acl.js';const ORIGINAL_BACKUP_PATH = process.env.FREEAPI_DB_BACKUP_PATH;const ORIGINAL_BACKUP_TARGET = process.env.FREEAPI_DB_BACKUP_TARGET;@@ -52,3 +53,78 @@ describe('encrypted SQLite backup', () => {restored.close();});});++describe('backup file permissions', () => {+ // The blob is AES-256-GCM encrypted and the restored file is a plain SQLite+ // database, but both live on a host that also holds the key — usually in a+ // .env in the same tree — so neither may be left world-readable.+ //+ // As elsewhere, each platform asserts what it can actually enforce: Node+ // synthesizes a 0o666 mode on Windows regardless of the ACL, so a POSIX-mode+ // assertion there would pass or fail for reasons unrelated to the guarantee.+ const isWindows = process.platform === 'win32';+ const itPosix = it.skipIf(isWindows);+ const itWindows = it.skipIf(!isWindows);++ afterEach(() => restoreEnv());++ async function backupInto(dir: string): Promise<string> {+ const dbPath = path.join(dir, 'freeapi.db');+ const backupPath = path.join(dir, 'backup.bin');+ process.env.ENCRYPTION_KEY = 'a'.repeat(64);+ process.env.FREEAPI_DB_BACKUP_PATH = backupPath;++ const db = new Database(dbPath);+ db.exec('CREATE TABLE items (name TEXT NOT NULL)');+ await backupDbNow(db, dbPath);+ db.close();+ return backupPath;+ }++ itPosix('writes the backup blob owner-only', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-backup-perms-'));+ const backupPath = await backupInto(dir);++ expect(fs.statSync(backupPath).mode & 0o077).toBe(0);+ });++ itPosix('tightens a backup target that already existed', async () => {+ // writeFileSync's mode argument only applies when the file is created, so+ // every backup after the first overwrites a file that keeps whatever mode+ // it already had. Without the explicit restrict call this is the case that+ // stays group-readable forever.+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-backup-perms-'));+ const backupPath = path.join(dir, 'backup.bin');+ fs.writeFileSync(backupPath, 'stale');+ // chmod rather than a creation mode: the mode argument is filtered through+ // the runner's umask, so a strict umask would leave this pre-condition+ // asserting the very thing it means to rule out.+ fs.chmodSync(backupPath, 0o644);+ expect(fs.statSync(backupPath).mode & 0o077).not.toBe(0);++ await backupInto(dir);++ expect(fs.statSync(backupPath).mode & 0o077).toBe(0);+ });++ itPosix('writes the restored database owner-only', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-backup-perms-'));+ const dbPath = path.join(dir, 'freeapi.db');+ await backupInto(dir);+ fs.rmSync(dbPath);++ // The restore lands before connectDb runs, and sometimes in a different+ // process entirely; the decrypted database must not be readable in between.+ expect((await restoreDbBackupIfNeeded(dbPath)).restored).toBe(true);+ expect(fs.statSync(dbPath).mode & 0o077).toBe(0);+ });++ itWindows('replaces the inherited ACL on the backup blob', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-backup-perms-'));+ const backupPath = await backupInto(dir);++ const entries = aclEntries(backupPath);+ expect(entries.filter(e => e.includes('(I)'))).toEqual([]);+ expect(entries).toHaveLength(3);+ });+});diff --git a/server/src/lib/db-backup.ts b/server/src/lib/db-backup.tsindex b855fa45..f988d4a8 100644--- a/server/src/lib/db-backup.ts+++ b/server/src/lib/db-backup.ts@@ -5,6 +5,7 @@ import { gzipSync, gunzipSync } from 'zlib';import type { Db } from '../db/types.js';import type { Scheduler } from './scheduler.js';import { getDefaultDbPath } from '../db/index.js';+import { restrictToOwner } from './file-permissions.js';const MAGIC = Buffer.from('FAPIBK1\0');const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;@@ -107,7 +108,15 @@ async function writeTarget(target: string, payload: Buffer): Promise<void> {}fs.mkdirSync(path.dirname(path.resolve(target)), { recursive: true });- fs.writeFileSync(target, payload);+ // Encrypted, but not therefore safe to leave world-readable: the key is+ // FREEAPI_DB_BACKUP_KEY or ENCRYPTION_KEY, which on a normal install sits in a+ // .env file on the same host. The mode covers creation; restrictToOwner covers+ // the overwrite case, where an existing file keeps the mode it already had —+ // and covers Windows, where the mode argument is a no-op.+ fs.writeFileSync(target, payload, { mode: 0o600 });+ if (!restrictToOwner(target)) {+ console.warn(`[db-backup] could not restrict permissions on ${target} — it may be readable by other local accounts`);+ }}export async function restoreDbBackupIfNeeded(dbPath = getDefaultDbPath()): Promise<DbBackupResult> {@@ -128,7 +137,13 @@ export async function restoreDbBackupIfNeeded(dbPath = getDefaultDbPath()): Prom}fs.mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true });- fs.writeFileSync(dbPath, restored);+ // This is the decrypted database — provider keys and the dashboard password+ // hash in the clear. connectDb hardens it too, but that is a later call and+ // sometimes a later process; the file must not be readable in between.+ fs.writeFileSync(dbPath, restored, { mode: 0o600 });+ if (!restrictToOwner(dbPath)) {+ console.warn(`[db-backup] could not restrict permissions on the restored database at ${dbPath}`);+ }console.log(`[db-backup] restored ${restored.length} bytes from ${target}`);return { ok: true, target, bytes: restored.length, restored: true };}