Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex r2): close the reloadSettings fail-open and the unreadable-cache gap

[._.]/ Adam Eivy00b9153fe21e
diff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.js
index d30a886120..049a819565 100644
--- a/server/lib/authGate.test.js
+++ b/server/lib/authGate.test.js
@@ -82,6 +82,24 @@ describe('authGate middleware', () => {
expect(gated.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });
});
+ it('stays fail-closed when a corrupt settings.json is loaded via reloadSettings (#2684)', async () => {
+ // A backup restore of a malformed snapshot calls reloadSettings(). It must NOT
+ // broadcast the corrupt file as {} and prime the auth cache to disabled — that
+ // would reopen the gate (fail open) and stick, since the cache is no longer null.
+ writeFileSync(join(tempRoot, 'settings.json'), '{ corrupt snapshot');
+ const { reloadSettings } = await import('../services/settings.js');
+ const { authGate } = await import('./authGate.js');
+
+ await reloadSettings();
+
+ // Gated route stays blocked (fail closed), public discovery stays reachable.
+ const gated = await runGate(authGate, { path: '/api/cos', headers: {} });
+ expect(gated.called).toBe(false);
+ expect(gated.res.statusCode).toBe(401);
+ const health = await runGate(authGate, { path: '/api/system/health', headers: {} });
+ expect(health.called).toBe(true);
+ });
+
it('treats an absent settings.json as auth OFF (fresh install, no regression)', async () => {
// ENOENT is the one non-failure case — a fresh install legitimately has no
// settings and auth is off, so gated routes pass through.
diff --git a/server/services/auth.js b/server/services/auth.js
index 5d7e3354ca..0b706ed72b 100644
--- a/server/services/auth.js
+++ b/server/services/auth.js
@@ -132,6 +132,12 @@ const recomputeEnabledCache = (settings) => {
enabledCache = !!(a?.enabled && a?.passwordHash && a?.salt);
};
settingsEvents.on('settings:updated', recomputeEnabledCache);
+// A corrupt reload (e.g. a backup restore of a malformed settings.json — see
+// reloadSettings() in settings.js) emits this instead of a `{}`-valued
+// settings:updated. Drop the cached boolean so the next isAuthEnabled() goes
+// through the strict read and FAILS CLOSED rather than reopening the gate from a
+// corrupt-derived empty snapshot. See #2684.
+settingsEvents.on('settings:invalidated', () => { enabledCache = null; });
export const isAuthEnabled = async () => {
if (enabledCache === null) {
diff --git a/server/services/settings.js b/server/services/settings.js
index dca76586d4..44515aa97d 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -1,5 +1,5 @@
import { join } from 'path';
-import { readFile } from 'fs/promises';
+import { access } from 'fs/promises';
import { EventEmitter } from 'events';
import { safeJSONParse, PATHS, atomicWrite, tryReadFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
@@ -95,24 +95,26 @@ const loadRaw = async () => {
* exists so unit tests can point it at a temp file without touching real data.
*/
export const readSettingsStrict = async (filePath = SETTINGS_FILE) => {
- let raw;
- try {
- raw = await readFile(filePath, 'utf8');
- } catch (err) {
- // ENOENT is the only "not a failure" case — no file means no settings yet.
- if (err?.code === 'ENOENT') return { present: false, corrupt: false, settings: {} };
- // EACCES / EIO / EISDIR / … — the file is there but we couldn't read it.
- return { present: true, corrupt: true, settings: {} };
- }
- try {
- const parsed = JSON.parse(raw);
- // A valid-JSON but non-object root (array, string, number, null) is not a
- // settings document — treat it as corrupt rather than reading properties off it.
- if (!isPlainObject(parsed)) return { present: true, corrupt: true, settings: {} };
- return { present: true, corrupt: false, settings: parsed };
- } catch {
- return { present: true, corrupt: true, settings: {} };
+ const raw = await tryReadFile(filePath);
+ if (raw === null) {
+ // tryReadFile collapses BOTH an absent file (ENOENT) and a read failure
+ // (EACCES / EIO / …) to null. Probe with access() to tell them apart: an
+ // ABSENT file is the fresh-install default (auth off), while a file that
+ // EXISTS but couldn't be read is corrupt (fail closed).
+ try {
+ await access(filePath);
+ return { present: true, corrupt: true, settings: {} }; // exists but unreadable
+ } catch {
+ return { present: false, corrupt: false, settings: {} }; // ENOENT — genuinely absent
+ }
}
+ // Present and read. safeJSONParse returns null for malformed/empty input; a
+ // valid-JSON but non-object root (array, string, number) is likewise not a
+ // settings document — either way, treat it as corrupt rather than reading
+ // properties off it.
+ const parsed = safeJSONParse(raw, null);
+ if (!isPlainObject(parsed)) return { present: true, corrupt: true, settings: {} };
+ return { present: true, corrupt: false, settings: parsed };
};
// Read-side cache. `getSettings()` is called 100+ times across the codebase
@@ -158,7 +160,21 @@ export const __resetSettingsCache = () => {
// since such a write bypasses the save()-emitted event the cache rides on and
// would otherwise leave every settings consumer serving pre-restore values.
export const reloadSettings = async () => {
- const cleaned = stripStoreKeys(await loadRaw());
+ const { corrupt, settings } = await readSettingsStrict();
+ if (corrupt) {
+ // Do NOT broadcast a corrupt on-disk settings.json as `{}` (issue #2684). The
+ // concrete path is a backup restore of a malformed snapshot: backup.js calls
+ // reloadSettings() after installing it. Emitting `settings:updated` with `{}`
+ // would prime the read cache AND the auth enabled-cache to an empty/disabled
+ // state — reopening the gate (FAIL OPEN) and sticking there because the cache
+ // is no longer null. Invalidate instead: drop the read cache and signal
+ // consumers (auth) to drop theirs, so the next read goes to disk and fails
+ // closed / re-reads. Self-heals on the next clean read.
+ settingsCache = null;
+ settingsEvents.emit('settings:invalidated');
+ return {};
+ }
+ const cleaned = stripStoreKeys(settings);
settingsEvents.emit('settings:updated', cleaned);
return cleaned;
};
@@ -204,20 +220,15 @@ const save = async (settings) => {
export const getSettings = async () => {
if (settingsCache === null) {
- const raw = await tryReadFile(SETTINGS_FILE);
- // Distinguish a CORRUPT (present but unparseable) settings.json from an
- // absent/empty one so a corrupt read does NOT poison the cache with `{}`
- // (issue #2684). Caching a corrupt-derived empty object would strand every
- // consumer — verifyPassword, schedulers, feature reads — on empty settings
- // until a save() or restart, defeating the no-restart self-heal that the
- // auth fail-closed path promises. A malformed file (`raw` present but not a
- // JSON object) is the corrupt case handled here; `tryReadFile` collapses an
- // absent OR unreadable file to null, which we treat as an empty, cacheable
- // snapshot (absent is the fresh-install default; the rarer unreadable case is
- // still failed CLOSED by isAuthEnabled's stricter readSettingsStrict).
- const parsed = raw === null ? {} : safeJSONParse(raw, null);
- const corrupt = raw !== null && !isPlainObject(parsed);
- const loaded = stripStoreKeys(isPlainObject(parsed) ? parsed : {});
+ // Route the cold read through the STRICT reader so a corrupt/unreadable
+ // settings.json does NOT poison the cache with `{}` (issue #2684). Caching a
+ // corrupt-derived empty object would strand every consumer — verifyPassword,
+ // schedulers, feature reads — on empty settings until a save() or restart,
+ // defeating the no-restart self-heal the auth fail-closed path promises. This
+ // covers BOTH failure modes (malformed content and an unreadable-but-present
+ // file); only a genuinely ABSENT file (fresh install) caches `{}`.
+ const { corrupt, settings } = await readSettingsStrict();
+ const loaded = stripStoreKeys(settings);
// A save()/reloadSettings() may have populated the cache via the
// settings:updated listener while this cold read was awaiting the disk read.
// Prefer that fresher in-memory value over our (older) on-disk snapshot.
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 23f54184c4..2f0cd95257 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -522,46 +522,92 @@ describe('settings.js', () => {
// Strict read for the auth gate (#2684): distinguishes absent (auth off) from
// present-but-corrupt (fail closed), which loadRaw()/getSettings() collapse to {}.
- // These exercise the REAL fs read path against temp files (not the tryReadFile
- // mock), which is the whole point — the collapse the mock would hide is the bug.
+ // Content comes through the mocked tryReadFile; the absent-vs-unreadable split
+ // uses a real access() probe, so those two cases drive a real temp file.
describe('readSettingsStrict', () => {
let dir;
beforeEach(() => { dir = mkdtempSync(joinPath(tmpdir(), 'portos-strict-')); });
afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
it('reports absent (not corrupt) when the file does not exist', async () => {
+ // tryReadFile null + a path that isn't there → access() throws → absent.
+ tryReadFile.mockResolvedValue(null);
const res = await readSettingsStrict(joinPath(dir, 'nope.json'));
expect(res).toEqual({ present: false, corrupt: false, settings: {} });
});
- it('parses a clean settings file', async () => {
+ it('flags a present-but-unreadable file as corrupt (fail-closed signal)', async () => {
+ // tryReadFile null (read failed) but the file EXISTS → access() succeeds → corrupt.
const p = joinPath(dir, 'settings.json');
- writeFileSync(p, JSON.stringify({ secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' } } }));
+ writeFileSync(p, '{}');
+ tryReadFile.mockResolvedValue(null);
const res = await readSettingsStrict(p);
+ expect(res).toEqual({ present: true, corrupt: true, settings: {} });
+ });
+
+ it('parses a clean settings file', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ secrets: { auth: { enabled: true, passwordHash: 'h', salt: 's' } } }));
+ const res = await readSettingsStrict(joinPath(dir, 'settings.json'));
expect(res.present).toBe(true);
expect(res.corrupt).toBe(false);
expect(res.settings.secrets.auth.enabled).toBe(true);
});
- it('flags a present-but-malformed file as corrupt (fail-closed signal)', async () => {
- const p = joinPath(dir, 'settings.json');
- writeFileSync(p, '{ this is not valid json');
- const res = await readSettingsStrict(p);
+ it('flags present-but-malformed content as corrupt', async () => {
+ tryReadFile.mockResolvedValue('{ this is not valid json');
+ const res = await readSettingsStrict(joinPath(dir, 'settings.json'));
expect(res).toEqual({ present: true, corrupt: true, settings: {} });
});
- it('flags an empty file as corrupt', async () => {
- const p = joinPath(dir, 'settings.json');
- writeFileSync(p, '');
- const res = await readSettingsStrict(p);
+ it('flags empty content as corrupt', async () => {
+ tryReadFile.mockResolvedValue('');
+ const res = await readSettingsStrict(joinPath(dir, 'settings.json'));
expect(res.corrupt).toBe(true);
});
it('flags a valid-JSON but non-object root as corrupt', async () => {
- const p = joinPath(dir, 'settings.json');
- writeFileSync(p, '[1,2,3]');
- const res = await readSettingsStrict(p);
+ tryReadFile.mockResolvedValue('[1,2,3]');
+ const res = await readSettingsStrict(joinPath(dir, 'settings.json'));
expect(res.corrupt).toBe(true);
});
});
+
+ // reloadSettings must not broadcast a corrupt file as `{}` (#2684) — that path
+ // (backup restore of a malformed snapshot) is what would prime the auth cache
+ // to disabled and fail open.
+ describe('reloadSettings corruption handling', () => {
+ it('emits settings:invalidated (not settings:updated) and drops the cache on a corrupt file', async () => {
+ const onUpdated = vi.fn();
+ const onInvalidated = vi.fn();
+ settingsEvents.on('settings:updated', onUpdated);
+ settingsEvents.on('settings:invalidated', onInvalidated);
+
+ tryReadFile.mockResolvedValue('{ truncated');
+ const result = await reloadSettings();
+
+ expect(result).toEqual({});
+ expect(onInvalidated).toHaveBeenCalledTimes(1);
+ expect(onUpdated).not.toHaveBeenCalled();
+
+ // Cache was dropped: a subsequent clean read is picked up (not a stale {}).
+ tryReadFile.mockResolvedValue(JSON.stringify({ theme: 'dark' }));
+ expect(await getSettings()).toEqual({ theme: 'dark' });
+
+ settingsEvents.off('settings:updated', onUpdated);
+ settingsEvents.off('settings:invalidated', onInvalidated);
+ });
+
+ it('emits settings:updated with the parsed settings on a clean reload', async () => {
+ const onUpdated = vi.fn();
+ settingsEvents.on('settings:updated', onUpdated);
+
+ tryReadFile.mockResolvedValue(JSON.stringify({ theme: 'light' }));
+ const result = await reloadSettings();
+
+ expect(result).toEqual({ theme: 'light' });
+ expect(onUpdated).toHaveBeenCalledWith({ theme: 'light' });
+
+ settingsEvents.off('settings:updated', onUpdated);
+ });
+ });
});