Repository navigation
fix(cli): save config and credentials atomically so parallel bgagent runs never read a partial file (#1080) #1081
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
abhiramshaji-cyber
wants to merge
3
commits into
aws-samples:main
from
abhiramshaji-cyber:fix/atomic-config-writes
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
6ea9530
fix(cli): save config and credentials atomically so parallel runs nev…
abhiramshaji-cyber 7defc2b
fix(cli): write in place when a file cannot be swapped by rename (#1080)
abhiramshaji-cyber 0b8ee22
fix(cli): build the temp file path without path.join so the semgrep s…
abhiramshaji-cyber File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<typeof fs>('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'); | ||
| }); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.