diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2976e7f..03caef6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -64,14 +64,17 @@ touching callers. Every write (a refresh, `auth login`, `auth logout`, a profile rename or delete) reads, changes and rewrites the whole file while holding `credentials.json.lock` -beside it, and the rewrite is a temp file renamed into place, retried briefly -when Windows refuses the rename for a moment. The lock file is created +beside it, and the rewrite is a temp file renamed into place. While another +program has the file open (an antivirus scan, say), Windows can refuse the +write's read of the file and its rename over it; the two are retried together, +for about 5 s in all, before the write fails. The lock file is created exclusively and holds the holder's pid, host name, pid namespace (on Linux) and the time it was taken. A lock older than 30 s, or whose holder is gone, is taken over; a live one is waited on for up to 45 s. The pid is trusted only on the host and in the pid namespace that wrote it: sandboxes and containers that give each command a pid namespace of its own give them equal pids, so elsewhere a lock is -judged by its age alone. A lock is +judged by its age alone. A Linux process that can't read its own pid namespace +(a sandbox that hides `/proc`) trusts no other process's pid. A lock is only ever removed, by its holder letting go or by a takeover, under a second exclusive file, `credentials.json.lock.guard`, after reading it again, so no process removes a lock it hasn't just checked. Letting go is best effort: a lock diff --git a/src/__tests__/auth/resolve.test.ts b/src/__tests__/auth/resolve.test.ts index 3d45002..f27599d 100644 --- a/src/__tests__/auth/resolve.test.ts +++ b/src/__tests__/auth/resolve.test.ts @@ -82,8 +82,9 @@ describe('auth/resolve — credential precedence', ()=>{ }); // Breaks if a record with nothing to refresh it is kept, or if one another process stored while - // this one waited for the lock (a new login, say) is removed in its place. - it('clears the record and errors when an expired token has no refresh token, unless the lock shows a newer one', async()=>{ + // this one waited for the lock (a new login, say) is removed in its place. Or if a caller that + // can't refresh deletes a sign-in nothing refused. + it('fails auth.expired on an expired token it can\'t refresh, removing it only when the record has no refresh token and the lock shows nothing newer', async()=>{ const {store, map} = fake_store({[HOST]: fresh_oauth({expires_at: NOW - 1, refresh_token: undefined})}); await expect(resolve_credential({}, {key: HOST, store, env: {}, now: NOW, refresh: vi.fn()})) .rejects.toMatchObject({code: 'auth.expired'}); @@ -97,6 +98,18 @@ describe('auth/resolve — credential precedence', ()=>{ const r = await resolve_credential({}, {key: HOST, store: peer.store, env: {}, now: NOW, refresh: vi.fn()}); expect(r).toMatchObject({token: 'peer_at', type: 'oauth', source: 'store'}); expect(peer.map[HOST]).toEqual(fresh_oauth({access_token: 'peer_at'})); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-expired-')); + try { + const file = path.join(dir, 'credentials.json'); + fs.writeFileSync(file, JSON.stringify({[HOST]: fresh_oauth({expires_at: NOW - 1})}, null, 2)); + const before = fs.readFileSync(file); + await expect(resolve_credential({}, {key: HOST, store: new FileCredentialStore(file), env: {}, now: NOW})) + .rejects.toMatchObject({code: 'auth.expired'}); + expect(fs.readFileSync(file).equals(before)).toBe(true); + } finally { + fs.rmSync(dir, {recursive: true, force: true}); + } }); it('errors (UsageError) when nothing is available and writes nothing', async()=>{ diff --git a/src/__tests__/credentials/file-store.test.ts b/src/__tests__/credentials/file-store.test.ts index ad139ed..e3854de 100644 --- a/src/__tests__/credentials/file-store.test.ts +++ b/src/__tests__/credentials/file-store.test.ts @@ -1,4 +1,4 @@ -import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest'; +import {describe, it, expect, beforeAll, beforeEach, afterEach, vi} from 'vitest'; import {spawnSync} from 'child_process'; import fs from 'fs'; import os from 'os'; @@ -109,48 +109,133 @@ describe('credentials/FileCredentialStore', ()=>{ await expect(store.keys()).rejects.toBeInstanceOf(RuntimeError); }); - // Breaks if a write gives up the moment Windows refuses a rename over a file another process - // is reading: a token the server already rotated would be lost with it. Or if two writes share - // a temp file: two writers with one pid (each in a pid namespace of its own) would rename each - // other's. - it('retries a rename refused for a moment, from a temp file of its own', async()=>{ - const rename = fs.renameSync; - let refused = false; + // Breaks if a write gives up while Windows still refuses its read or its rename because another + // program has the file open, which an antivirus scan or a backup can keep up for seconds: a token + // the server already rotated would be lost with it. Or if the read and the rename each wait a + // budget of their own, so a refresh can outlast the lock's stale age; or if a refusal that doesn't + // end hangs the write or leaves its temp file behind; or if a read is retried off Windows, where a + // refusal is a permission no retry fixes; or if a plain read waits too: a refresh's re-read comes + // before its request, and would push it past the stale age. Or if two writes share a temp file: + // two writers with one pid (each in a pid namespace of its own) would rename each other's. + it('retries a write\'s read (on Windows) and its rename refused for seconds, from a temp file of its own, within one budget of about 5 s per write', async()=>{ + await store.set('h', API_KEY); + const real = { + read: fs.readFileSync, rename: fs.renameSync, + platform: Object.getOwnPropertyDescriptor(process, 'platform') as PropertyDescriptor, + }; + let refused = {read_until: 0, read_code: 'EBUSY', rename_until: 0}; const temps: string[] = []; - const spy = vi.spyOn(fs, 'renameSync').mockImplementation((from, to)=>{ - if (String(to) === file) + const spies = [ + vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathOrFileDescriptor, ...rest: unknown[])=>{ + if (String(target) === file && Date.now() < refused.read_until) + { + throw Object.assign(new Error(`${refused.read_code}: refused, open '${target}'`), {code: refused.read_code}); + } + return (real.read as (...a: unknown[]) => unknown)(target, ...rest); + }) as typeof fs.readFileSync), + vi.spyOn(fs, 'renameSync').mockImplementation((from, to)=>{ + if (String(to) === file) + { + temps.push(String(from)); + if (Date.now() < refused.rename_until) + { + throw Object.assign(new Error(`EPERM: operation not permitted, rename '${from}'`), {code: 'EPERM'}); + } + } + real.rename(from, to); + }), + ]; + type Case = { + name: string; + platform?: NodeJS.Platform; + op?: 'get' | 'keys'; + read?: {code: string; for_ms: number}; + rename_for_ms?: number; + ends: string; + within_ms: [number, number]; + }; + const CASES: Case[] = [ + {name: 'a rename refused for 2 s', rename_for_ms: 2_000, ends: 'stored', within_ms: [2_000, 3_000]}, { - temps.push(String(from)); - } - if (!refused && String(to) === file) + name: 'on Windows, a read refused for 1 s, then the rename until 2 s', platform: 'win32', + read: {code: 'EBUSY', for_ms: 1_000}, rename_for_ms: 2_000, ends: 'stored', within_ms: [2_000, 3_000], + }, { - refused = true; - throw Object.assign(new Error(`EPERM: operation not permitted, rename '${from}'`), {code: 'EPERM'}); - } - rename(from, to); - }); + name: 'on Windows, a read refused for 3 s, then the rename for good', platform: 'win32', + read: {code: 'EBUSY', for_ms: 3_000}, rename_for_ms: Infinity, ends: 'EPERM', within_ms: [4_500, 6_000], + }, + { + name: 'on Windows, a read refused for good', platform: 'win32', + read: {code: 'EBUSY', for_ms: Infinity}, ends: 'store.read', within_ms: [4_500, 6_000], + }, + {name: 'a rename refused for good', rename_for_ms: Infinity, ends: 'EPERM', within_ms: [4_500, 6_000]}, + { + name: 'on Linux, a read refused', platform: 'linux', + read: {code: 'EACCES', for_ms: Infinity}, ends: 'store.read', within_ms: [0, 0], + }, + { + name: 'on Windows, a plain get with the read refused for good', platform: 'win32', op: 'get', + read: {code: 'EBUSY', for_ms: Infinity}, ends: 'store.read', within_ms: [0, 0], + }, + { + name: 'on Windows, a plain keys with the read refused for good', platform: 'win32', op: 'keys', + read: {code: 'EBUSY', for_ms: Infinity}, ends: 'store.read', within_ms: [0, 0], + }, + ]; + const got: Record = {}; + vi.useFakeTimers(); try { - await store.set('h', API_KEY); - await store.set('h2', OAUTH); + for (const [i, c] of CASES.entries()) + { + const started = Date.now(); + refused = { + read_until: started + (c.read?.for_ms ?? 0), read_code: c.read?.code ?? 'EBUSY', + rename_until: started + (c.rename_for_ms ?? 0), + }; + Object.defineProperty(process, 'platform', {...real.platform, value: c.platform ?? real.platform.value}); + try { + const op = c.op === 'get' ? store.get('h') : c.op === 'keys' ? store.keys() : store.set(`k${i}`, OAUTH); + const ends = op.then(()=>(c.op ? 'read' : 'stored'), (e: {code?: string})=>String(e.code)); + await vi.runAllTimersAsync(); + got[c.name] = {ends: await ends, ms: Date.now() - started}; + } finally { + Object.defineProperty(process, 'platform', real.platform); + } + } } finally { - spy.mockRestore(); + vi.useRealTimers(); + spies.forEach(s=>s.mockRestore()); } - expect(refused).toBe(true); - expect(await store.get('h')).toEqual(API_KEY); - expect(temps).toHaveLength(3); - expect(new Set(temps).size).toBe(2); + expect(Object.fromEntries(CASES.map(c=>[c.name, got[c.name].ends]))) + .toEqual(Object.fromEntries(CASES.map(c=>[c.name, c.ends]))); + for (const c of CASES) + { + expect(got[c.name].ms, c.name).toBeGreaterThanOrEqual(c.within_ms[0]); + expect(got[c.name].ms, c.name).toBeLessThanOrEqual(c.within_ms[1]); + } + expect(await store.keys()).toEqual(['h', 'k0', 'k1']); + expect(fs.readdirSync(path.dirname(file)).filter(name=>name.endsWith('.tmp'))).toEqual([]); + // The four writes that reached a rename: one temp file each, kept through its retries. + expect(new Set(temps).size).toBe(4); + expect(temps.length).toBeGreaterThan(4); }); }); describe('credentials/FileCredentialStore — the lock beside the file', ()=>{ const HOST = os.hostname(); - const PID_NS = ((): string | undefined=>{ + // This process's pid namespace as the store names it, read from a lock the store writes: where + // /proc is hidden, that name is the store's own making. + let PID_NS: string | undefined; + beforeAll(async()=>{ + const probe = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'reply-ns-')), 'credentials.json'); try { - return fs.readlinkSync('/proc/self/ns/pid'); - } catch { - return undefined; + await new FileCredentialStore(probe).with_lock(async()=>{ + PID_NS = JSON.parse(fs.readFileSync(`${probe}.lock`, 'utf8')).ns; + }); + } finally { + fs.rmSync(path.dirname(probe), {recursive: true, force: true}); } - })(); + }); const lock = ()=>`${file}.lock`; // Another process's lock as it sits on disk, by default from this host and pid namespace. A // live holder is this test's parent process. @@ -283,11 +368,34 @@ describe('credentials/FileCredentialStore — the lock beside the file', ()=>{ expect(await s.get('h')).toEqual(API_KEY); }); + // The store as loaded by a process on `platform` that can't read its pid namespace, as in a + // sandbox that hides /proc. + const load_without_ns = async(platform: NodeJS.Platform): Promise=>{ + const real = {platform: Object.getOwnPropertyDescriptor(process, 'platform') as PropertyDescriptor, readlink: fs.readlinkSync}; + const spy = vi.spyOn(fs, 'readlinkSync').mockImplementation(((target: fs.PathLike, ...rest: unknown[])=>{ + if (String(target) === '/proc/self/ns/pid') + { + throw Object.assign(new Error(`ENOENT: no such file or directory, readlink '${target}'`), {code: 'ENOENT'}); + } + return (real.readlink as (...a: unknown[]) => unknown)(target, ...rest); + }) as typeof fs.readlinkSync); + Object.defineProperty(process, 'platform', {...real.platform, value: platform}); + try { + vi.resetModules(); + return (await import('../../credentials/file-store')).FileCredentialStore; + } finally { + spy.mockRestore(); + Object.defineProperty(process, 'platform', real.platform); + } + }; + // Breaks if a pid from another host or another pid namespace is read as this one's: a holder // alive there would be taken over at once. Sandboxes that give every command its own pid // namespace give them all the same pid, so a lock with this process's pid that it didn't leave - // itself is a live peer's. Or if a holder that hangs keeps the lock for good. - it('judges a lock from another host or pid namespace by its age alone, and takes over one held longer than a refresh can run', async()=>{ + // itself is a live peer's. On Linux, two processes that can't read their namespaces can't tell + // whether they share one, so neither trusts the other's pid; elsewhere no process has one, and + // a dead holder's lock is taken over at once. Or if a holder that hangs keeps the lock for good. + it('judges a lock from another host or pid namespace, or from a Linux process that can\'t read its own, by its age alone, and takes over one held longer than a refresh can run', async()=>{ const peers = [ {pid: gone_pid(), host: `not-${HOST}`, taken_at: Date.now()}, {pid: gone_pid(), ns: `${PID_NS ?? 'pid:[1]'}-elsewhere`, taken_at: Date.now()}, @@ -303,6 +411,22 @@ describe('credentials/FileCredentialStore — the lock beside the file', ()=>{ } expect(outcomes).toEqual(['store.locked', 'store.locked', 'store.locked']); + const blind: Record = {}; + for (const platform of ['linux', 'win32'] as const) + { + fs.rmSync(lock(), {force: true}); + const [Peer, Mine] = [await load_without_ns(platform), await load_without_ns(platform)]; + let peer_lock: {ns?: string; id?: string} = {}; + await new Peer(file).with_lock(async()=>{ + peer_lock = JSON.parse(fs.readFileSync(lock(), 'utf8')); + }); + hold_lock({pid: gone_pid(), ns: peer_lock.ns, id: peer_lock.id, taken_at: Date.now()}); + blind[platform] = await new Mine(file, {lock: {wait_ms: 300}}).set('h', API_KEY) + .then(()=>'taken over', (e: {code?: string})=>String(e.code)); + fs.rmSync(file, {force: true}); + } + expect(blind).toEqual({linux: 'store.locked', win32: 'taken over'}); + hold_lock({pid: process.ppid, taken_at: Date.now() - 5_000}); const s = new FileCredentialStore(file, {lock: {wait_ms: 2_000, stale_ms: 1_000}}); await s.set('h', API_KEY); diff --git a/src/auth/resolve.ts b/src/auth/resolve.ts index 709ce6f..9ebd943 100644 --- a/src/auth/resolve.ts +++ b/src/auth/resolve.ts @@ -177,7 +177,8 @@ const refresh_under_lock = async( // STRICT precedence: 1) --api-key flag 2) _API_KEY env 3) stored // credential. Flag/env are ephemeral and are never written to disk. A stored // oauth record is refreshed when expired, one process at a time. It is removed -// only when the server refuses the grant; any other failure keeps it. +// only when the server refuses the grant or it has no refresh token; any other +// failure keeps it. const resolve_credential = async( opts: Resolve_opts, deps: Resolve_deps, @@ -208,7 +209,6 @@ const resolve_credential = async( const refresh = deps.refresh; if (!refresh) { - await deps.store.remove(deps.key); throw session_expired(); } diff --git a/src/credentials/file-store.ts b/src/credentials/file-store.ts index 9944aef..a629c25 100644 --- a/src/credentials/file-store.ts +++ b/src/credentials/file-store.ts @@ -9,9 +9,14 @@ import type {Credential_record, CredentialStore} from './types'; type Key_map = Record; -// On Windows a rename over a file another process has open can fail for a moment. -const RENAME_RETRY_MS = [20, 40, 80, 160, 320]; -const RENAME_BUSY = ['EPERM', 'EACCES', 'EBUSY']; +// On Windows, while another program has the file open (an antivirus scan or a backup can take +// seconds), a read of it and a rename over it can be refused. A write's read and rename wait out +// those refusals from one copy of these waits: about 5 s in all, so that with the token request a +// refresh still lets go of the lock before it counts as stale. +const BUSY_RETRY_MS = [20, 40, 80, 160, 320, 640, 1_000, 1_000, 1_000, 1_000]; +const BUSY = ['EPERM', 'EACCES', 'EBUSY']; + +const pause = (ms: number): Promise=>new Promise(resolve=>setTimeout(resolve, ms)); // v1 credential backend: a single JSON file keyed by profile name, written // with strict 0600 perms in a 0700 dir (the gh/aws/az plaintext-file model). @@ -29,35 +34,37 @@ class FileCredentialStore implements CredentialStore { async get(key: string): Promise { - return this.read()[key]; + return (await this.read())[key]; } async set(key: string, record: Credential_record): Promise { await this.with_lock(async()=>{ - const map = this.read(); + const waits = [...BUSY_RETRY_MS]; + const map = await this.read(waits); map[key] = record; - await this.write(map); + await this.write(map, waits); }); } async remove(key: string, only_if?: (record: Credential_record) => boolean): Promise { return this.with_lock(async()=>{ - const map = this.read(); + const waits = [...BUSY_RETRY_MS]; + const map = await this.read(waits); if (!(key in map) || (only_if && !only_if(map[key]))) { return false; } delete map[key]; - await this.write(map); + await this.write(map, waits); return true; }); } async keys(): Promise { - return Object.keys(this.read()); + return Object.keys(await this.read()); } async with_lock(fn: () => Promise): Promise @@ -74,20 +81,34 @@ class FileCredentialStore implements CredentialStore { } } - private read(): Key_map + // Only the read a write starts with waits, from the write's `waits`, and only on Windows: + // elsewhere these codes are a permission no wait fixes. A plain read fails at once and loses + // nothing, since a refresh reads before it sends its request; waiting there would add to its + // time under the lock. + private async read(waits: number[] = []): Promise { let raw: string; - try { - raw = fs.readFileSync(this.file, 'utf8'); - } catch (e) { - if ((e as NodeJS.ErrnoException).code === 'ENOENT') - { - return {}; + for (;;) + { + try { + raw = fs.readFileSync(this.file, 'utf8'); + break; + } catch (e) { + const code = (e as NodeJS.ErrnoException).code; + if (code === 'ENOENT') + { + return {}; + } + const wait = process.platform === 'win32' && BUSY.includes(String(code)) ? waits.shift() : undefined; + if (wait === undefined) + { + throw new RuntimeError('Could not read the credential store.', { + code: 'store.read', detail: this.file, + hint: (e as Error).message, + }); + } + await pause(wait); } - throw new RuntimeError('Could not read the credential store.', { - code: 'store.read', detail: this.file, - hint: (e as Error).message, - }); } if (!raw.trim()) { @@ -114,7 +135,7 @@ class FileCredentialStore implements CredentialStore { // Atomic write: temp file created 0600, then renamed into place so the // final file is never briefly world-readable and rewrites keep 0600. - private async write(map: Key_map): Promise + private async write(map: Key_map, waits: number[]): Promise { const dir = path.dirname(this.file); fs.mkdirSync(dir, {recursive: true, mode: 0o700}); @@ -123,19 +144,20 @@ class FileCredentialStore implements CredentialStore { const tmp = `${this.file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`; fs.writeFileSync(tmp, JSON.stringify(map, null, 2), {mode: 0o600}); fs.chmodSync(tmp, 0o600); - for (let attempt = 0; ; attempt++) + for (;;) { try { fs.renameSync(tmp, this.file); return; } catch (e) { - if (attempt >= RENAME_RETRY_MS.length || !RENAME_BUSY.includes(String((e as NodeJS.ErrnoException).code))) + const wait = BUSY.includes(String((e as NodeJS.ErrnoException).code)) ? waits.shift() : undefined; + if (wait === undefined) { fs.rmSync(tmp, {force: true}); throw e; } + await pause(wait); } - await new Promise(resolve=>setTimeout(resolve, RENAME_RETRY_MS[attempt])); } } } diff --git a/src/credentials/lock.ts b/src/credentials/lock.ts index b2cdb29..335d314 100644 --- a/src/credentials/lock.ts +++ b/src/credentials/lock.ts @@ -13,6 +13,13 @@ import {RuntimeError} from '../utils/errors'; // holder letting go or a stale one taken over, happens under a second exclusive file, the guard, // after reading the lock again: so the lock read is the lock removed, and no process removes a // lock it has not just checked. +// +// Breaking a guard left stale is not serialised in turn: try_guard reads it, compares and unlinks +// it as separate steps, so two processes breaking one stale guard together can unlink a guard a +// third has just taken (as can a holder that stalled that long, letting go when it wakes), and two +// processes can then hold the lock at once. That is accepted: a guard goes stale only when its +// holder dies, stalls for 5 s in the instant it holds it, or can't delete it, and closing the gap +// would take an OS file lock, which Node has no API for. type Lock_opts = { wait_ms?: number; // how long to wait for another holder before giving up @@ -24,7 +31,8 @@ type Lock_opts = { const LOCK_STALE_MS = TOKEN_TIMEOUT_MS + 10_000; const LOCK_WAIT_MS = LOCK_STALE_MS + 15_000; const POLL_MS = 50; -// The guard is held for a read and an unlink; one this old was left by a process that died holding it. +// The guard is held for a read and an unlink; one this old was left by a holder that died, stalled +// or couldn't delete it. const GUARD_STALE_MS = 5_000; // How long Windows may refuse a create with no lock in place: a lock being deleted refuses it for // a moment, and a directory that can't be written refuses it for good. @@ -32,14 +40,18 @@ const CREATE_GRACE_MS = 1_000; const RELEASE_RETRY_MS = [20, 40, 80, 160, 320]; const WINDOWS_BUSY = ['EPERM', 'EACCES', 'EBUSY']; +const new_id = (): string=>crypto.randomBytes(8).toString('hex'); + // A pid means something only in its own pid namespace: sandboxes and containers that give each // command a namespace of its own give them all the same pid, or each other's. Linux names the -// namespace; elsewhere there is none to tell apart. +// namespace; elsewhere there is none to tell apart. A Linux process that can't read its own (a +// sandbox that hides /proc) can't tell whether a peer shares it, so it takes a name no other +// process has, and judges every other process's lock by its age alone. const PID_NS = ((): string | undefined=>{ try { return fs.readlinkSync('/proc/self/ns/pid'); } catch { - return undefined; + return process.platform === 'linux' ? `unknown:${new_id()}` : undefined; } })(); @@ -47,8 +59,6 @@ const PID_NS = ((): string | undefined=>{ // pid that are known not to be held. const left_here = new Set(); -const new_id = (): string=>crypto.randomBytes(8).toString('hex'); - class Lock_timeout_error extends RuntimeError { constructor(file: string) {