Skip to content

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): harden the data directory so WAL sidecars are covered (#795)

OhOkThisIsFinea6f7718a7bd2
diff --git a/.env.example b/.env.example
index 335e1d82..618b352e 100644
--- a/.env.example
+++ b/.env.example
@@ -173,6 +173,15 @@ REQUEST_ANALYTICS_MAX_ROWS=100000
# persistently, or when you want to keep the DB outside server/data.
# FREEAPI_DB_PATH=/app/server/data/freellmapi.db
+# Whether to restrict the directory holding the database to this account, so the
+# SQLite -wal/-shm sidecars are protected too (they are created on first write,
+# after any startup permission check could reach them). Done automatically for
+# the default server/data directory and for any directory FreeLLMAPI creates
+# itself; skipped for a FREEAPI_DB_PATH pointing somewhere pre-existing, since
+# that may be a shared location this server should not be locking down. Set to 1
+# if the directory belongs to this account alone, or 0 to disable entirely.
+# FREEAPI_DB_DIR_HARDENING=1
+
# Optional encrypted SQLite backup. On startup, FreeLLMAPI restores this backup
# if the configured DB file is missing; while running, it uploads a fresh backup
# periodically. File paths and HTTP(S) URLs are supported.
diff --git a/server/src/__tests__/db/hardening.test.ts b/server/src/__tests__/db/hardening.test.ts
index 56504c59..638ced53 100644
--- a/server/src/__tests__/db/hardening.test.ts
+++ b/server/src/__tests__/db/hardening.test.ts
@@ -2,7 +2,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { describe, it, expect, afterEach } from 'vitest';
-import { connectDb } from '../../db/index.js';
+import { connectDb, getDefaultDbPath, shouldHardenDataDir } from '../../db/index.js';
import { aclEntries } from '../helpers/acl.js';
const isWindows = process.platform === 'win32';
@@ -10,6 +10,10 @@ const itPosix = it.skipIf(isWindows);
const itWindows = it.skipIf(!isWindows);
const created: string[] = [];
+const createdDirs: string[] = [];
+
+const ORIGINAL_DIR_HARDENING = process.env.FREEAPI_DB_DIR_HARDENING;
+const ORIGINAL_DB_PATH = process.env.FREEAPI_DB_PATH;
function tempDbPath(): string {
const p = path.join(os.tmpdir(), `freeapi-hardening-${Date.now()}-${Math.random()}.db`);
@@ -17,12 +21,37 @@ function tempDbPath(): string {
return p;
}
+/** A directory that already exists, like a mounted volume or a shared temp dir:
+ * connectDb finds it rather than creating it. */
+function existingDir(): string {
+ const p = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-hardening-existing-'));
+ createdDirs.push(p);
+ return p;
+}
+
+/** A path connectDb has to create, which is what earns it the right to harden
+ * it. Returns the not-yet-existent directory and the DB path inside it. */
+function unbornDataDir(): { dataDir: string; dbPath: string } {
+ const parent = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-hardening-parent-'));
+ createdDirs.push(parent);
+ const dataDir = path.join(parent, 'data');
+ return { dataDir, dbPath: path.join(dataDir, 'freeapi.db') };
+}
+
afterEach(() => {
+ if (ORIGINAL_DIR_HARDENING === undefined) delete process.env.FREEAPI_DB_DIR_HARDENING;
+ else process.env.FREEAPI_DB_DIR_HARDENING = ORIGINAL_DIR_HARDENING;
+ if (ORIGINAL_DB_PATH === undefined) delete process.env.FREEAPI_DB_PATH;
+ else process.env.FREEAPI_DB_PATH = ORIGINAL_DB_PATH;
+
for (const p of created.splice(0)) {
for (const suffix of ['', '-wal', '-shm']) {
try { fs.unlinkSync(`${p}${suffix}`); } catch { /* best effort */ }
}
}
+ for (const p of createdDirs.splice(0)) {
+ try { fs.rmSync(p, { recursive: true, force: true }); } catch { /* best effort */ }
+ }
});
describe('database runtime hardening', () => {
@@ -116,9 +145,10 @@ describe('database runtime hardening', () => {
// Windows leg say so rather than pretending it verified something.
//
// Note what the reconnect above buys, and what it does not: it proves the
- // pass restricts sidecars THAT ALREADY EXIST. A real server never gets
- // here — it opens once, and SQLite creates the sidecars afterwards on the
- // first write. See the known gap on restrictDbFilePermissions.
+ // file pass restricts sidecars THAT ALREADY EXIST, which is the unclean
+ // shutdown case. It says nothing about a normal start, where the sidecars
+ // appear after connectDb has already been and gone — that is what the
+ // "data directory" block below covers.
expect(checked).toBeGreaterThan(0);
});
@@ -135,3 +165,123 @@ describe('database runtime hardening', () => {
expect(() => connectDb(':memory:')).not.toThrow();
});
});
+
+describe('data directory hardening policy', () => {
+ it('claims a directory it just created', () => {
+ expect(shouldHardenDataDir(existingDir(), true)).toBe(true);
+ });
+
+ it('claims the built-in default data directory, so upgrades are covered too', () => {
+ // An install that predates this change already has server/data, so it never
+ // hits the "we created it" case. Without this leg the fix would reach new
+ // installs only.
+ delete process.env.FREEAPI_DB_PATH;
+ expect(shouldHardenDataDir(path.dirname(getDefaultDbPath()), false)).toBe(true);
+ });
+
+ it('matches the default directory case-insensitively on Windows', () => {
+ delete process.env.FREEAPI_DB_PATH;
+ const defaultDir = path.dirname(getDefaultDbPath());
+ expect(shouldHardenDataDir(defaultDir.toUpperCase(), false, 'win32')).toBe(true);
+ // POSIX paths really are case-sensitive; the same leniency there would be a bug.
+ expect(shouldHardenDataDir(defaultDir.toUpperCase(), false, 'linux')).toBe(false);
+ });
+
+ it('refuses a pre-existing directory it was merely pointed at', () => {
+ // The whole reason this predicate exists: FREEAPI_DB_PATH=/tmp/freeapi.db
+ // must never end in chmod 0700 /tmp.
+ expect(shouldHardenDataDir(os.tmpdir(), false)).toBe(false);
+ expect(shouldHardenDataDir(existingDir(), false)).toBe(false);
+ });
+
+ it('lets an operator force it on for a directory of their own', () => {
+ process.env.FREEAPI_DB_DIR_HARDENING = '1';
+ expect(shouldHardenDataDir(os.tmpdir(), false)).toBe(true);
+ });
+
+ it('lets an operator force it off even where the default would apply', () => {
+ process.env.FREEAPI_DB_DIR_HARDENING = '0';
+ expect(shouldHardenDataDir(existingDir(), true)).toBe(false);
+ });
+
+ it('ignores a value it cannot interpret rather than guessing', () => {
+ process.env.FREEAPI_DB_DIR_HARDENING = 'maybe';
+ expect(shouldHardenDataDir(os.tmpdir(), false)).toBe(false);
+ expect(shouldHardenDataDir(existingDir(), true)).toBe(true);
+ });
+});
+
+describe('WAL sidecars on a normal start', () => {
+ // The case the file-by-file pass structurally cannot reach. SQLite creates
+ // -wal/-shm on the first write and deletes them on the last clean close, so
+ // on a real start there is nothing to harden by the time connectDb looks —
+ // and a real server, unlike the tests above, never reconnects to get a second
+ // chance. Only the directory can carry the restriction forward.
+ //
+ // Each leg asserts the guarantee its own OS actually expresses, because the
+ // two platforms reach it by genuinely different mechanisms: Windows inherits
+ // the ACL onto the new child, while POSIX never propagates modes and instead
+ // makes the child unreachable by clearing the directory's search bit.
+
+ function connectAndWrite(dbPath: string): void {
+ const db = connectDb(dbPath);
+ // Deliberately no second connectDb: this must hold for a process that opens
+ // the database exactly once, which is what the server does.
+ db.exec('CREATE TABLE IF NOT EXISTS probe (id INTEGER PRIMARY KEY)');
+ db.exec('INSERT INTO probe (id) VALUES (1)');
+ }
+
+ function sidecars(dbPath: string): string[] {
+ return ['-wal', '-shm'].map(s => `${dbPath}${s}`).filter(p => fs.existsSync(p));
+ }
+
+ itPosix('makes the directory it created unreachable to other accounts', () => {
+ const { dataDir, dbPath } = unbornDataDir();
+ connectAndWrite(dbPath);
+
+ expect(sidecars(dbPath).length).toBeGreaterThan(0);
+ expect(fs.statSync(dataDir).mode & 0o077).toBe(0);
+ // Owner search+write must survive: 0600 here would lock the server out of
+ // its own data directory.
+ expect(fs.statSync(dataDir).mode & 0o700).toBe(0o700);
+ });
+
+ itWindows('gives the sidecars the restricted ACL by inheritance', () => {
+ const { dataDir, dbPath } = unbornDataDir();
+ connectAndWrite(dbPath);
+
+ const dirEntries = aclEntries(dataDir);
+ expect(dirEntries.filter(e => e.includes('(I)'))).toEqual([]);
+ expect(dirEntries).toHaveLength(3);
+ // Without (OI)(CI) the ACEs apply to the directory alone and no child ever
+ // sees them — the flags are the entire mechanism.
+ expect(dirEntries.every(e => e.includes('(OI)') && e.includes('(CI)'))).toBe(true);
+
+ const found = sidecars(dbPath);
+ expect(found.length).toBeGreaterThan(0);
+ for (const target of found) {
+ // Exactly the owner, SYSTEM and Administrators — inherited from the
+ // directory, since nothing hardened these files directly.
+ expect(aclEntries(target)).toHaveLength(3);
+ }
+ });
+
+ itPosix('leaves a directory it did not create exactly as it found it', () => {
+ // The safety property that makes the default acceptable. A group-readable
+ // shared directory must come out of connectDb unchanged.
+ const dir = existingDir();
+ fs.chmodSync(dir, 0o755);
+ connectAndWrite(path.join(dir, 'freeapi.db'));
+
+ expect(fs.statSync(dir).mode & 0o777).toBe(0o755);
+ });
+
+ itPosix('hardens that same directory once the operator opts in', () => {
+ const dir = existingDir();
+ fs.chmodSync(dir, 0o755);
+ process.env.FREEAPI_DB_DIR_HARDENING = '1';
+ connectAndWrite(path.join(dir, 'freeapi.db'));
+
+ expect(fs.statSync(dir).mode & 0o777).toBe(0o700);
+ });
+});
diff --git a/server/src/__tests__/lib/file-permissions.test.ts b/server/src/__tests__/lib/file-permissions.test.ts
index dcff5e99..98a16a0d 100644
--- a/server/src/__tests__/lib/file-permissions.test.ts
+++ b/server/src/__tests__/lib/file-permissions.test.ts
@@ -4,6 +4,7 @@ import path from 'path';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
restrictToOwner,
+ restrictDirToOwner,
restrictAllToOwner,
windowsRestrictArgs,
type ExecFileSyncLike,
@@ -18,6 +19,7 @@ const SID = 'S-1-5-21-111-222-333-1002';
const WHOAMI_OUT = `"E-DESK\\ethan","${SID}"\r\n`;
const created: string[] = [];
+const createdDirs: string[] = [];
function tempFile(contents = 'x'): string {
const p = path.join(os.tmpdir(), `freeapi-fileperms-${Date.now()}-${Math.random()}`);
@@ -26,6 +28,12 @@ function tempFile(contents = 'x'): string {
return p;
}
+function tempDir(): string {
+ const p = fs.mkdtempSync(path.join(os.tmpdir(), 'freeapi-fileperms-dir-'));
+ createdDirs.push(p);
+ return p;
+}
+
/** A fake icacls/whoami that records calls and answers the SID lookup. */
function fakeExec(overrides?: { onIcacls?: () => string }): ExecFileSyncLike & { calls: Array<{ file: string; args: string[] }> } {
const calls: Array<{ file: string; args: string[] }> = [];
@@ -46,6 +54,11 @@ afterEach(() => {
for (const p of created.splice(0)) {
try { fs.unlinkSync(p); } catch { /* best effort */ }
}
+ for (const p of createdDirs.splice(0)) {
+ // A test that hardened the directory may have left it unreadable to the
+ // umask the runner expects; force is enough, these are all mkdtemp paths.
+ try { fs.rmSync(p, { recursive: true, force: true }); } catch { /* best effort */ }
+ }
});
describe('windowsRestrictArgs', () => {
@@ -72,6 +85,71 @@ describe('windowsRestrictArgs', () => {
expect(windowsRestrictArgs('f', SID)).toContain('/grant:r');
expect(windowsRestrictArgs('f', SID)).not.toContain('/grant');
});
+
+ it('marks every principal inheritable for a directory, so later children get it', () => {
+ // (OI) object-inherit + (CI) container-inherit are the entire mechanism by
+ // which a WAL sidecar created minutes after startup is born restricted.
+ expect(windowsRestrictArgs('C:\\data', SID, { inheritable: true })).toEqual([
+ 'C:\\data',
+ '/inheritance:r',
+ '/grant:r', `*${SID}:(OI)(CI)(F)`,
+ '/grant:r', '*S-1-5-18:(OI)(CI)(F)',
+ '/grant:r', '*S-1-5-32-544:(OI)(CI)(F)',
+ ]);
+ });
+
+ it('leaves inheritance flags off a file, where they would grant nothing', () => {
+ for (const args of [windowsRestrictArgs('f', SID), windowsRestrictArgs('f', SID, {})]) {
+ expect(args.join(' ')).not.toContain('(OI)');
+ expect(args.join(' ')).not.toContain('(CI)');
+ }
+ });
+});
+
+describe('restrictDirToOwner', () => {
+ it('hands icacls the inheritable form on Windows', () => {
+ const dir = tempDir();
+ const exec = fakeExec();
+
+ expect(restrictDirToOwner(dir, { platform: 'win32', execFileSync: exec, ownerSid: SID })).toBe(true);
+
+ expect(exec.calls).toHaveLength(1);
+ expect(exec.calls[0].args).toEqual(windowsRestrictArgs(dir, SID, { inheritable: true }));
+ });
+
+ it('uses 0700 on POSIX, not 0600', () => {
+ // 0600 on a directory is not a stricter 0700 — it clears the search bit and
+ // locks the server out of its own data directory. Assert the mode itself
+ // rather than "owner-only", which both values satisfy.
+ const dir = tempDir();
+ const chmod = vi.spyOn(fs, 'chmodSync').mockImplementation(() => {});
+
+ expect(restrictDirToOwner(dir, { platform: 'linux' })).toBe(true);
+ expect(chmod).toHaveBeenCalledWith(dir, 0o700);
+ });
+
+ it('still uses 0600 for a plain file', () => {
+ const target = tempFile();
+ const chmod = vi.spyOn(fs, 'chmodSync').mockImplementation(() => {});
+
+ expect(restrictToOwner(target, { platform: 'linux' })).toBe(true);
+ expect(chmod).toHaveBeenCalledWith(target, 0o600);
+ });
+
+ it('treats an absent directory as nothing to do', () => {
+ const missing = path.join(os.tmpdir(), `freeapi-fileperms-nodir-${Date.now()}`);
+ const exec = fakeExec();
+
+ expect(restrictDirToOwner(missing, { platform: 'win32', execFileSync: exec })).toBe(true);
+ expect(exec.calls).toHaveLength(0);
+ });
+
+ it('reports failure instead of throwing when icacls fails', () => {
+ const dir = tempDir();
+ const exec = fakeExec({ onIcacls: () => { throw new Error('Access is denied.'); } });
+
+ expect(restrictDirToOwner(dir, { platform: 'win32', execFileSync: exec })).toBe(false);
+ });
});
describe('restrictToOwner on Windows', () => {
diff --git a/server/src/db/index.ts b/server/src/db/index.ts
index fa7082ee..2910674c 100644
--- a/server/src/db/index.ts
+++ b/server/src/db/index.ts
@@ -5,7 +5,7 @@ import { createRequire } from 'node:module';
import { fileURLToPath } from 'url';
import { runMigrationsSync } from './migrate/runner.js';
import { initEncryptionKey, isEncryptionKeyInitialized } from '../lib/crypto.js';
-import { restrictAllToOwner } from '../lib/file-permissions.js';
+import { restrictAllToOwner, restrictDirToOwner } from '../lib/file-permissions.js';
import { nodeSqliteFactory } from './node-sqlite.js';
import type { Db, DbFactory } from './types.js';
@@ -61,11 +61,21 @@ export function connectDb(
const ensureDir = opts?.ensureDir ?? true;
const factory = opts?.factory ?? defaultDbFactory();
+ // Gated on ensureDir along with the mkdir: that flag means "this process does
+ // not shape the filesystem here", and changing a directory's permissions is
+ // exactly that kind of change. It also keeps the warning below from firing on
+ // every boot in the read-only environments the flag exists for.
if (!isMemory && ensureDir) {
const dataDir = path.dirname(resolvedPath);
+ let created = false;
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
+ created = true;
}
+ // Before the connection, not after: on Windows the restriction is inherited,
+ // so hardening first means the database file is born protected instead of
+ // spending its first moments with whatever ACL the parent handed down.
+ restrictDataDir(dataDir, created);
}
db = factory(resolvedPath);
@@ -82,6 +92,85 @@ export function connectDb(
return db;
}
+/**
+ * Whether the directory holding the database may be restricted to this account.
+ *
+ * The sidecars can only be covered by the directory: SQLite creates `-wal` and
+ * `-shm` on the first write and deletes them on the last clean close, so at
+ * startup there is nothing there to chmod. But the directory is also shared
+ * state — FREEAPI_DB_PATH may point anywhere — and locking down a directory
+ * that is not ours is a worse outage than the leak it prevents. Pointing the DB
+ * at `/tmp/freeapi.db` must not chmod 0700 `/tmp`.
+ *
+ * So the rule is ownership by construction rather than a guess about what is
+ * safe. Two cases qualify, and nothing else does:
+ *
+ * 1. We just created the directory. Nothing else can be living in a directory
+ * that did not exist a moment ago.
+ * 2. It is the built-in default data directory, which ships as ours.
+ *
+ * Case 2 is what covers the installed base: an existing deployment already has
+ * `server/data`, so case 1 alone would harden new installs and quietly leave
+ * every upgrade behind.
+ *
+ * An operator who points FREEAPI_DB_PATH at a dedicated directory can opt in
+ * with FREEAPI_DB_DIR_HARDENING=1, and one who dislikes the default can opt out
+ * with =0. It is a deliberate default-on-where-safe rather than a flag, because
+ * hardening that only runs when someone remembers to ask for it is the same
+ * class of failure as hardening nobody noticed had stopped running.
+ */
+export function shouldHardenDataDir(
+ dataDir: string,
+ created: boolean,
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ const override = parseDirHardeningOverride();
+ if (override !== undefined) return override;
+ if (created) return true;
+
+ // Windows paths are case-insensitive; comparing them case-sensitively would
+ // miss `C:\App\Data` vs `c:\app\data` and silently skip the default install.
+ const normalize = (p: string): string =>
+ platform === 'win32' ? path.resolve(p).toLowerCase() : path.resolve(p);
+ return normalize(dataDir) === normalize(path.dirname(DB_PATH));
+}
+
+/** Tri-state, matching CSP_UPGRADE_INSECURE_REQUESTS in lib/config.ts: on, off,
+ * or unset to leave the policy above in charge. */
+function parseDirHardeningOverride(): boolean | undefined {
+ const raw = process.env.FREEAPI_DB_DIR_HARDENING;
+ if (raw === undefined || raw.trim() === '') return undefined;
+ const lower = raw.trim().toLowerCase();
+ if (lower === 'true' || lower === '1' || lower === 'yes') return true;
+ if (lower === 'false' || lower === '0' || lower === 'no') return false;
+ return undefined;
+}
+
+/** Emitted at most once: connectDb runs once in a server, but a test suite
+ * reconnects constantly and does not need the same line each time. */
+let warnedUnhardenedDataDir = false;
+
+function restrictDataDir(dataDir: string, created: boolean): void {
+ if (!shouldHardenDataDir(dataDir, created)) {
+ if (!warnedUnhardenedDataDir) {
+ warnedUnhardenedDataDir = true;
+ console.log(
+ `[db] leaving permissions on ${dataDir} as they are: it is not a directory this server created. ` +
+ 'The WAL sidecars written there inherit whatever it already grants. ' +
+ 'Set FREEAPI_DB_DIR_HARDENING=1 if it belongs to this account alone.',
+ );
+ }
+ return;
+ }
+
+ if (!restrictDirToOwner(dataDir)) {
+ console.warn(
+ `[db] could not restrict permissions on ${dataDir}; ` +
+ 'the database and its WAL sidecars may be readable by other local accounts',
+ );
+ }
+}
+
/** Restrict the DB and its WAL sidecars to the owner. The file holds encrypted
* provider keys plus the dashboard password hash, so it must not be readable by
* other local users. Best-effort: a filesystem that cannot express the
@@ -89,12 +178,12 @@ export function connectDb(
* silently, because a hardening step nobody can see failing is one nobody
* notices is absent.
*
- * Known gap, pre-existing and platform-independent: on a clean start the
- * `-wal`/`-shm` sidecars do not exist yet (SQLite creates them on the first
- * write and removes them on the last close), so this pass only ever restricts
- * the main file. Covering them needs the containing directory to carry the
- * restriction so new children inherit it, which cannot be done blindly here —
- * FREEAPI_DB_PATH may point anywhere, including a shared temp directory. */
+ * This pass only ever finds the main file on a clean start; the sidecars do not
+ * exist yet. They are covered by the directory instead — see
+ * shouldHardenDataDir. It still runs for both, because a directory this server
+ * is not allowed to touch can still hold sidecars left behind by an unclean
+ * shutdown, and because the main file predates the directory pass on any
+ * install that upgraded into it. */
function restrictDbFilePermissions(resolvedPath: string): void {
const failed = restrictAllToOwner(['', '-wal', '-shm'].map(suffix => `${resolvedPath}${suffix}`));
if (failed.length > 0) {
diff --git a/server/src/lib/file-permissions.ts b/server/src/lib/file-permissions.ts
index b175ba9d..915df921 100644
--- a/server/src/lib/file-permissions.ts
+++ b/server/src/lib/file-permissions.ts
@@ -18,6 +18,22 @@ import { execFileSync as nodeExecFileSync } from 'node:child_process';
* last two mirrors POSIX, where 0600 never locks root out — and dropping them
* would break backup agents and service accounts for no security gain, since
* both can take ownership regardless.
+ *
+ * `restrictDirToOwner` covers what per-file hardening structurally cannot: a
+ * file that does not exist yet. SQLite's `-wal`/`-shm` sidecars are created on
+ * the first write, long after startup has walked the file list, so the only
+ * thing that can protect them is the directory holding them. The two platforms
+ * reach that guarantee by different mechanisms, and it is worth being precise
+ * about which, because they are not the same idea:
+ *
+ * - Windows really does inherit. `(OI)(CI)` marks an ACE object- and
+ * container-inheritable, so a sidecar created afterwards is born with the
+ * restricted ACL already on it.
+ * - POSIX does not propagate modes at all — a file created inside a 0700
+ * directory still lands at 0644. It does not need to: 0700 clears the search
+ * bit for group and other, and without search permission no other account
+ * can resolve a path through the directory to reach the child in the first
+ * place. The sidecar is unreachable rather than unreadable.
*/
/** Injectable seam so tests never spawn a real process. Mirrors the `ExecFile`
@@ -95,27 +111,36 @@ function resolveOwnerSid(exec: ExecFileSyncLike, useCache: boolean): string | nu
* the extra principals come from), and `/grant:r` replaces rather than adds, so
* running it twice is idempotent. The `*` prefix makes icacls read each
* principal as a SID literal instead of an account name.
+ *
+ * `inheritable` adds `(OI)(CI)` so children created later are born restricted.
+ * It is only ever set for a directory: the flags describe what a container
+ * hands down, and on a leaf file they protect nothing.
*/
-export function windowsRestrictArgs(target: string, ownerSid: string): string[] {
+export function windowsRestrictArgs(
+ target: string,
+ ownerSid: string,
+ opts?: { inheritable?: boolean },
+): string[] {
+ const rights = opts?.inheritable ? '(OI)(CI)(F)' : '(F)';
return [
target,
'/inheritance:r',
- '/grant:r', `*${ownerSid}:(F)`,
- '/grant:r', `*${SID_SYSTEM}:(F)`,
- '/grant:r', `*${SID_ADMINISTRATORS}:(F)`,
+ '/grant:r', `*${ownerSid}:${rights}`,
+ '/grant:r', `*${SID_SYSTEM}:${rights}`,
+ '/grant:r', `*${SID_ADMINISTRATORS}:${rights}`,
];
}
-/**
- * Restrict `target` to its owner. Never throws: permissions are a hardening
- * measure, not a correctness one, and startup must survive a filesystem that
- * cannot express them.
- *
- * @returns true when the restriction was applied, false when it could not be.
- * Callers are expected to surface a false — the failure mode that made
- * this function necessary was a guard everyone believed was running.
- */
-export function restrictToOwner(target: string, opts?: RestrictOptions): boolean {
+/** A directory needs its search bit kept, or the owning process locks itself
+ * out of its own data directory; 0600 on a directory is not a stricter 0700,
+ * it is a broken one. */
+const POSIX_MODE = { file: 0o600, directory: 0o700 } as const;
+
+function restrict(
+ target: string,
+ kind: 'file' | 'directory',
+ opts?: RestrictOptions,
+): boolean {
const platform = opts?.platform ?? process.platform;
const exec = opts?.execFileSync ?? defaultExecFileSync;
@@ -127,7 +152,7 @@ export function restrictToOwner(target: string, opts?: RestrictOptions): boolean
if (platform !== 'win32') {
try {
- fs.chmodSync(target, 0o600);
+ fs.chmodSync(target, POSIX_MODE[kind]);
return true;
} catch {
return false;
@@ -140,18 +165,51 @@ export function restrictToOwner(target: string, opts?: RestrictOptions): boolean
if (!ownerSid) return false;
try {
- exec(system32('icacls.exe'), windowsRestrictArgs(target, ownerSid), {
- encoding: 'utf8',
- timeout: EXEC_TIMEOUT_MS,
- windowsHide: true,
- stdio: ['ignore', 'pipe', 'pipe'],
- });
+ exec(
+ system32('icacls.exe'),
+ windowsRestrictArgs(target, ownerSid, { inheritable: kind === 'directory' }),
+ {
+ encoding: 'utf8',
+ timeout: EXEC_TIMEOUT_MS,
+ windowsHide: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ },
+ );
return true;
} catch {
return false;
}
}
+/**
+ * Restrict `target` to its owner. Never throws: permissions are a hardening
+ * measure, not a correctness one, and startup must survive a filesystem that
+ * cannot express them.
+ *
+ * @returns true when the restriction was applied, false when it could not be.
+ * Callers are expected to surface a false — the failure mode that made
+ * this function necessary was a guard everyone believed was running.
+ */
+export function restrictToOwner(target: string, opts?: RestrictOptions): boolean {
+ return restrict(target, 'file', opts);
+}
+
+/**
+ * Restrict a directory to its owner, so files created inside it later are
+ * protected without anyone having to remember to harden them. See the header
+ * for why this is the only thing that can cover SQLite's WAL sidecars.
+ *
+ * Callers must be sure the directory is theirs. This is deliberately not
+ * something to do to any path handed in by configuration: locking down a shared
+ * directory — a temp dir, a working copy, someone else's data directory — is a
+ * worse outage than the leak it prevents.
+ *
+ * @returns true when the restriction was applied, false when it could not be.
+ */
+export function restrictDirToOwner(target: string, opts?: RestrictOptions): boolean {
+ return restrict(target, 'directory', opts);
+}
+
/**
* Restrict several files that share an owner, resolving the SID at most once.
* Missing files are skipped, not failed — SQLite's `-wal`/`-shm` sidecars do not