From 6ea9530f57164d20cd24821fdb1cd134a90e32a4 Mon Sep 17 00:00:00 2001 From: Abhiram Shaji Date: Tue, 24 Nov 2026 19:38:52 -0500 Subject: [PATCH 1/3] fix(cli): save config and credentials atomically so parallel runs never read a partial file (#1080) --- cli/src/config.ts | 46 +++++++++++++++++++++++++------ cli/test/config.test.ts | 60 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 8 deletions(-) diff --git a/cli/src/config.ts b/cli/src/config.ts index 1ffc112ae..6ad3a80f6 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -17,6 +17,7 @@ * SOFTWARE. */ +import { randomUUID } from 'crypto'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -29,6 +30,8 @@ const CREDENTIALS_FILE = 'credentials.json'; /** Owner-only read/write — credentials must never be group/world readable. */ const SECRET_FILE_MODE = 0o600; +const CONFIG_FILE_MODE = 0o644; +const PERMISSION_MODULUS = 0o10000; /** Returns the config directory path (~/.bgagent or BGAGENT_CONFIG_DIR). */ export function getConfigDir(): string { @@ -74,7 +77,9 @@ export function loadConfig(): CliConfig { /** Save CLI configuration. */ export function saveConfig(config: CliConfig): void { ensureConfigDir(); - fs.writeFileSync(configPath(), JSON.stringify(config, null, 2) + '\n', { mode: 0o644 }); + const p = configPath(); + const existing = fs.statSync(p, { throwIfNoEntry: false }); + replaceFile(p, JSON.stringify(config, null, 2) + '\n', CONFIG_FILE_MODE, existing && existing.mode % PERMISSION_MODULUS); } /** Load existing CLI config if present, else return null (no error). */ @@ -112,13 +117,38 @@ export function clearCredentials(): void { /** Write a file that only its owner may read, whether it is new or already there. */ export function writeSecretFile(file: string, content: string): void { - fs.writeFileSync(file, content, { mode: SECRET_FILE_MODE }); - // writeFileSync only honors `mode` when CREATING the file; overwriting a - // pre-existing loose-permissions file leaves its bits untouched. chmod - // makes the 0600 intent durable across rewrites. Regular files only: a - // path the user chose may be a device such as /dev/null. - if (fs.statSync(file).isFile()) { - fs.chmodSync(file, SECRET_FILE_MODE); + replaceFile(file, content, SECRET_FILE_MODE, SECRET_FILE_MODE); +} + +function regularFileTarget(file: string): string | undefined { + try { + const real = fs.realpathSync(file); + return fs.statSync(real).isFile() ? real : undefined; + } catch (err) { + const creatable = (err as NodeJS.ErrnoException).code === 'ENOENT' + && !fs.lstatSync(file, { throwIfNoEntry: false }) + && fs.existsSync(path.dirname(file)); + return creatable ? file : undefined; + } +} + +function replaceFile(file: string, content: string, createMode: number, setMode?: number): void { + const target = regularFileTarget(file); + if (!target) { + fs.writeFileSync(file, content, { mode: createMode }); + return; + } + + const temp = path.join(path.dirname(target), `.${randomUUID()}.tmp`); + try { + fs.writeFileSync(temp, content, { mode: createMode, flag: 'wx' }); + if (setMode !== undefined) { + fs.chmodSync(temp, setMode); + } + fs.renameSync(temp, target); + } catch (err) { + fs.rmSync(temp, { force: true }); + throw err; } } diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts index 1d96d28b5..7607e4d23 100644 --- a/cli/test/config.test.ts +++ b/cli/test/config.test.ts @@ -23,6 +23,11 @@ import * as path from 'path'; import { loadConfig, loadCredentials, saveConfig, saveCredentials } from '../src/config'; import { CliError } from '../src/errors'; +jest.mock('fs', () => { + const actual = jest.requireActual('fs'); + return { ...actual, renameSync: jest.fn(actual.renameSync) }; +}); + describe('config', () => { let tmpDir: string; @@ -48,6 +53,16 @@ describe('config', () => { expect(loadConfig()).toEqual(config); }); + test('keeps the mode of a config file that already exists', () => { + const file = path.join(tmpDir, 'config.json'); + fs.writeFileSync(file, '{}'); + fs.chmodSync(file, 0o600); + + saveConfig({ api_url: 'https://api.example.com/v1', region: 'us-east-1', user_pool_id: 'p', client_id: 'c' }); + + expect(fs.statSync(file).mode % 0o1000).toBe(0o600); + }); + test('throws when config does not exist', () => { expect(() => loadConfig()).toThrow('Not configured'); }); @@ -118,5 +133,50 @@ describe('config', () => { expect(fs.statSync(p).mode % 0o1000).toBe(0o600); }); + + const before = { id_token: 'old', refresh_token: 'old-ref', token_expiry: '2026-01-01T00:00:00.000Z' }; + const after = { id_token: 'new', refresh_token: 'new-ref', token_expiry: '2026-02-01T00:00:00.000Z' }; + + test('a reader during a save sees the old credentials, then the new ones', () => { + saveCredentials(before); + let seen: unknown; + jest.mocked(fs.renameSync).mockImplementationOnce((from, to) => { + seen = loadCredentials(); + jest.requireActual('fs').renameSync(from, to); + }); + + saveCredentials(after); + + expect(seen).toEqual(before); + expect(loadCredentials()).toEqual(after); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('a failed save keeps the old credentials and leaves no temporary file', () => { + saveCredentials(before); + jest.mocked(fs.renameSync).mockImplementationOnce(() => { + throw new Error('EXDEV'); + }); + + expect(() => saveCredentials(after)).toThrow('EXDEV'); + + expect(loadCredentials()).toEqual(before); + expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); + }); + + test('a save through a symlink updates the linked file and keeps the link', () => { + const realDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bgagent-real-')); + const real = path.join(realDir, 'creds.json'); + const link = path.join(tmpDir, 'credentials.json'); + fs.writeFileSync(real, '{}', { mode: 0o644 }); + fs.symlinkSync(real, link); + + saveCredentials(after); + + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(JSON.parse(fs.readFileSync(real, 'utf-8'))).toEqual(after); + expect(fs.statSync(real).mode % 0o1000).toBe(0o600); + fs.rmSync(realDir, { recursive: true, force: true }); + }); }); }); From 7defc2b7a9699cc7e8a2ea1626cedd0a7425548b Mon Sep 17 00:00:00 2001 From: Abhiram Shaji Date: Wed, 25 Nov 2026 12:49:07 -0500 Subject: [PATCH 2/3] fix(cli): write in place when a file cannot be swapped by rename (#1080) A bind mounted file (EBUSY), a cross device rename (EXDEV), a directory that is not writable, or an owner the temporary file cannot take now falls back to the in place write. A hard linked file is written in place, a read only file is refused as before, the temporary file is created with its final mode, keeps the owner and group, and is synced before the rename. A failed cleanup no longer hides the original error. --- cli/src/config.ts | 39 +-------- cli/src/replace-file.ts | 95 +++++++++++++++++++++ cli/test/config.test.ts | 7 +- cli/test/replace-file.test.ts | 155 ++++++++++++++++++++++++++++++++++ 4 files changed, 255 insertions(+), 41 deletions(-) create mode 100644 cli/src/replace-file.ts create mode 100644 cli/test/replace-file.test.ts diff --git a/cli/src/config.ts b/cli/src/config.ts index 6ad3a80f6..07b40b578 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -17,11 +17,11 @@ * SOFTWARE. */ -import { randomUUID } from 'crypto'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { CliError } from './errors'; +import { replaceFile } from './replace-file'; import { CliConfig, Credentials } from './types'; const CONFIG_DIR_ENV = 'BGAGENT_CONFIG_DIR'; @@ -31,7 +31,6 @@ const CREDENTIALS_FILE = 'credentials.json'; /** Owner-only read/write — credentials must never be group/world readable. */ const SECRET_FILE_MODE = 0o600; const CONFIG_FILE_MODE = 0o644; -const PERMISSION_MODULUS = 0o10000; /** Returns the config directory path (~/.bgagent or BGAGENT_CONFIG_DIR). */ export function getConfigDir(): string { @@ -77,9 +76,7 @@ export function loadConfig(): CliConfig { /** Save CLI configuration. */ export function saveConfig(config: CliConfig): void { ensureConfigDir(); - const p = configPath(); - const existing = fs.statSync(p, { throwIfNoEntry: false }); - replaceFile(p, JSON.stringify(config, null, 2) + '\n', CONFIG_FILE_MODE, existing && existing.mode % PERMISSION_MODULUS); + replaceFile(configPath(), JSON.stringify(config, null, 2) + '\n', CONFIG_FILE_MODE); } /** Load existing CLI config if present, else return null (no error). */ @@ -120,38 +117,6 @@ export function writeSecretFile(file: string, content: string): void { replaceFile(file, content, SECRET_FILE_MODE, SECRET_FILE_MODE); } -function regularFileTarget(file: string): string | undefined { - try { - const real = fs.realpathSync(file); - return fs.statSync(real).isFile() ? real : undefined; - } catch (err) { - const creatable = (err as NodeJS.ErrnoException).code === 'ENOENT' - && !fs.lstatSync(file, { throwIfNoEntry: false }) - && fs.existsSync(path.dirname(file)); - return creatable ? file : undefined; - } -} - -function replaceFile(file: string, content: string, createMode: number, setMode?: number): void { - const target = regularFileTarget(file); - if (!target) { - fs.writeFileSync(file, content, { mode: createMode }); - return; - } - - const temp = path.join(path.dirname(target), `.${randomUUID()}.tmp`); - try { - fs.writeFileSync(temp, content, { mode: createMode, flag: 'wx' }); - if (setMode !== undefined) { - fs.chmodSync(temp, setMode); - } - fs.renameSync(temp, target); - } catch (err) { - fs.rmSync(temp, { force: true }); - throw err; - } -} - /** Save credentials with restricted permissions. */ export function saveCredentials(creds: Credentials): void { ensureConfigDir(); diff --git a/cli/src/replace-file.ts b/cli/src/replace-file.ts new file mode 100644 index 000000000..0eed2896a --- /dev/null +++ b/cli/src/replace-file.ts @@ -0,0 +1,95 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { randomUUID } from 'crypto'; +import * as fs from 'fs'; +import * as path from 'path'; + +const PERMISSION_MODULUS = 0o10000; +const RENAME_REFUSED = new Set(['EACCES', 'EPERM', 'EROFS', 'EBUSY', 'EXDEV', 'ENOTSUP']); + +export function replaceFile(file: string, content: string, createMode: number, setMode?: number): void { + const target = regularFileTarget(file); + const existing = target ? fs.statSync(target, { throwIfNoEntry: false }) : undefined; + const mode = setMode ?? (existing ? existing.mode % PERMISSION_MODULUS : undefined); + + if (!target || (existing && existing.nlink > 1)) { + writeInPlace(file, content, createMode, mode); + return; + } + + if (existing) { + fs.accessSync(target, fs.constants.W_OK); + } + try { + swapIn(target, content, mode ?? createMode, mode, existing); + } catch (err) { + if (!RENAME_REFUSED.has((err as NodeJS.ErrnoException).code ?? '')) { + throw err; + } + writeInPlace(target, content, createMode, mode); + } +} + +function regularFileTarget(file: string): string | undefined { + try { + const real = fs.realpathSync(file); + return fs.statSync(real).isFile() ? real : undefined; + } catch (err) { + const creatable = (err as NodeJS.ErrnoException).code === 'ENOENT' + && !fs.lstatSync(file, { throwIfNoEntry: false }) + && fs.existsSync(path.dirname(file)); + return creatable ? file : undefined; + } +} + +function writeInPlace(file: string, content: string, createMode: number, mode?: number): void { + fs.writeFileSync(file, content, { mode: createMode }); + if (mode !== undefined && fs.statSync(file).isFile()) { + fs.chmodSync(file, mode); + } +} + +function swapIn(target: string, content: string, openMode: number, mode?: number, owner?: fs.Stats): void { + const temp = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`); + const fd = fs.openSync(temp, 'wx', openMode); + try { + try { + fs.writeFileSync(fd, content); + // chown first: it clears setuid and setgid bits + if (owner) { + fs.fchownSync(fd, owner.uid, owner.gid); + } + if (mode !== undefined) { + fs.fchmodSync(fd, mode); + } + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + fs.renameSync(temp, target); + } catch (err) { + try { + fs.rmSync(temp, { force: true }); + } catch { + throw err; + } + throw err; + } +} diff --git a/cli/test/config.test.ts b/cli/test/config.test.ts index 7607e4d23..d07eda3b7 100644 --- a/cli/test/config.test.ts +++ b/cli/test/config.test.ts @@ -155,17 +155,17 @@ describe('config', () => { test('a failed save keeps the old credentials and leaves no temporary file', () => { saveCredentials(before); jest.mocked(fs.renameSync).mockImplementationOnce(() => { - throw new Error('EXDEV'); + throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); }); - expect(() => saveCredentials(after)).toThrow('EXDEV'); + expect(() => saveCredentials(after)).toThrow('ENOSPC'); expect(loadCredentials()).toEqual(before); expect(fs.readdirSync(tmpDir)).toEqual(['credentials.json']); }); test('a save through a symlink updates the linked file and keeps the link', () => { - const realDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bgagent-real-')); + const realDir = fs.mkdtempSync(path.join(tmpDir, 'real-')); const real = path.join(realDir, 'creds.json'); const link = path.join(tmpDir, 'credentials.json'); fs.writeFileSync(real, '{}', { mode: 0o644 }); @@ -176,7 +176,6 @@ describe('config', () => { expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); expect(JSON.parse(fs.readFileSync(real, 'utf-8'))).toEqual(after); expect(fs.statSync(real).mode % 0o1000).toBe(0o600); - fs.rmSync(realDir, { recursive: true, force: true }); }); }); }); diff --git a/cli/test/replace-file.test.ts b/cli/test/replace-file.test.ts new file mode 100644 index 000000000..e49badf88 --- /dev/null +++ b/cli/test/replace-file.test.ts @@ -0,0 +1,155 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { replaceFile } from '../src/replace-file'; + +jest.mock('fs', () => { + const actual = jest.requireActual('fs'); + return { + ...actual, + openSync: jest.fn(actual.openSync), + fchownSync: jest.fn(actual.fchownSync), + renameSync: jest.fn(actual.renameSync), + rmSync: jest.fn(actual.rmSync), + }; +}); + +const errno = (code: string) => Object.assign(new Error(`${code}: refused`), { code }); +const codeOf = (write: () => void) => { + let code: string | undefined; + try { + write(); + } catch (err) { + code = (err as NodeJS.ErrnoException).code; + } + return code; +}; + +describe('replaceFile', () => { + let dir: string; + let file: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bgagent-replace-')); + file = path.join(dir, 'credentials.json'); + fs.writeFileSync(file, 'old', { mode: 0o644 }); + }); + + afterEach(() => { + fs.chmodSync(dir, 0o700); + fs.rmSync(dir, { recursive: true, force: true }); + jest.clearAllMocks(); + }); + + test('creates the temporary file with the final mode, so it is never looser than the result', () => { + fs.chmodSync(file, 0o600); + + replaceFile(file, 'new', 0o644); + + expect(fs.openSync).toHaveBeenCalledWith(expect.stringMatching(/\.tmp$/), 'wx', 0o600); + expect(fs.statSync(file).mode % 0o1000).toBe(0o600); + }); + + test('keeps the owner and group of the file it replaces', () => { + const { uid, gid } = fs.statSync(file); + + replaceFile(file, 'new', 0o600, 0o600); + + expect(fs.fchownSync).toHaveBeenCalledWith(expect.any(Number), uid, gid); + expect(fs.readFileSync(file, 'utf-8')).toBe('new'); + }); + + test.each(['EBUSY', 'EXDEV', 'EPERM', 'EACCES'])( + 'writes in place when the rename is refused with %s, as for a bind mounted file', + (code) => { + const { ino } = fs.statSync(file); + jest.mocked(fs.renameSync).mockImplementationOnce(() => { + throw errno(code); + }); + + replaceFile(file, 'new', 0o600, 0o600); + + expect(fs.readFileSync(file, 'utf-8')).toBe('new'); + expect(fs.statSync(file).ino).toBe(ino); + expect(fs.statSync(file).mode % 0o1000).toBe(0o600); + expect(fs.readdirSync(dir)).toEqual(['credentials.json']); + }, + ); + + test('writes in place when the file belongs to an owner the temporary file cannot take', () => { + const { ino } = fs.statSync(file); + jest.mocked(fs.fchownSync).mockImplementationOnce(() => { + throw errno('EPERM'); + }); + + replaceFile(file, 'new', 0o600, 0o600); + + expect(fs.readFileSync(file, 'utf-8')).toBe('new'); + expect(fs.statSync(file).ino).toBe(ino); + expect(fs.readdirSync(dir)).toEqual(['credentials.json']); + }); + + test('writes in place when the directory is not writable but the file is', () => { + fs.chmodSync(dir, 0o555); + + replaceFile(file, 'new', 0o600, 0o600); + + expect(fs.readFileSync(file, 'utf-8')).toBe('new'); + expect(fs.statSync(file).mode % 0o1000).toBe(0o600); + }); + + test('treats a read only file exactly as a plain write does', () => { + const plain = path.join(dir, 'plain.json'); + fs.writeFileSync(plain, 'old'); + fs.chmodSync(plain, 0o444); + fs.chmodSync(file, 0o444); + + const plainCode = codeOf(() => fs.writeFileSync(plain, 'new')); + const code = codeOf(() => replaceFile(file, 'new', 0o600, 0o600)); + + expect(code).toBe(plainCode); + expect(fs.readFileSync(file, 'utf-8')).toBe(fs.readFileSync(plain, 'utf-8')); + }); + + test('writes a hard linked file in place, so every link sees the new content', () => { + const other = path.join(dir, 'other.json'); + fs.linkSync(file, other); + + replaceFile(file, 'new', 0o600, 0o600); + + expect(fs.readFileSync(other, 'utf-8')).toBe('new'); + expect(fs.statSync(file).ino).toBe(fs.statSync(other).ino); + }); + + test('reports the original error when removing the temporary file fails too', () => { + jest.mocked(fs.renameSync).mockImplementationOnce(() => { + throw errno('ENOSPC'); + }); + jest.mocked(fs.rmSync).mockImplementationOnce(() => { + throw errno('EIO'); + }); + + expect(() => replaceFile(file, 'new', 0o600, 0o600)).toThrow('ENOSPC'); + + expect(fs.readFileSync(file, 'utf-8')).toBe('old'); + }); +}); From 0b8ee22f30feba51c675c88d2c0bb70f178d5069 Mon Sep 17 00:00:00 2001 From: Abhiram Shaji Date: Wed, 25 Nov 2026 13:26:18 -0500 Subject: [PATCH 3/3] fix(cli): build the temp file path without path.join so the semgrep scan passes (#1080) --- cli/src/replace-file.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cli/src/replace-file.ts b/cli/src/replace-file.ts index 0eed2896a..e48d19faa 100644 --- a/cli/src/replace-file.ts +++ b/cli/src/replace-file.ts @@ -67,7 +67,8 @@ function writeInPlace(file: string, content: string, createMode: number, mode?: } function swapIn(target: string, content: string, openMode: number, mode?: number, owner?: fs.Stats): void { - const temp = path.join(path.dirname(target), `.${path.basename(target)}.${randomUUID()}.tmp`); + const { root, dir, base } = path.parse(target); + const temp = path.format({ root, dir, base: `.${base}.${randomUUID()}.tmp` }); const fd = fs.openSync(temp, 'wx', openMode); try { try {