diff --git a/cli/src/config.ts b/cli/src/config.ts index 1ffc112ae..07b40b578 100644 --- a/cli/src/config.ts +++ b/cli/src/config.ts @@ -21,6 +21,7 @@ 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'; @@ -29,6 +30,7 @@ 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; /** Returns the config directory path (~/.bgagent or BGAGENT_CONFIG_DIR). */ export function getConfigDir(): string { @@ -74,7 +76,7 @@ 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 }); + replaceFile(configPath(), JSON.stringify(config, null, 2) + '\n', CONFIG_FILE_MODE); } /** Load existing CLI config if present, else return null (no error). */ @@ -112,14 +114,7 @@ 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); } /** Save credentials with restricted permissions. */ diff --git a/cli/src/replace-file.ts b/cli/src/replace-file.ts new file mode 100644 index 000000000..e48d19faa --- /dev/null +++ b/cli/src/replace-file.ts @@ -0,0 +1,96 @@ +/** + * 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 { 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 { + 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 1d96d28b5..d07eda3b7 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,49 @@ 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 Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + }); + + 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(tmpDir, '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); + }); }); }); 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'); + }); +});