From 290d6b1038bc73c3cbc1f2a31a8a6793eb342b58 Mon Sep 17 00:00:00 2001 From: Gazzy-Lee Date: Thu, 19 Nov 2026 16:20:53 +0100 Subject: [PATCH 1/2] fix(config): define portable project config filesystem policy Read the config through an inspected regular-file descriptor, reject symlinks explicitly (including link swaps), ignore POSIX mode/ownership on all platforms, and keep unreadable-file errors content-free. Add deterministic regression coverage and document the non-secret permission policy. --- .changeset/config-file-boundary-policy.md | 5 + docs/reference/configuration.md | 17 +- docs/reference/platform-support.md | 3 +- docs/reference/troubleshooting.md | 4 +- src/config/project.ts | 143 ++++++++++--- tests/config-filesystem-boundaries.test.ts | 228 ++++++++++++++++++++- tests/configuration.test.ts | 43 +++- 7 files changed, 400 insertions(+), 43 deletions(-) create mode 100644 .changeset/config-file-boundary-policy.md diff --git a/.changeset/config-file-boundary-policy.md b/.changeset/config-file-boundary-policy.md new file mode 100644 index 00000000..811cc772 --- /dev/null +++ b/.changeset/config-file-boundary-policy.md @@ -0,0 +1,5 @@ +--- +'@diginodes/stellarforge-cli': patch +--- + +Harden project configuration loading so reads stay on an inspected regular file inside the project root, document the portable non-secret permission policy, and add deterministic coverage for unreadable files and symlink boundaries. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 58904829..1682f20d 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -56,13 +56,24 @@ overrides only the identity. The file must: -- live at the project root; -- be a regular file rather than a symbolic link; +- live at the project root under the exact name `stellarforge.config.json`; +- be a regular file rather than a symbolic link, including links whose target is inside the project root; +- be readable by the current process; - be no larger than 64 KiB; - contain valid JSON; - contain no duplicate object keys at any nesting level (escaped-equivalent spellings are treated as the same key); - contain only supported schema fields. -Validation failures are designed to be actionable without echoing raw file contents or sensitive values. +The loader reads only the opened regular file descriptor and rechecks the project-root path before reading. A symlink substituted between inspection and read is rejected; the config is never read through a link that could escape the project boundary. + +Validation failures are designed to be actionable without echoing raw file contents, paths, OS error text, or sensitive values. + +### File permissions and platform behavior + +This configuration file is non-secret by design: it holds only a schema version, a network name, and an identity alias. StellarForge therefore does not reject or warn about permissive file modes or unusual ownership, because those are not security signals for this file. + +- POSIX permission and ownership bits are ignored on every supported platform, including Windows where those bits are synthetic. Mode `0666`, group ownership, and root ownership are accepted. +- A file that the current process cannot read produces the validation error `Unable to inspect stellarforge.config.json.` (exit code 2). The message never includes the path, the OS error, or file contents. +- StellarForge never changes file permissions or ownership and never attempts privilege escalation. If a config file cannot be read, adjust it outside the CLI. If the file is rejected, see [Troubleshooting](troubleshooting.md#configuration-file-is-rejected). For deployment settings, see [Deployment network is required](troubleshooting.md#deployment-network-is-required) and [Deployment identity is rejected](troubleshooting.md#deployment-identity-is-rejected). diff --git a/docs/reference/platform-support.md b/docs/reference/platform-support.md index 69753026..d6e4582d 100644 --- a/docs/reference/platform-support.md +++ b/docs/reference/platform-support.md @@ -37,7 +37,8 @@ StellarForge code should expose platform differences deliberately instead of hid - Cargo subprocesses use `cargo.exe`; - Stellar deployment subprocesses use `stellar.exe`; - path tests must use Node path APIs rather than assuming POSIX separators; -- commands must not rely on Bash being the default shell. +- commands must not rely on Bash being the default shell; +- POSIX permission and ownership bits reported for files are synthetic, so config loading ignores them on every platform instead of applying platform-dependent rules or changing file permissions. ### macOS and Linux diff --git a/docs/reference/troubleshooting.md b/docs/reference/troubleshooting.md index 957f2216..447f4c89 100644 --- a/docs/reference/troubleshooting.md +++ b/docs/reference/troubleshooting.md @@ -135,7 +135,9 @@ stellarforge.config.json and live at the project root. -It must be a regular non-symlink file, no larger than 64 KiB, and contain valid JSON with schema version `1`, and it must not contain duplicate object keys at any nesting level (escaped-equivalent spellings are treated as the same key). +It must be a regular non-symlink file, no larger than 64 KiB, and contain valid JSON with schema version `1`, and it must not contain duplicate object keys at any nesting level (escaped-equivalent spellings are treated as the same key). Symbolic links are never followed, including links that point back inside the project. + +If the file cannot be read, the CLI reports `Unable to inspect stellarforge.config.json.` without echoing the path or the system error. Fix access outside StellarForge: the CLI never changes permissions or ownership. Permissive POSIX modes are accepted because this file contains no secrets, and Windows does not expose meaningful POSIX permission semantics. Supported fields are only: diff --git a/src/config/project.ts b/src/config/project.ts index a92c043a..88e1f018 100644 --- a/src/config/project.ts +++ b/src/config/project.ts @@ -1,4 +1,13 @@ -import { existsSync, lstatSync, readFileSync, type Stats } from 'node:fs'; +import { + closeSync, + constants as fsConstants, + existsSync, + fstatSync, + lstatSync, + openSync, + readFileSync, + type Stats, +} from 'node:fs'; import { resolve } from 'node:path'; import { ValidationCliError } from '../errors/errors.js'; import { @@ -10,6 +19,108 @@ import { export const PROJECT_CONFIG_FILENAME = 'stellarforge.config.json'; const MAX_CONFIG_BYTES = 64 * 1024; +/** + * Portable project-config filesystem policy: + * + * - the only accepted path is `/stellarforge.config.json`; + * - the path must be a regular file; symlinks are rejected rather than + * followed, so a link can never redirect the loader outside the root; + * - the opened descriptor is checked before reading, so a path swap between + * inspection and read cannot turn the read into a symlink escape; + * - POSIX mode bits and ownership are deliberately not used as trust signals. + * The file is non-secret by design (version, network, identity alias), so + * permissive modes are valid and must not be rejected. Windows also reports + * synthetic POSIX bits, which cannot carry security meaning there; + * - unreadable files fail with a content-free validation error; + * - the CLI never changes permissions or ownership and never attempts to + * escalate privileges. + * + * `O_NOFOLLOW` is used where the platform exposes it. Where it does not + * (notably Windows), the post-open path check keeps the same explicit symlink + * boundary for the read path. + */ +const NOFOLLOW_FLAG: number = + (fsConstants as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0; +const CONFIG_OPEN_FLAGS = fsConstants.O_RDONLY | NOFOLLOW_FLAG; + +function assertRegularConfigFile(metadata: Stats): void { + if (metadata.isSymbolicLink()) { + throw new ValidationCliError( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + } + + if (!metadata.isFile()) { + throw new ValidationCliError( + 'stellarforge.config.json must be a regular project file.', + ); + } +} + +function assertConfigSize(size: number): void { + if (size > MAX_CONFIG_BYTES) { + throw new ValidationCliError( + 'stellarforge.config.json is larger than the 64 KiB MVP limit.', + ); + } +} + +function isSymlinkOpenFailure(error: unknown): boolean { + return ( + error instanceof Error && (error as NodeJS.ErrnoException).code === 'ELOOP' + ); +} + +function readConfigFile(configPath: string): string { + let descriptor: number | undefined; + + try { + try { + descriptor = openSync(configPath, CONFIG_OPEN_FLAGS); + } catch (error) { + // A link swapped in after the initial lstat() is reported with ELOOP on + // platforms that support O_NOFOLLOW. Keep the symlink diagnostic stable. + if (isSymlinkOpenFailure(error)) { + throw new ValidationCliError( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + } + throw error; + } + + const opened = fstatSync(descriptor); + assertRegularConfigFile(opened); + assertConfigSize(opened.size); + + // The path is checked again after opening. On platforms without + // O_NOFOLLOW this catches a link substituted before open(); the open + // descriptor still pins the original file for the bytes read below. + assertRegularConfigFile(lstatSync(configPath)); + + return readFileSync(descriptor, 'utf8'); + } catch (error) { + if (error instanceof ValidationCliError) { + throw error; + } + + // Never include the OS error text, path, or file contents in the message. + throw new ValidationCliError( + 'Unable to inspect stellarforge.config.json.', + { + cause: error, + }, + ); + } finally { + if (descriptor !== undefined) { + try { + closeSync(descriptor); + } catch { + // A close failure must not replace an already-produced result. + } + } + } +} + /** * Best-effort JSON scanner that rejects duplicate object keys, including * escaped-equivalent spellings of the same key and duplicates at any depth. @@ -308,34 +419,10 @@ export function loadProjectConfig(cwd: string): StellarForgeConfig | undefined { ); } - if (metadata.isSymbolicLink()) { - throw new ValidationCliError( - 'stellarforge.config.json must be a regular project file, not a symbolic link.', - ); - } + assertRegularConfigFile(metadata); + assertConfigSize(metadata.size); - if (!metadata.isFile()) { - throw new ValidationCliError( - 'stellarforge.config.json must be a regular project file.', - ); - } - - if (metadata.size > MAX_CONFIG_BYTES) { - throw new ValidationCliError( - 'stellarforge.config.json is larger than the 64 KiB MVP limit.', - ); - } - - let text: string; - - try { - text = readFileSync(configPath, 'utf8'); - } catch (error) { - throw new ValidationCliError( - 'Unable to inspect stellarforge.config.json.', - { cause: error }, - ); - } + const text = readConfigFile(configPath); assertNoDuplicateJsonKeys(text); diff --git a/tests/config-filesystem-boundaries.test.ts b/tests/config-filesystem-boundaries.test.ts index 39cfb979..55ad9ad4 100644 --- a/tests/config-filesystem-boundaries.test.ts +++ b/tests/config-filesystem-boundaries.test.ts @@ -1,6 +1,15 @@ +/** + * Project config filesystem boundary policy (WS-CONFIG). + * + * The config file is non-secret by design, so POSIX mode bits and ownership + * are not trust signals. These tests pin the portable policy instead: + * exact-path regular files only, explicit symlink rejection, content-free + * errors when a file cannot be read, and no permission changes by the CLI. + */ +import type * as NodeFs from 'node:fs'; import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { loadProjectConfig, PROJECT_CONFIG_FILENAME, @@ -11,6 +20,70 @@ import { withTempDirectory, } from './helpers/index.js'; +const fsProbe = vi.hoisted(() => ({ + failOpenWith: null as NodeJS.ErrnoException | null, + failReadWith: null as NodeJS.ErrnoException | null, + secondLstatIsSymlink: false, + lstatCalls: 0, + chmodCalls: [] as unknown[][], + mutateStats: null as null | ((stats: NodeFs.Stats) => NodeFs.Stats), +})); + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + + function withStatsOverride(stats: NodeFs.Stats): NodeFs.Stats { + return fsProbe.mutateStats ? fsProbe.mutateStats(stats) : stats; + } + + function symlinkStats(stats: NodeFs.Stats): NodeFs.Stats { + const fake = Object.create(Object.getPrototypeOf(stats)) as NodeFs.Stats; + Object.assign(fake, stats); + Object.defineProperty(fake, 'isSymbolicLink', { value: () => true }); + Object.defineProperty(fake, 'isFile', { value: () => false }); + return fake; + } + + return { + ...actual, + lstatSync: ((...args: Parameters) => { + const stats = actual.lstatSync(...args) as NodeFs.Stats; + + if (String(args[0]).endsWith('stellarforge.config.json')) { + fsProbe.lstatCalls += 1; + + // Simulates a link substituted between the first inspection and the + // post-open check without depending on OS symlink privileges. + if (fsProbe.lstatCalls === 2 && fsProbe.secondLstatIsSymlink) { + return symlinkStats(stats); + } + } + + return withStatsOverride(stats); + }) as typeof actual.lstatSync, + fstatSync: ((...args: Parameters) => + withStatsOverride( + actual.fstatSync(...args) as NodeFs.Stats, + )) as typeof actual.fstatSync, + openSync: ((...args: Parameters) => { + if (fsProbe.failOpenWith) { + throw fsProbe.failOpenWith; + } + return actual.openSync(...args); + }) as typeof actual.openSync, + readFileSync: ((...args: Parameters) => { + if (fsProbe.failReadWith) { + throw fsProbe.failReadWith; + } + return actual.readFileSync(...args); + }) as typeof actual.readFileSync, + chmodSync: ((...args: Parameters) => { + fsProbe.chmodCalls.push(args); + return actual.chmodSync(...args); + }) as typeof actual.chmodSync, + }; +}); + function canCreateSymlink(): boolean { const fixture = createTempDirectoryFixture(); try { @@ -26,6 +99,51 @@ function canCreateSymlink(): boolean { } const symlinksSupported = canCreateSymlink(); +const ORIGINAL_PLATFORM = process.platform; + +function onPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { + value: platform, + configurable: true, + }); +} + +function captureError(action: () => unknown): unknown { + try { + action(); + } catch (error) { + return error; + } + return undefined; +} + +function permissionDenied(code: string): NodeJS.ErrnoException { + return Object.assign(new Error('permission denied'), { code }); +} + +function permissiveStats(stats: NodeFs.Stats): NodeFs.Stats { + const clone = Object.create(Object.getPrototypeOf(stats)) as NodeFs.Stats; + // Keep the file-type bits so the clone is still a regular file; only the + // permission bits and ownership become deliberately permissive/foreign. + return Object.assign(clone, stats, { + mode: (stats.mode & ~0o7777) | 0o777, + uid: 0, + gid: 0, + }); +} + +afterEach(() => { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); + fsProbe.failOpenWith = null; + fsProbe.failReadWith = null; + fsProbe.secondLstatIsSymlink = false; + fsProbe.lstatCalls = 0; + fsProbe.chmodCalls.length = 0; + fsProbe.mutateStats = null; +}); function writeValidConfig(root: string, name = PROJECT_CONFIG_FILENAME): void { writeFileSync( @@ -111,4 +229,112 @@ describe('configuration filesystem boundaries', () => { expect(loadProjectConfig(root)).toBeUndefined(); }), ); + + it.skipIf(!symlinksSupported)( + 'does not read a symlink whose target is outside the project root', + () => + withTempDirectory((root) => { + const outside = join(root, 'outside'); + mkdirSync(outside); + const target = join(outside, 'config.json'); + writeFileSync( + target, + JSON.stringify({ version: 1, network: 'mainnet' }), + ); + symlinkSync(target, join(root, PROJECT_CONFIG_FILENAME)); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + expect((thrown as Error).message).not.toContain(target); + expect((thrown as Error).message).not.toContain('mainnet'); + }), + ); + + it('rejects an ELOOP raised when the path is opened', () => + withTempDirectory((root) => { + writeValidConfig(root); + fsProbe.failOpenWith = permissionDenied('ELOOP'); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + })); + + it('rejects when the path becomes a symlink after the file is opened', () => + withTempDirectory((root) => { + writeValidConfig(root); + fsProbe.secondLstatIsSymlink = true; + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toContain('not a symbolic link'); + })); + + it.each([ + { + stage: 'opened', + fail: () => (fsProbe.failOpenWith = permissionDenied('EACCES')), + }, + { + stage: 'read', + fail: () => (fsProbe.failReadWith = permissionDenied('EACCES')), + }, + ])( + 'reports a content-free error when the file cannot be $stage', + ({ fail }) => + withTempDirectory((root) => { + writeValidConfig(root); + fail(); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'Unable to inspect stellarforge.config.json.', + ); + expect((thrown as Error).message).not.toContain(root); + expect((thrown as Error).message).not.toContain('EACCES'); + }), + ); + + describe.each([ + { platform: 'win32', label: 'Windows' }, + { platform: 'linux', label: 'POSIX' }, + ] as const)('portable permission policy on $label', ({ platform }) => { + it('accepts permissive modes and foreign ownership without changing permissions', () => + withTempDirectory((root) => { + onPlatform(platform); + writeValidConfig(root); + fsProbe.mutateStats = permissiveStats; + + expect(loadProjectConfig(root)).toEqual({ + version: 1, + network: 'testnet', + }); + expect(fsProbe.chmodCalls).toEqual([]); + })); + + it('reports the same content-free error for an unreadable file', () => + withTempDirectory((root) => { + onPlatform(platform); + writeValidConfig(root); + fsProbe.failReadWith = permissionDenied('EACCES'); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'Unable to inspect stellarforge.config.json.', + ); + expect(fsProbe.chmodCalls).toEqual([]); + })); + }); }); diff --git a/tests/configuration.test.ts b/tests/configuration.test.ts index 148f0b43..6472180c 100644 --- a/tests/configuration.test.ts +++ b/tests/configuration.test.ts @@ -7,7 +7,26 @@ import { resolveProjectConfig, } from '../src/config/project.js'; import { ValidationCliError } from '../src/errors/errors.js'; -import { withTempDirectory } from './helpers/index.js'; +import { + createTempDirectoryFixture, + withTempDirectory, +} from './helpers/index.js'; + +// Windows may require privileges or developer mode to create symlinks. +function canCreateSymlink(): boolean { + const fixture = createTempDirectoryFixture(); + try { + writeFileSync(join(fixture.path, 'target'), 'target'); + symlinkSync(join(fixture.path, 'target'), join(fixture.path, 'link')); + return true; + } catch { + return false; + } finally { + fixture.cleanup(); + } +} + +const symlinksSupported = canCreateSymlink(); describe('project configuration', () => { it('returns undefined when project configuration is missing', () => @@ -172,12 +191,18 @@ describe('project configuration', () => { }), ); - it('rejects a symlinked project configuration', () => - withTempDirectory((root) => { - const target = join(root, 'actual-config.json'); - writeFileSync(target, JSON.stringify({ version: 1, network: 'testnet' })); - symlinkSync(target, join(root, PROJECT_CONFIG_FILENAME)); - - expect(() => loadProjectConfig(root)).toThrow('not a symbolic link'); - })); + it.skipIf(!symlinksSupported)( + 'rejects a symlinked project configuration', + () => + withTempDirectory((root) => { + const target = join(root, 'actual-config.json'); + writeFileSync( + target, + JSON.stringify({ version: 1, network: 'testnet' }), + ); + symlinkSync(target, join(root, PROJECT_CONFIG_FILENAME)); + + expect(() => loadProjectConfig(root)).toThrow('not a symbolic link'); + }), + ); }); From 3e65f1a9b9dabcd635ed0946c457aca11d727f33 Mon Sep 17 00:00:00 2001 From: Gazzy-Lee Date: Sun, 22 Nov 2026 16:39:58 +0100 Subject: [PATCH 2/2] fix(e2e): import Buffer explicitly for lint --- scripts/e2e-smoke.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/e2e-smoke.mjs b/scripts/e2e-smoke.mjs index a4b44172..5bf951f6 100644 --- a/scripts/e2e-smoke.mjs +++ b/scripts/e2e-smoke.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { Buffer } from 'node:buffer'; import { chmodSync, copyFileSync,