From de6aa8ae9d4ad7337b1d9c29ca32e3181d0107a6 Mon Sep 17 00:00:00 2001 From: vigubikReply Date: Wed, 25 Nov 2026 18:04:37 -0500 Subject: [PATCH] fix(auth): keep the sign-in when a token refresh fails for a passing reason A stored OAuth sign-in was deleted whenever a token refresh failed, whatever the reason. A 429, a 5xx, a timeout, a network error, or two reply processes refreshing one expired one-time refresh token together all signed the person out, and an app that starts several reply commands at once met the last one most of all. - The stored record is removed only when the identity server refuses the grant (400 invalid_grant) and the credentials file still holds the refused record, decided on the same read the removal rewrites. If another process stored a newer one meanwhile, that one is used and nothing is removed. - Another OAuth refusal (400 or 401 with an error) keeps the record and fails auth.refresh_failed, exit 2. A 429 keeps it and fails rate_limited with retry_after. Any other answer, a timeout (20 s), a network error or a 2xx without an access token keeps it and fails reply.unavailable, exit 1. - One refresh at a time across processes: credentials.json.lock, created exclusively beside the file, holds its holder's pid, host, pid namespace 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 same host and in the same pid namespace, since sandboxes that give each command a namespace of its own give them equal pids. A lock is only removed, when let go or taken over, under a guard file after reading it again, so no two processes hold it at once. Letting go never fails the command. Under the lock the record is read again, and a token another process already refreshed is used with no request. - Every write to the file (a refresh, login, logout, a profile rename or delete) is a read-modify-write under the lock; a rename moves the credential in one locked step. The new token is stored as soon as the answer is read, by the same temp-file rename, now retried briefly when Windows refuses it for a moment. - The error keeps what the token endpoint said under details.refresh: status and error, or a reason (timeout, network, unreadable, lock_wait). No token is ever printed. - Every token request, a refresh or a login's code exchange, sends the CLI's User-Agent, as API requests do, instead of Node's default, so the identity server's logs can tell them apart. A test runs two built CLI processes against a local fake identity server that rotates one-time refresh tokens and holds the first refresh until the second arrives: both end signed in, on one refresh. --- CONTRIBUTING.md | 48 +++- README.md | 13 +- skills/reply-adapter/reply-cli/SKILL.md | 11 +- src/__tests__/auth/oauth-flow.test.ts | 35 ++- src/__tests__/auth/refresh-processes.test.ts | 165 +++++++++++ src/__tests__/auth/resolve.test.ts | 272 +++++++++++++++++-- src/__tests__/commands/profile.test.ts | 42 ++- src/__tests__/credentials/file-store.test.ts | 262 +++++++++++++++++- src/auth/oauth-flow.ts | 104 +++++-- src/auth/resolve.ts | 192 +++++++++++-- src/auth/token.ts | 13 +- src/commands/profile.ts | 15 +- src/credentials/file-store.ts | 75 +++-- src/credentials/lock.ts | 229 ++++++++++++++++ src/credentials/types.ts | 6 +- src/utils/client.ts | 2 +- src/utils/errors.ts | 6 +- 17 files changed, 1380 insertions(+), 110 deletions(-) create mode 100644 src/__tests__/auth/refresh-processes.test.ts create mode 100644 src/credentials/lock.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 06752d2..2976e7f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,8 +21,10 @@ npm link # put the built `reply` binary on your PATH The suite is fully offline — no test contacts the Reply.io API or the identity server. `fetch` is stubbed, and the OAuth loopback flow is exercised against a -local `127.0.0.1` listener with an injected browser stub. CI runs the build and -tests on Linux and Windows. +local `127.0.0.1` listener with an injected browser stub. One test runs two +built CLI processes (`dist/`) against a fake identity server on `127.0.0.1`, so +run `npm run build` before `npm test`. CI runs the build and tests on Linux and +Windows. `npm run smoke:hosts` is a separate check that runs `reply skills install` entirely inside a throwaway `HOME`/`USERPROFILE` sandbox, and proves your real @@ -56,10 +58,44 @@ do. Each record is keyed by profile name, so multiple accounts never collide even when they hit the same backend. A record is either an OAuth entry (access token -+ refresh token + expiry) or an API-key entry. Expired OAuth tokens refresh -automatically; if a refresh fails the record is cleared and the user is prompted -to log in again. The store sits behind a `CredentialStore` interface so an -OS-keychain backend can be added later without touching callers. ++ refresh token + expiry) or an API-key entry. The store sits behind a +`CredentialStore` interface so an OS-keychain backend can be added later without +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 +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 +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 +left behind is taken over by the same rules. + +Expired OAuth tokens refresh automatically, one process at a time: the identity +server hands out one-time refresh tokens, so two processes refreshing together +would otherwise spend the same one. Under the lock the record is read again, and +a token another process already refreshed is used with no request sent. The token +request times out after 20 s, and the new record is stored as soon as the answer +is read. What a failed refresh does: + +| The token endpoint's answer | The stored record | The command fails with | +|---|---|---| +| `400` `invalid_grant` | removed — unless the file by then holds another record (another process refreshed first): that one is used, nothing is removed, and the command goes on | `auth.refresh_failed`, exit 2 | +| another OAuth error, `400` or `401` with an `error` | kept | `auth.refresh_failed`, exit 2 | +| `429` | kept | `rate_limited`, exit 1, with `retry_after` when it sent `Retry-After` | +| a `5xx`, any other status, a `2xx` that isn't a token answer, a timeout, a network error, or a lock wait that ran out | kept | `reply.unavailable`, exit 1 | + +The error carries the failed refresh under `details.refresh`: `status` (the token +endpoint's HTTP status) and `error` (its OAuth error code) when it answered, and +`reason` (`timeout`, `network`, `unreadable` or `lock_wait`) when no usable +answer came. The top-level `status` stays unset, since it is Reply's answer to the +command itself, and no token or request body is ever printed. ## Credential resolution diff --git a/README.md b/README.md index 436f3a0..4163025 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,16 @@ Pass a key for a single command with `--api-key` or the `REPLY_API_KEY` environment variable; both take precedence over a stored login and are never written to disk. +An OAuth login refreshes itself when it expires, one `reply` process at a time, +so commands started together don't sign you out. Only a refresh the sign-in +server refuses outright fails with `auth.refresh_failed` (exit 2) and needs a new +`reply auth login`. A refresh that hits a rate limit (`rate_limited`, with +`retry_after`), or a server error, an error page, a timeout or a network error +(`reply.unavailable`), keeps the login and exits 1: run the command again. With +`--json`, the error's `details.refresh` says what the sign-in server answered +(`status`, and `error`, its OAuth error code) or why no answer came (`reason`: +`timeout`, `network`, `unreadable` or `lock_wait`). Tokens are never printed. + ## Profiles Profiles keep more than one Reply.io account signed in at once — each stores its @@ -776,7 +786,8 @@ sets it for each command it runs. The value must be one lower-case name of up to 32 letters, digits or dashes, a `/`, and a version of up to 32 letters, digits, dots, `+` or `-`; anything else is left out and the User-Agent stays as it is. It is a label, not an input: it never refuses a command and never prints -anything, and it is read only from the environment of the process. +anything, and it is read only from the environment of the process. The token +requests a sign-in and its refreshes make carry the same User-Agent. ## Contributing diff --git a/skills/reply-adapter/reply-cli/SKILL.md b/skills/reply-adapter/reply-cli/SKILL.md index bb47c01..de4791b 100644 --- a/skills/reply-adapter/reply-cli/SKILL.md +++ b/skills/reply-adapter/reply-cli/SKILL.md @@ -6,7 +6,7 @@ description: > Use when executing any Reply.io operation from a shell, setting up authentication, or when another Reply skill needs commands executed. metadata: - version: 1.5.0 + version: 1.5.1 pack: reply-adapter category: execution maturity: reviewed @@ -58,8 +58,10 @@ reply auth logout ``` Credential precedence (strict): `--api-key` flag → `REPLY_API_KEY` env → stored credential. -Flag/env are ephemeral — never written to disk. Expired OAuth sessions refresh automatically; if -refresh fails the CLI asks to log in again. +Flag/env are ephemeral — never written to disk. Expired OAuth sessions refresh automatically, one +process at a time. Only `auth.refresh_failed` (exit 2) needs `reply auth login`. A refresh that +failed with `rate_limited` or `reply.unavailable` (exit 1) keeps the sign-in: run the command again, +after `retry_after` seconds when the error gives it. A user with no Reply.io account can create one during `reply auth login` — the sign-in page offers registration, and a trial costs nothing. Say that rather than treating a missing account @@ -170,6 +172,9 @@ explicit confirmation its Safety section requires. ## Changelog +- 1.5.1 (2026-11-25): *Authentication* says which failed refresh needs a new sign-in: only + `auth.refresh_failed`. After `rate_limited` or `reply.unavailable` the sign-in is kept and the + command can run again. - 1.5.0 (2026-11-21): *Failure modes* no longer offers the hosted mailbox page: the CLI prints only one-mailbox connection links, and `--allow-shared-page` is deprecated and does nothing. - 1.4.1 (2026-11-21): `reply api` says that a 429 saying an active contacts limit was reached is diff --git a/src/__tests__/auth/oauth-flow.test.ts b/src/__tests__/auth/oauth-flow.test.ts index 6468e2f..83a6d66 100644 --- a/src/__tests__/auth/oauth-flow.test.ts +++ b/src/__tests__/auth/oauth-flow.test.ts @@ -7,6 +7,7 @@ vi.stubGlobal('fetch', mock_fetch); import {build_authorize_url, run_login, refresh_stored, browser_open_command, CLIENT_ID, SCOPE} from '../../auth/oauth-flow'; import {RuntimeError} from '../../utils/errors'; +import {cli_version} from '../../config'; import type {Oauth_record} from '../../credentials/types'; const AUTHORITY = 'https://oauth.dev.replyapp.io'; @@ -99,6 +100,7 @@ describe('auth/oauth-flow', ()=>{ expect(token_url).toBe('https://oauth.dev.replyapp.io/connect/token'); expect(String(init.body)).toContain('grant_type=authorization_code'); expect(String(init.body)).toContain('code_verifier='); + expect(init.headers['User-Agent']).toMatch(/^reply-cli\/\d+\.\d+\.\d+/); }); it('rejects on a state mismatch (CSRF guard) without exchanging a token', async()=>{ @@ -124,21 +126,36 @@ describe('auth/oauth-flow', ()=>{ }); describe('refresh_stored', ()=>{ - it('posts a refresh_token grant and maps the new record, keeping the old refresh token', async()=>{ - mock_fetch.mockResolvedValue(token_res({access_token: 'AT2', expires_in: 3600})); + // The User-Agent breaks if a refresh goes out as Node's default: the identity server's logs + // could no longer tell this CLI's refreshes, or the program running it, from anything else. + // The mapping breaks if an answer with a usable access token is thrown away over its other + // fields: the server has already spent the old one-time refresh token by then. + it('posts a refresh_token grant under the CLI\'s User-Agent and maps the new record, keeping the old refresh token', async()=>{ + mock_fetch.mockResolvedValue(token_res({access_token: 'AT2', refresh_token: null, expires_in: null})); const prev: Oauth_record = {type: 'oauth', access_token: 'AT', refresh_token: 'RT', expires_at: 1}; - const record = await refresh_stored({authority: AUTHORITY, record: prev, now: NOW}); - expect(record.access_token).toBe('AT2'); - expect(record.refresh_token).toBe('RT'); + let record: Oauth_record; + try { + vi.stubEnv('REPLY_CLIENT', 'some-app/1.2.3'); + record = await refresh_stored({authority: AUTHORITY, record: prev, now: NOW}); + } finally { + vi.unstubAllEnvs(); + } + expect(record).toEqual({type: 'oauth', access_token: 'AT2', refresh_token: 'RT', expires_at: NOW + 3_600_000}); const [, init] = mock_fetch.mock.calls[0]; expect(String(init.body)).toContain('grant_type=refresh_token'); + expect(init.headers['User-Agent']).toBe(`some-app/1.2.3 reply-cli/${cli_version()}`); }); - it('throws when the token endpoint returns an error', async()=>{ - mock_fetch.mockResolvedValue(token_res({error: 'invalid_grant'}, 400)); + // Breaks if the status or the OAuth error of a failed refresh is lost: whether the sign-in is + // kept depends on them. + it('throws with the status and the OAuth error when the token endpoint returns an error', async()=>{ + mock_fetch.mockResolvedValue(token_res({error: 'invalid_grant', error_description: 'Token was used'}, 400)); const prev: Oauth_record = {type: 'oauth', access_token: 'AT', refresh_token: 'RT', expires_at: 1}; - await expect(refresh_stored({authority: AUTHORITY, record: prev, now: NOW})) - .rejects.toBeInstanceOf(RuntimeError); + const e = await refresh_stored({authority: AUTHORITY, record: prev, now: NOW}).catch((x: unknown)=>x); + expect(e).toBeInstanceOf(RuntimeError); + expect(e).toMatchObject({ + code: 'oauth.token', detail: 'HTTP 400: Token was used', failure: {status: 400, error: 'invalid_grant'}, + }); }); }); }); diff --git a/src/__tests__/auth/refresh-processes.test.ts b/src/__tests__/auth/refresh-processes.test.ts new file mode 100644 index 0000000..f0d8937 --- /dev/null +++ b/src/__tests__/auth/refresh-processes.test.ts @@ -0,0 +1,165 @@ +import {describe, it, expect, beforeEach, afterEach} from 'vitest'; +import {spawn} from 'child_process'; +import fs from 'fs'; +import http from 'http'; +import os from 'os'; +import path from 'path'; +import type {AddressInfo} from 'net'; + +// The built CLI: this test runs real processes, so `npm run build` comes first. +const CLI = path.resolve(__dirname, '..', '..', '..', 'dist', 'index.js'); +const PROFILE = 'race'; +// Long enough for the second process to start and reach the token endpoint while the first waits. +const HOLD_MS = 2_000; + +type Fake_reply = { + url: string; + refreshes: number; + refresh_tokens: Set; + access_tokens: Set; + close: () => Promise; +}; + +const read_body = (req: http.IncomingMessage): Promise=>new Promise((resolve, reject)=>{ + let body = ''; + req.on('data', chunk=>{ body += chunk; }); + req.on('end', ()=>resolve(body)); + req.on('error', reject); +}); + +const send_json = (res: http.ServerResponse, status: number, body: unknown): void=>{ + res.writeHead(status, {'Content-Type': 'application/json'}); + res.end(JSON.stringify(body)); +}; + +// One local server for the sign-in server and the API. Its token endpoint hands out one-time +// refresh tokens, as Reply's does, and answers a spent one with invalid_grant. It holds the first +// refresh until a second one arrives or HOLD_MS passes, so two processes that refresh at once both +// reach it with the same token. +const start_fake_reply = async(): Promise=>{ + let next = 1; + let release_first: (() => void) | undefined; + const fake = { + refreshes: 0, + refresh_tokens: new Set(['rt-0']), + access_tokens: new Set(), + }; + + const answer_refresh = (form: URLSearchParams): [number, unknown]=>{ + const token = form.get('refresh_token') ?? ''; + if (form.get('grant_type') !== 'refresh_token' || form.get('client_id') !== 'Reply.Cli' || !fake.refresh_tokens.delete(token)) + { + return [400, {error: 'invalid_grant'}]; + } + const n = next++; + fake.refresh_tokens.add(`rt-${n}`); + fake.access_tokens.add(`at-${n}`); + return [200, {access_token: `at-${n}`, refresh_token: `rt-${n}`, expires_in: 3600, token_type: 'Bearer'}]; + }; + + const server = http.createServer(async(req, res)=>{ + const body = await read_body(req); + if (req.method === 'POST' && req.url === '/connect/token') + { + fake.refreshes += 1; + if (release_first) + { + release_first(); + release_first = undefined; + await new Promise(r=>setImmediate(r)); + } + else if (fake.refreshes === 1) + { + await new Promise(resolve=>{ + release_first = resolve; + setTimeout(resolve, HOLD_MS); + }); + release_first = undefined; + } + const [status, answer] = answer_refresh(new URLSearchParams(body)); + send_json(res, status, answer); + return; + } + if (req.method === 'GET' && req.url === '/v3/whoami') + { + const token = (req.headers.authorization ?? '').replace(/^Bearer /, ''); + if (!fake.access_tokens.has(token)) + { + send_json(res, 401, {title: 'Unauthorized'}); + return; + } + send_json(res, 200, {userId: 7, username: 'ann@example.com', teamId: 3}); + return; + } + send_json(res, 404, {title: 'Not found'}); + }); + await new Promise(resolve=>server.listen(0, '127.0.0.1', resolve)); + const {port} = server.address() as AddressInfo; + return Object.assign(fake, { + url: `http://127.0.0.1:${port}`, + close: ()=>new Promise(resolve=>server.close(()=>resolve())), + }); +}; + +type Run = {code: number | null; stdout: string; stderr: string}; + +const run_cli = (args: string[], env: NodeJS.ProcessEnv): Promise=>new Promise(resolve=>{ + const child = spawn(process.execPath, [CLI, ...args], {env, stdio: ['ignore', 'pipe', 'pipe']}); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', chunk=>{ stdout += chunk; }); + child.stderr.on('data', chunk=>{ stderr += chunk; }); + child.on('close', code=>resolve({code, stdout, stderr})); +}); + +describe('two reply processes refreshing one expired sign-in together', ()=>{ + let dir: string; + let fake: Fake_reply; + + beforeEach(async()=>{ + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-race-')); + fake = await start_fake_reply(); + }); + + afterEach(async()=>{ + await fake.close(); + fs.rmSync(dir, {recursive: true, force: true}); + }); + + // Breaks if the second process spends the one-time refresh token the first already spent, and + // signs the person out on the refusal: what happens when an app starts several commands at once. + it('both end signed in, on one refresh', async()=>{ + expect(fs.existsSync(CLI), `${CLI} is missing: run \`npm run build\` first`).toBe(true); + const credentials = path.join(dir, 'credentials.json'); + fs.writeFileSync(path.join(dir, 'config.json'), + JSON.stringify({profiles: {[PROFILE]: {authority: fake.url, api_base: fake.url}}})); + fs.writeFileSync(credentials, JSON.stringify({[PROFILE]: { + type: 'oauth', access_token: 'at-0', refresh_token: 'rt-0', expires_at: Date.now() - 60_000, + }})); + + // Nothing outside the temp dir: no credential, profile or home from the machine running the test. + const env: NodeJS.ProcessEnv = Object.fromEntries( + Object.entries(process.env).filter(([name])=>!name.startsWith('REPLY_'))); + Object.assign(env, { + REPLY_CONFIG_DIR: dir, REPLY_PROFILE: PROFILE, REPLY_NO_UPDATE_CHECK: '1', + HOME: dir, USERPROFILE: dir, APPDATA: dir, XDG_CONFIG_HOME: dir, + }); + + const runs = await Promise.all([ + run_cli(['auth', 'whoami', '--json'], env), + run_cli(['auth', 'whoami', '--json'], env), + ]); + + expect(runs.map(r=>r.code), runs.map(r=>r.stderr).join('\n')).toEqual([0, 0]); + for (const r of runs) + { + expect(JSON.parse(r.stdout)).toEqual({userId: 7, username: 'ann@example.com', teamId: 3}); + } + expect(fake.refreshes).toBe(1); + const stored = JSON.parse(fs.readFileSync(credentials, 'utf8'))[PROFILE]; + expect(stored).toMatchObject({type: 'oauth', access_token: 'at-1', refresh_token: 'rt-1'}); + expect(stored.expires_at).toBeGreaterThan(Date.now()); + expect(fake.refresh_tokens.has(stored.refresh_token)).toBe(true); + expect(fs.existsSync(`${credentials}.lock`)).toBe(false); + }, 30_000); +}); diff --git a/src/__tests__/auth/resolve.test.ts b/src/__tests__/auth/resolve.test.ts index 88c0979..3d45002 100644 --- a/src/__tests__/auth/resolve.test.ts +++ b/src/__tests__/auth/resolve.test.ts @@ -1,6 +1,11 @@ -import {describe, it, expect, vi} from 'vitest'; +import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; import {resolve_credential} from '../../auth/resolve'; -import {UsageError} from '../../utils/errors'; +import {refresh_stored, CLIENT_ID} from '../../auth/oauth-flow'; +import {FileCredentialStore} from '../../credentials/file-store'; +import {CliError, UsageError, format_hint} from '../../utils/errors'; import {APP_NAME} from '../../config'; import type {Credential_record, CredentialStore, Oauth_record} from '../../credentials/types'; @@ -13,12 +18,16 @@ const fake_store = (seed: Record = {})=>{ const store: CredentialStore = { get: vi.fn(async(h: string)=>map[h]), set: vi.fn(async(h: string, r: Credential_record)=>{map[h] = r;}), - remove: vi.fn(async(h: string)=>{ - const had = h in map; + remove: vi.fn(async(h: string, only_if?: (r: Credential_record) => boolean)=>{ + if (!(h in map) || (only_if && !only_if(map[h]))) + { + return false; + } delete map[h]; - return had; + return true; }), keys: vi.fn(async()=>Object.keys(map)), + with_lock: async(fn: () => Promise)=>fn(), }; return {store, map}; }; @@ -72,19 +81,22 @@ describe('auth/resolve — credential precedence', ()=>{ expect(r.token).toBe('new_at'); }); - it('clears the record and errors when an expired token has no refresh token', async()=>{ - const {store} = fake_store({[HOST]: fresh_oauth({expires_at: NOW - 1, refresh_token: undefined})}); + // 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()=>{ + 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.toBeInstanceOf(UsageError); - expect(store.remove).toHaveBeenCalledWith(HOST); - }); + .rejects.toMatchObject({code: 'auth.expired'}); + expect(map).toEqual({}); - it('clears the record and errors when refresh fails', async()=>{ - const {store} = fake_store({[HOST]: fresh_oauth({expires_at: NOW - 1})}); - const refresh = vi.fn(async()=>{throw new Error('token endpoint said no');}); - await expect(resolve_credential({}, {key: HOST, store, env: {}, now: NOW, refresh})) - .rejects.toBeInstanceOf(UsageError); - expect(store.remove).toHaveBeenCalledWith(HOST); + const peer = fake_store({[HOST]: fresh_oauth({expires_at: NOW - 1, refresh_token: undefined})}); + peer.store.with_lock = async(fn: () => Promise)=>{ + peer.map[HOST] = fresh_oauth({access_token: 'peer_at'}); + return fn(); + }; + 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'})); }); it('errors (UsageError) when nothing is available and writes nothing', async()=>{ @@ -94,3 +106,231 @@ describe('auth/resolve — credential precedence', ()=>{ expect(store.set).not.toHaveBeenCalled(); }); }); + +// A failed refresh against the real credentials file and the real token request, with only the +// token endpoint's answer recorded. +describe('auth/resolve — a refresh that fails', ()=>{ + const AUTHORITY = 'https://oauth.test'; + const PROFILE = 'default'; + const EXPIRED: Oauth_record = { + type: 'oauth', access_token: 'at-old-SECRET', refresh_token: 'rt-old-SECRET', expires_at: NOW - 1, user: {id: 7}, + }; + const NEWER: Oauth_record = { + type: 'oauth', access_token: 'at-new-SECRET', refresh_token: 'rt-new-SECRET', expires_at: NOW + 3_600_000, user: {id: 7}, + }; + const OTHER: Credential_record = {type: 'api_key', key: 'key-other-SECRET'}; + const SECRETS = ['at-old-SECRET', 'rt-old-SECRET', 'at-new-SECRET', 'rt-new-SECRET', 'key-other-SECRET']; + const REFRESH_REQUEST = { + url: `${AUTHORITY}/connect/token`, + form: {grant_type: 'refresh_token', refresh_token: 'rt-old-SECRET', client_id: CLIENT_ID}, + }; + + let dir: string; + let file: string; + const token_endpoint = vi.fn(); + + beforeEach(()=>{ + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-refresh-')); + file = path.join(dir, 'credentials.json'); + fs.writeFileSync(file, JSON.stringify({[PROFILE]: EXPIRED, other: OTHER}, null, 2)); + token_endpoint.mockReset(); + vi.stubGlobal('fetch', token_endpoint); + }); + + afterEach(()=>{ + vi.unstubAllGlobals(); + fs.rmSync(dir, {recursive: true, force: true}); + }); + + const store = (lock?: {wait_ms?: number}): FileCredentialStore=>new FileCredentialStore(file, {lock}); + const resolve = (s: FileCredentialStore = store())=>resolve_credential({}, { + key: PROFILE, store: s, env: {}, now: NOW, + refresh: record=>refresh_stored({authority: AUTHORITY, record, now: NOW, timeout_ms: 50}), + }); + const failure = (s?: FileCredentialStore): Promise=>resolve(s).then( + r=>{ throw new Error(`resolved to a ${r.type} credential instead of failing`); }, + (e: unknown)=>e as CliError); + const requests = ()=>token_endpoint.mock.calls.map(([url, init]: [string, RequestInit])=> + ({url, form: Object.fromEntries(new URLSearchParams(String(init.body)))})); + const json = (status: number, body: unknown, headers: Record = {})=> + new Response(JSON.stringify(body), {status, headers: {'Content-Type': 'application/json', ...headers}}); + // Another live process's lock: this test's parent process holds it. + const hold_lock = ()=>fs.writeFileSync(`${file}.lock`, JSON.stringify({pid: process.ppid, host: os.hostname(), taken_at: Date.now()})); + // What the top-level handler prints for an error, with --json and without. + const printed = (e: CliError): string=>[e.message, e.hint ? format_hint(e.hint) : '', JSON.stringify(e.to_json())].join('\n'); + const expect_no_secret = (e: CliError): void=>{ + for (const secret of SECRETS) + { + expect(printed(e)).not.toContain(secret); + } + }; + + type Passing = { + name: string; + answer: (init: RequestInit) => Promise; + code: string; + retry_after?: number; + refresh: Record; + says: string; + }; + const PASSING: Passing[] = [ + { + name: 'a 429 with Retry-After', code: 'rate_limited', retry_after: 30, refresh: {status: 429}, says: 'HTTP 429', + answer: async()=>new Response('Too Many Requests', {status: 429, headers: {'Retry-After': '30'}}), + }, + { + name: 'a 429 without Retry-After', code: 'rate_limited', refresh: {status: 429}, says: 'HTTP 429', + answer: async()=>new Response('Too Many Requests', {status: 429}), + }, + { + name: 'a 5xx', code: 'reply.unavailable', refresh: {status: 503}, says: 'HTTP 503', + answer: async()=>new Response('upstream connect error', {status: 503}), + }, + { + name: 'a 405 maintenance page', code: 'reply.unavailable', refresh: {status: 405}, says: 'HTTP 405', + answer: async()=>new Response('We are down for maintenance', + {status: 405, headers: {'Content-Type': 'text/html'}}), + }, + { + name: 'a timeout', code: 'reply.unavailable', refresh: {reason: 'timeout'}, says: 'No answer', + answer: init=>new Promise((_, reject)=>{ + init.signal!.addEventListener('abort', ()=>reject(init.signal!.reason)); + }), + }, + { + name: 'a network error', code: 'reply.unavailable', refresh: {reason: 'network'}, says: 'ECONNREFUSED', + answer: async()=>{ + throw Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:443'), {code: 'ECONNREFUSED'}), + }); + }, + }, + { + name: 'a 2xx that is not a token answer', code: 'reply.unavailable', refresh: {status: 200, reason: 'unreadable'}, + says: 'HTTP 200', + answer: async()=>new Response('ok', {status: 200}), + }, + ]; + + // Breaks if a failure that a later attempt can get past signs the person out, or reads to the + // caller as a sign-in problem no retry can help. + it.each(PASSING)('keeps the sign-in byte for byte on $name and fails $code at exit 1', async c=>{ + const before = fs.readFileSync(file); + token_endpoint.mockImplementation((_url: string, init: RequestInit)=>c.answer(init)); + const e = await failure(); + expect({code: e.code, exit_code: e.exit_code, retry_after: e.retry_after, details: e.details}) + .toEqual({code: c.code, exit_code: 1, retry_after: c.retry_after, details: {refresh: c.refresh}}); + expect(e.to_json().error.status).toBeUndefined(); + expect(e.message).toContain(c.says); + expect(fs.readFileSync(file).equals(before)).toBe(true); + expect(fs.existsSync(`${file}.lock`)).toBe(false); + expect(requests()).toEqual([REFRESH_REQUEST]); + expect_no_secret(e); + }); + + // Breaks if a lock another process never lets go of hangs the command or signs the person out. + it('keeps the sign-in and fails reply.unavailable when another process holds the lock too long', async()=>{ + hold_lock(); + const before = fs.readFileSync(file); + const e = await failure(store({wait_ms: 200})); + expect({code: e.code, exit_code: e.exit_code, details: e.details}) + .toEqual({code: 'reply.unavailable', exit_code: 1, details: {refresh: {reason: 'lock_wait'}}}); + expect(fs.readFileSync(file).equals(before)).toBe(true); + expect(token_endpoint).not.toHaveBeenCalled(); + expect_no_secret(e); + }); + + // Breaks if a definite refusal other than a dead grant deletes a sign-in a new login would replace anyway. + it('keeps the sign-in on an OAuth refusal other than invalid_grant and fails auth.refresh_failed', async()=>{ + const before = fs.readFileSync(file); + token_endpoint.mockResolvedValue(json(401, {error: 'invalid_client', error_description: 'Unknown client'})); + const e = await failure(); + expect({code: e.code, exit_code: e.exit_code, details: e.details}) + .toEqual({code: 'auth.refresh_failed', exit_code: 2, details: {refresh: {status: 401, error: 'invalid_client'}}}); + expect(e.message).toContain('HTTP 401 invalid_client'); + expect(e.hint).toContain('auth login'); + expect(fs.readFileSync(file).equals(before)).toBe(true); + expect(requests()).toEqual([REFRESH_REQUEST]); + expect_no_secret(e); + }); + + // Breaks if a dead grant is kept (every command would send it again) or its reason is dropped; or + // if the check that the file still holds it is a read of its own before the delete's, leaving a + // window for a record stored in between to be deleted. + it('removes the sign-in when the grant is refused and the file still holds it, deciding on the read it rewrites', async()=>{ + let refused = false; + let rewritten = false; + let reads = 0; + token_endpoint.mockImplementation(async()=>{ + refused = true; + return json(400, {error: 'invalid_grant'}); + }); + const read = fs.readFileSync; + const rename = fs.renameSync; + const spies = [ + vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathOrFileDescriptor, ...rest: unknown[])=>{ + if (refused && !rewritten && String(target) === file) + { + reads += 1; + } + return (read as (...a: unknown[]) => unknown)(target, ...rest); + }) as typeof fs.readFileSync), + vi.spyOn(fs, 'renameSync').mockImplementation((from, to)=>{ + rename(from, to); + rewritten ||= String(to) === file; + }), + ]; + let e: CliError; + try { + e = await failure(); + } finally { + spies.forEach(s=>s.mockRestore()); + } + expect(reads).toBe(1); + expect({code: e.code, exit_code: e.exit_code, details: e.details}) + .toEqual({code: 'auth.refresh_failed', exit_code: 2, details: {refresh: {status: 400, error: 'invalid_grant'}}}); + expect(e.message).toContain('HTTP 400 invalid_grant'); + expect(e.hint).toContain('auth login'); + expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({other: OTHER}); + expect(fs.existsSync(`${file}.lock`)).toBe(false); + expect(requests()).toEqual([REFRESH_REQUEST]); + expect_no_secret(e); + }); + + // Breaks if a refusal caused by a peer that spent the same one-time token deletes the token that + // peer stored; or if the error says a sign-in was removed when a peer had already removed it. + // The peer here is a reply that takes no lock, such as an older version. + it('uses a sign-in another process stored while the refresh was refused, deleting nothing', async()=>{ + token_endpoint.mockImplementation(async()=>{ + fs.writeFileSync(file, JSON.stringify({[PROFILE]: NEWER, other: OTHER}, null, 2)); + return json(400, {error: 'invalid_grant'}); + }); + const r = await resolve(); + expect(r).toMatchObject({token: 'at-new-SECRET', type: 'oauth', source: 'store'}); + expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({[PROFILE]: NEWER, other: OTHER}); + expect(requests()).toEqual([REFRESH_REQUEST]); + + fs.writeFileSync(file, JSON.stringify({[PROFILE]: EXPIRED, other: OTHER}, null, 2)); + token_endpoint.mockImplementation(async()=>{ + fs.writeFileSync(file, JSON.stringify({other: OTHER}, null, 2)); + return json(400, {error: 'invalid_grant'}); + }); + const e = await failure(); + expect({code: e.code, details: e.details}) + .toEqual({code: 'auth.refresh_failed', details: {refresh: {status: 400, error: 'invalid_grant'}}}); + expect(e.message).not.toContain('removed'); + expect(JSON.parse(fs.readFileSync(file, 'utf8'))).toEqual({other: OTHER}); + }); + + // Breaks if two processes that find one expired token both spend it: the second is refused. + it('waits for another process refreshing, then uses what it stored and sends no refresh', async()=>{ + hold_lock(); + const resolved = resolve().catch((e: unknown)=>e); + await new Promise(r=>setTimeout(r, 200)); + expect(token_endpoint).not.toHaveBeenCalled(); + fs.writeFileSync(file, JSON.stringify({[PROFILE]: NEWER, other: OTHER}, null, 2)); + fs.rmSync(`${file}.lock`); + expect(await resolved).toMatchObject({token: 'at-new-SECRET', type: 'oauth', source: 'store'}); + expect(token_endpoint).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/commands/profile.test.ts b/src/__tests__/commands/profile.test.ts index 9897022..0f457ac 100644 --- a/src/__tests__/commands/profile.test.ts +++ b/src/__tests__/commands/profile.test.ts @@ -1,4 +1,4 @@ -import {describe, it, expect, beforeEach, afterEach} from 'vitest'; +import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest'; import fs from 'fs'; import os from 'os'; import path from 'path'; @@ -28,7 +28,9 @@ beforeEach(()=>{ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-cmd-')); }); afterEach(()=>{ fs.rmSync(dir, {recursive: true, force: true}); }); describe('handle_rename', ()=>{ - it('moves the stored credential from old key to new key', async()=>{ + // Breaks if the move is two locked writes: another process that refreshes the old key's sign-in + // between them stores its new token there, and the move then drops it. + it('moves the stored credential from old key to new key, in one locked step', async()=>{ add_profile('alice@reply.io', {}, env_for()); const store = store_for(); await store.set('alice@reply.io', api_key); @@ -36,6 +38,42 @@ describe('handle_rename', ()=>{ expect(await store.get('alice@reply.io')).toBeUndefined(); expect(await store.get('ally@reply.io')).toEqual(api_key); expect(list_profiles(env_for()).available).toContain('ally@reply.io'); + + // The peer takes the lock the moment it is free and, as a refresh does, rewrites the old key + // only while the file still holds it. + add_profile('bob', {}, env_for()); + await store.set('bob', api_key); + const credentials = path.join(dir, 'credentials.json'); + const lock = `${credentials}.lock`; + const real = {read: fs.readFileSync, write: fs.writeFileSync, unlink: fs.unlinkSync, rm: fs.rmSync, exists: fs.existsSync}; + let peer_between = false; + const peer = (target: unknown): void=>{ + if (String(target) !== lock || real.exists(lock)) + { + return; + } + real.write(lock, JSON.stringify({pid: process.ppid, host: os.hostname(), taken_at: Date.now()}), {flag: 'wx'}); + const map = JSON.parse(String(real.read(credentials, 'utf8'))); + if ('bob' in map && 'bobby' in map) + { + map.bob = {...api_key, key: 'refreshed'}; + real.write(credentials, JSON.stringify(map)); + peer_between = true; + } + real.unlink(lock); + }; + const spies = [ + vi.spyOn(fs, 'unlinkSync').mockImplementation(target=>{ real.unlink(target); peer(target); }), + vi.spyOn(fs, 'rmSync').mockImplementation((target, opts)=>{ real.rm(target, opts); peer(target); }), + ]; + try { + await handle_rename('bob', 'bobby', {}, {store, env: env_for()}); + } finally { + spies.forEach(s=>s.mockRestore()); + } + expect(peer_between).toBe(false); + expect(await store.get('bob')).toBeUndefined(); + expect(await store.get('bobby')).toEqual(api_key); }); it('renames a profile that has no stored credential (no-op on store)', async()=>{ diff --git a/src/__tests__/credentials/file-store.test.ts b/src/__tests__/credentials/file-store.test.ts index fc745ee..ad139ed 100644 --- a/src/__tests__/credentials/file-store.test.ts +++ b/src/__tests__/credentials/file-store.test.ts @@ -1,4 +1,5 @@ -import {describe, it, expect, beforeEach, afterEach} from 'vitest'; +import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest'; +import {spawnSync} from 'child_process'; import fs from 'fs'; import os from 'os'; import path from 'path'; @@ -107,4 +108,263 @@ describe('credentials/FileCredentialStore', ()=>{ fs.writeFileSync(file, '["nope"]'); 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; + const temps: string[] = []; + const spy = vi.spyOn(fs, 'renameSync').mockImplementation((from, to)=>{ + if (String(to) === file) + { + temps.push(String(from)); + } + if (!refused && String(to) === file) + { + refused = true; + throw Object.assign(new Error(`EPERM: operation not permitted, rename '${from}'`), {code: 'EPERM'}); + } + rename(from, to); + }); + try { + await store.set('h', API_KEY); + await store.set('h2', OAUTH); + } finally { + spy.mockRestore(); + } + expect(refused).toBe(true); + expect(await store.get('h')).toEqual(API_KEY); + expect(temps).toHaveLength(3); + expect(new Set(temps).size).toBe(2); + }); +}); + +describe('credentials/FileCredentialStore — the lock beside the file', ()=>{ + const HOST = os.hostname(); + const PID_NS = ((): string | undefined=>{ + try { + return fs.readlinkSync('/proc/self/ns/pid'); + } catch { + return undefined; + } + })(); + 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. + const hold_lock = (holder: {pid: number; host?: string; ns?: string; id?: string; taken_at: number; peer?: string}): string=>{ + fs.mkdirSync(path.dirname(file), {recursive: true}); + const text = JSON.stringify({host: HOST, ns: PID_NS, ...holder}); + fs.writeFileSync(lock(), text); + return text; + }; + const gone_pid = (): number=>spawnSync(process.execPath, ['-e', '']).pid as number; + const settles_within = (p: Promise, ms: number): Promise=>Promise.race([ + p.then(()=>true, ()=>true), + new Promise(resolve=>setTimeout(()=>resolve(false), ms)), + ]); + // Runs `after` after every call this module makes to the fs functions named, whether it throws or not. + const after_each_call = (names: (keyof typeof fs)[], after: (name: string, args: unknown[]) => void)=> + names.map(name=>{ + const original = fs[name] as (...a: unknown[]) => unknown; + return vi.spyOn(fs, name as 'statSync').mockImplementation(((...args: unknown[])=>{ + try { + return original(...args); + } finally { + after(name, args); + } + }) as never); + }); + + // Breaks if a login or a logout writes in the middle of another process's refresh, and one of + // the two writes is lost; or if failing to delete the lock file fails a write that happened. + // Or if two guards read the same: breaking a stale guard has to tell it from a live one. + it('waits for a live lock before a set or a remove, then writes and lets it go, even when letting go fails', async()=>{ + await store.set('keep', API_KEY); + hold_lock({pid: process.ppid, taken_at: Date.now()}); + const write = fs.writeFileSync; + const guards: string[] = []; + const guard_spy = vi.spyOn(fs, 'writeFileSync').mockImplementation(((target: fs.PathOrFileDescriptor, data: unknown, ...rest: unknown[])=>{ + if (String(target) === `${lock()}.guard`) + { + guards.push(String(data)); + } + return (write as (...a: unknown[]) => void)(target, data, ...rest); + }) as typeof fs.writeFileSync); + try { + const writes = Promise.all([store.set('h', OAUTH), store.remove('keep')]); + expect(await settles_within(writes, 300)).toBe(false); + expect(await store.keys()).toEqual(['keep']); + fs.rmSync(lock()); + expect(await writes).toEqual([undefined, true]); + } finally { + guard_spy.mockRestore(); + } + expect(await store.keys()).toEqual(['h']); + expect(fs.existsSync(lock())).toBe(false); + expect(guards).toHaveLength(2); + expect(new Set(guards).size).toBe(2); + + // Windows refuses to delete a file another program holds open, an antivirus say. + const busy = (target: unknown): void=>{ + if (String(target) === lock()) + { + throw Object.assign(new Error(`EBUSY: resource busy or locked, unlink '${lock()}'`), {code: 'EBUSY'}); + } + }; + const unlink = fs.unlinkSync; + const rm = fs.rmSync; + const spies = [ + vi.spyOn(fs, 'unlinkSync').mockImplementation(target=>{ busy(target); unlink(target); }), + vi.spyOn(fs, 'rmSync').mockImplementation((target, opts)=>{ busy(target); rm(target, opts); }), + ]; + try { + await store.set('h2', API_KEY); + } finally { + spies.forEach(s=>s.mockRestore()); + } + expect(await store.get('h2')).toEqual(API_KEY); + // The lock left behind is this process's own, so its next write takes it over at once. + await store.set('h3', API_KEY); + expect(await store.keys()).toEqual(['h', 'h2', 'h3']); + expect(fs.existsSync(lock())).toBe(false); + }); + + // Breaks if a lock left by a killed process blocks every later write; or if several processes + // that find one stale lock each remove what is there by then, so two of them hold the lock. + it('takes over a lock whose holder is gone, and never one a peer took over meanwhile', async()=>{ + hold_lock({pid: gone_pid(), taken_at: Date.now()}); + const s = new FileCredentialStore(file, {lock: {wait_ms: 2_000}}); + await s.set('h', API_KEY); + expect(await s.get('h')).toEqual(API_KEY); + expect(fs.existsSync(lock())).toBe(false); + + // Peer A takes the stale lock over just after this process judged it stale. Peer C creates a + // lock of its own whenever the lock path is free. Only A may end up holding it. + const stale = hold_lock({pid: gone_pid(), taken_at: Date.now()}); + const peer_a = JSON.stringify({pid: process.ppid, host: HOST, taken_at: Date.now(), peer: 'a'}); + const real = {read: fs.readFileSync, write: fs.writeFileSync, unlink: fs.unlinkSync, exists: fs.existsSync}; + let a_took_over = false; + let c_took = false; + const c_creates_when_free = (): void=>{ + if (a_took_over && !c_took && !real.exists(lock())) + { + try { + real.write(lock(), JSON.stringify({pid: process.ppid, host: HOST, taken_at: Date.now(), peer: 'c'}), {flag: 'wx'}); + c_took = true; + } catch { + // Someone else's lock is there. + } + } + }; + const spies = [ + ...after_each_call(['renameSync', 'linkSync', 'unlinkSync', 'rmSync', 'writeFileSync', 'statSync'], c_creates_when_free), + vi.spyOn(fs, 'readFileSync').mockImplementation(((...args: unknown[])=>{ + const out = (real.read as (...a: unknown[]) => unknown)(...args); + if (!a_took_over && String(args[0]) === lock() && String(out) === stale) + { + real.unlink(lock()); + real.write(lock(), peer_a, {flag: 'wx'}); + a_took_over = true; + } + c_creates_when_free(); + return out; + }) as never), + ]; + try { + await expect(new FileCredentialStore(file, {lock: {wait_ms: 300}}).set('h', OAUTH)) + .rejects.toMatchObject({code: 'store.locked'}); + } finally { + spies.forEach(spy=>spy.mockRestore()); + } + expect({a_took_over, c_took, lock: fs.readFileSync(lock(), 'utf8')}).toEqual({a_took_over: true, c_took: false, lock: peer_a}); + expect(await s.get('h')).toEqual(API_KEY); + }); + + // 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()=>{ + 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()}, + {pid: process.pid, id: 'not-left-here', taken_at: Date.now()}, + ]; + const outcomes: string[] = []; + for (const peer of peers) + { + hold_lock(peer); + outcomes.push(await new FileCredentialStore(file, {lock: {wait_ms: 300}}).set('h', API_KEY) + .then(()=>'taken over', (e: {code?: string})=>String(e.code))); + fs.rmSync(file, {force: true}); + } + expect(outcomes).toEqual(['store.locked', 'store.locked', 'store.locked']); + + 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); + expect(await s.get('h')).toEqual(API_KEY); + expect(fs.existsSync(lock())).toBe(false); + }); + + // Breaks if a wait for a held lock has no end; or if, on Windows, a config dir that can't be + // written waits out the whole wait as if another process held the lock; or if a lock let go + // between a refused create and its read is taken for such a dir. + it('fails store.locked when a live lock outlasts the wait, and store.lock soon when nothing holds it', async()=>{ + hold_lock({pid: process.ppid, taken_at: Date.now()}); + const s = new FileCredentialStore(file, {lock: {wait_ms: 200}}); + await expect(s.set('h', API_KEY)).rejects.toMatchObject({code: 'store.locked', exit_code: 1}); + expect(fs.existsSync(file)).toBe(false); + expect(fs.existsSync(lock())).toBe(true); + + fs.rmSync(lock()); + const platform = Object.getOwnPropertyDescriptor(process, 'platform') as PropertyDescriptor; + const write = fs.writeFileSync; + Object.defineProperty(process, 'platform', {...platform, value: 'win32'}); + const spy = vi.spyOn(fs, 'writeFileSync').mockImplementation(((target: fs.PathOrFileDescriptor, ...rest: unknown[])=>{ + if (String(target) === lock()) + { + throw Object.assign(new Error(`EPERM: operation not permitted, open '${lock()}'`), {code: 'EPERM'}); + } + return (write as (...a: unknown[]) => void)(target, ...rest); + }) as typeof fs.writeFileSync); + const started = Date.now(); + try { + await expect(new FileCredentialStore(file, {lock: {wait_ms: 3_000}}).set('h', API_KEY)) + .rejects.toMatchObject({code: 'store.lock', exit_code: 1}); + } finally { + spy.mockRestore(); + Object.defineProperty(process, 'platform', platform); + } + expect(Date.now() - started).toBeLessThan(2_500); + expect(fs.existsSync(file)).toBe(false); + + // Every create finds a lock, and every read finds it already let go: busy, not broken. + const read = fs.readFileSync; + const spies = [ + vi.spyOn(fs, 'writeFileSync').mockImplementation(((target: fs.PathOrFileDescriptor, ...rest: unknown[])=>{ + if (String(target) === lock()) + { + throw Object.assign(new Error(`EEXIST: file already exists, open '${lock()}'`), {code: 'EEXIST'}); + } + return (write as (...a: unknown[]) => void)(target, ...rest); + }) as typeof fs.writeFileSync), + vi.spyOn(fs, 'readFileSync').mockImplementation(((target: fs.PathOrFileDescriptor, ...rest: unknown[])=>{ + if (String(target) === lock()) + { + throw Object.assign(new Error(`ENOENT: no such file or directory, open '${lock()}'`), {code: 'ENOENT'}); + } + return (read as (...a: unknown[]) => unknown)(target, ...rest); + }) as typeof fs.readFileSync), + ]; + try { + await expect(new FileCredentialStore(file, {lock: {wait_ms: 1_500}}).set('h', API_KEY)) + .rejects.toMatchObject({code: 'store.locked', exit_code: 1}); + } finally { + spies.forEach(spy=>spy.mockRestore()); + } + }, 10_000); }); diff --git a/src/auth/oauth-flow.ts b/src/auth/oauth-flow.ts index 15781bc..c641533 100644 --- a/src/auth/oauth-flow.ts +++ b/src/auth/oauth-flow.ts @@ -1,10 +1,13 @@ import http from 'http'; import {spawn} from 'child_process'; import {URL} from 'url'; +import {user_agent} from '../config'; +import {failure_detail, parse_retry_after} from '../utils/client'; import {RuntimeError} from '../utils/errors'; import {info} from '../utils/output'; import {create_pkce, create_state} from './pkce'; import { + TOKEN_TIMEOUT_MS, build_token_exchange_body, build_refresh_body, to_oauth_record, @@ -175,24 +178,91 @@ const parse_token_error = (text: string): string=>{ } }; -const post_token = async(authority: string, body: URLSearchParams): Promise=>{ - const res = await fetch(`${authority}/connect/token`, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Accept': 'application/json', - }, - body: body.toString(), - }); - const text = await res.text(); +const parse_json = (text: string): unknown=>{ + try { + return JSON.parse(text); + } catch { + return undefined; + } +}; + +const is_object = (v: unknown): v is Record=>typeof v === 'object' && v !== null && !Array.isArray(v); + +// The OAuth `error` code of an error answer (RFC 6749 §5.2), if the answer is one. +const oauth_error_of = (text: string): string | undefined=>{ + const body = parse_json(text); + return is_object(body) && typeof body.error === 'string' && body.error ? body.error : undefined; +}; + +// A 2xx is a token answer whenever it carries an access token: by then the server has spent the old +// one-time refresh token, so an odd field elsewhere must not cost the new one (to_oauth_record +// falls back for those). +const token_answer_of = (text: string): Token_response | undefined=>{ + const body = parse_json(text); + return is_object(body) && typeof body.access_token === 'string' && body.access_token + ? body as Token_response + : undefined; +}; + +// What is known of a token request that failed. Never a token or the request body. +type Token_failure = { + status?: number; // the HTTP status, when the server answered + error?: string; // the OAuth `error` code of its answer, when it was one + reason?: 'timeout' | 'network' | 'unreadable'; // why no usable answer came + retry_after?: number; // seconds, from a 429's Retry-After +}; + +class Token_request_error extends RuntimeError { + readonly failure: Token_failure; + + constructor(detail: string, failure: Token_failure) + { + super('OAuth token request failed.', {code: 'oauth.token', detail}); + this.name = 'Token_request_error'; + this.failure = failure; + } +} + +const post_token = async( + authority: string, body: URLSearchParams, timeout_ms: number = TOKEN_TIMEOUT_MS, +): Promise=>{ + let res: Response; + let text: string; + try { + res = await fetch(`${authority}/connect/token`, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Accept': 'application/json', + 'User-Agent': user_agent(), + }, + body: body.toString(), + signal: AbortSignal.timeout(timeout_ms), + }); + text = await res.text(); + } catch (e) { + if ((e as Error)?.name === 'TimeoutError' || (e as Error)?.name === 'AbortError') + { + throw new Token_request_error(`No answer within ${timeout_ms / 1000} s.`, {reason: 'timeout'}); + } + throw new Token_request_error(failure_detail(e), {reason: 'network'}); + } if (!res.ok) { - throw new RuntimeError('OAuth token request failed.', { - code: 'oauth.token', - detail: `HTTP ${res.status}: ${parse_token_error(text)}`, + throw new Token_request_error(`HTTP ${res.status}: ${parse_token_error(text)}`, { + status: res.status, + error: oauth_error_of(text), + retry_after: res.status === 429 ? parse_retry_after(res.headers.get('Retry-After')) ?? undefined : undefined, + }); + } + const answer = token_answer_of(text); + if (!answer) + { + throw new Token_request_error(`HTTP ${res.status}: the answer is not a token response.`, { + status: res.status, reason: 'unreadable', }); } - return JSON.parse(text) as Token_response; + return answer; }; const exchange_code = async(p: { @@ -215,6 +285,7 @@ const refresh_stored = async(p: { record: Oauth_record; client_id?: string; now?: number; + timeout_ms?: number; }): Promise=>{ if (!p.record.refresh_token) { @@ -223,7 +294,7 @@ const refresh_stored = async(p: { const now = p.now ?? Date.now(); const resp = await post_token(p.authority, build_refresh_body({ refresh_token: p.record.refresh_token, client_id: p.client_id ?? CLIENT_ID, - })); + }), p.timeout_ms); return to_oauth_record(resp, now, p.record); }; @@ -251,6 +322,7 @@ const run_login = async(opts: { }; export { - CLIENT_ID, SCOPE, + CLIENT_ID, SCOPE, Token_request_error, build_authorize_url, run_login, exchange_code, refresh_stored, browser_open_command, }; +export type {Token_failure}; diff --git a/src/auth/resolve.ts b/src/auth/resolve.ts index 0f72e35..709ce6f 100644 --- a/src/auth/resolve.ts +++ b/src/auth/resolve.ts @@ -1,5 +1,7 @@ import {PROGRAM_NAME, env_var, get_env, type Env} from '../config'; -import {UsageError} from '../utils/errors'; +import {Lock_timeout_error} from '../credentials/lock'; +import {Operation_error, UsageError} from '../utils/errors'; +import {Token_request_error, type Token_failure} from './oauth-flow'; import {needs_refresh} from './token'; import type {Credential_record, CredentialStore, Oauth_record} from '../credentials/types'; @@ -27,10 +29,155 @@ type Resolve_deps = { refresh?: (record: Oauth_record) => Promise; }; +const LOGIN_HINT = `Run \`${PROGRAM_NAME} auth login\` to sign in again.`; +const KEPT_HINT = 'The stored sign-in is kept. Run the command again.'; + +const not_authenticated = (): UsageError=>new UsageError('Not authenticated.', { + code: 'auth.required', + hint: `Run \`${PROGRAM_NAME} auth login\` or set ${env_var('API_KEY')}.`, +}); + +const session_expired = (): UsageError=>new UsageError('Session expired.', {code: 'auth.expired', hint: LOGIN_HINT}); + +const usable = (record: Credential_record, now: number): boolean=> + record.type === 'api_key' || !needs_refresh(record, now); + +const from_store = (record: Credential_record): Resolved_credential=>({ + token: record.type === 'api_key' ? record.key : record.access_token, + type: record.type, + source: 'store', + ephemeral: false, + record, +}); + +const same_record = (a: Credential_record, b: Credential_record): boolean=> + a.type === 'oauth' && b.type === 'oauth' && a.access_token === b.access_token && a.refresh_token === b.refresh_token; + +// A token request's failure, or a wait for the lock that ran out before any request was sent. +type Refresh_failure = Omit & {reason?: Token_failure['reason'] | 'lock_wait'}; + +// The failed refresh as the printed error carries it, under `details.refresh`: the token endpoint's +// HTTP status and OAuth `error` code when it answered, and why no usable answer came otherwise. The +// top-level `status` stays unset, since a caller reads it as Reply's answer to the command itself. +const refresh_details = (f: Refresh_failure): Record=>{ + const refresh: Record = {}; + if (f.status !== undefined) + { + refresh.status = f.status; + } + if (f.error !== undefined) + { + refresh.error = f.error; + } + if (f.reason !== undefined) + { + refresh.reason = f.reason; + } + return {refresh}; +}; + +const answered = (f: Refresh_failure): string=>`HTTP ${f.status}${f.error ? ` ${f.error}` : ''}`; + +// A definite refusal is an OAuth error answer (RFC 6749 §5.2): a 400 or a 401 that names its error. +// Anything else, a maintenance page's 405 or a proxy's 404 among them, says nothing of the grant. +const refused = (f: Token_failure): boolean=> + (f.status === 400 || f.status === 401) && f.error !== undefined; + +const UNAVAILABLE_TITLES: Record, string> = { + timeout: 'The sign-in server did not answer the session refresh in time.', + network: 'The sign-in server could not be reached to refresh the session.', + unreadable: 'The sign-in server\'s answer to the session refresh could not be read.', + lock_wait: 'Another reply process kept the session refresh locked for too long.', +}; + +// The error for a refresh that failed for a reason a later attempt can get past. The stored +// sign-in is kept, and the codes are the ones a caller retries. +const passing_failure = (f: Refresh_failure, detail: string): Operation_error=>{ + const details = refresh_details(f); + if (f.status === 429) + { + return new Operation_error('rate_limited', 'The sign-in server asked for the session refresh to be made later.', { + detail, retry_after: f.retry_after, details, + hint: f.retry_after === undefined ? KEPT_HINT : `The stored sign-in is kept. Run the command again in ${f.retry_after} s.`, + }); + } + const title = f.reason ? UNAVAILABLE_TITLES[f.reason] : 'The sign-in server failed to refresh the session.'; + return new Operation_error('reply.unavailable', title, {detail, details, hint: KEPT_HINT}); +}; + +const STORED_AFTER = { + removed: 'the stored sign-in was removed', + kept: 'the stored sign-in is kept', + gone: 'another process had already signed this profile out', +}; + +const refresh_failed = (f: Token_failure, stored: keyof typeof STORED_AFTER): UsageError=>new UsageError('Session refresh failed.', { + code: 'auth.refresh_failed', + detail: `The sign-in server refused the refresh (${answered(f)}); ${STORED_AFTER[stored]}.`, + details: refresh_details(f), + hint: LOGIN_HINT, +}); + +// Under the lock: read the record again, since another process may have refreshed it while this +// one waited, and refresh only if it still needs it. The new record is stored the moment it is +// read. A record is removed only while the file still holds it, decided on the read the removal +// rewrites: a refused grant can mean another process spent the same one-time refresh token, and +// then the file holds what it stored. +const refresh_under_lock = async( + deps: Resolve_deps & {refresh: NonNullable}, now: number, +): Promise=>{ + const current = await deps.store.get(deps.key); + if (!current) + { + throw not_authenticated(); + } + if (usable(current, now)) + { + return from_store(current); + } + if (current.type !== 'oauth' || !current.refresh_token) + { + await deps.store.remove(deps.key, r=>same_record(r, current)); + throw session_expired(); + } + + let refreshed: Oauth_record; + try { + refreshed = await deps.refresh(current); + } catch (e) { + if (!(e instanceof Token_request_error)) + { + throw e; + } + const f = e.failure; + if (f.status === 400 && f.error === 'invalid_grant') + { + if (await deps.store.remove(deps.key, r=>same_record(r, current))) + { + throw refresh_failed(f, 'removed'); + } + const latest = await deps.store.get(deps.key); + if (latest) + { + return from_store(latest); + } + throw refresh_failed(f, 'gone'); + } + if (refused(f)) + { + throw refresh_failed(f, 'kept'); + } + // A server's own error text can be a whole HTML page; its status says enough. + throw passing_failure(f, f.reason ? e.detail ?? '' : answered(f)); + } + await deps.store.set(deps.key, refreshed); + return from_store(refreshed); +}; + // 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; if that fails it is cleared and the -// user is told to log in again. +// 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. const resolve_credential = async( opts: Resolve_opts, deps: Resolve_deps, @@ -49,44 +196,31 @@ const resolve_credential = async( const record = await deps.store.get(deps.key); if (!record) { - throw new UsageError('Not authenticated.', { - code: 'auth.required', - hint: `Run \`${PROGRAM_NAME} auth login\` or set ${env_var('API_KEY')}.`, - }); - } - - if (record.type === 'api_key') - { - return {token: record.key, type: 'api_key', source: 'store', ephemeral: false, record}; + throw not_authenticated(); } const now = deps.now ?? Date.now(); - if (!needs_refresh(record, now)) + if (usable(record, now)) { - return {token: record.access_token, type: 'oauth', source: 'store', ephemeral: false, record}; + return from_store(record); } - if (!record.refresh_token || !deps.refresh) + const refresh = deps.refresh; + if (!refresh) { await deps.store.remove(deps.key); - throw new UsageError('Session expired.', { - code: 'auth.expired', - hint: `Run \`${PROGRAM_NAME} auth login\` to sign in again.`, - }); + throw session_expired(); } - let refreshed: Oauth_record; try { - refreshed = await deps.refresh(record); - } catch { - await deps.store.remove(deps.key); - throw new UsageError('Session refresh failed.', { - code: 'auth.refresh_failed', - hint: `Run \`${PROGRAM_NAME} auth login\` to sign in again.`, - }); + return await deps.store.with_lock(()=>refresh_under_lock({...deps, refresh}, now)); + } catch (e) { + if (e instanceof Lock_timeout_error) + { + throw passing_failure({reason: 'lock_wait'}, `${e.detail} stayed locked by another reply process.`); + } + throw e; } - await deps.store.set(deps.key, refreshed); - return {token: refreshed.access_token, type: 'oauth', source: 'store', ephemeral: false, record: refreshed}; }; export {resolve_credential}; diff --git a/src/auth/token.ts b/src/auth/token.ts index 183c2d6..2b96bdc 100644 --- a/src/auth/token.ts +++ b/src/auth/token.ts @@ -6,6 +6,9 @@ const DEFAULT_SKEW_MS = 60_000; const DEFAULT_EXPIRES_IN_S = 3600; +// The longest a token request may take before it counts as unanswered. +const TOKEN_TIMEOUT_MS = 20_000; + type Token_response = { access_token: string; refresh_token?: string; @@ -20,8 +23,9 @@ const needs_refresh = ( skew_ms: number = DEFAULT_SKEW_MS, ): boolean=>record.expires_at - skew_ms <= now; +// The answer's fields are typed as the server should send them; a value of another type falls back. const expires_at_from = (resp: Token_response, now: number): number=> - now + (resp.expires_in ?? DEFAULT_EXPIRES_IN_S) * 1000; + now + (typeof resp.expires_in === 'number' && Number.isFinite(resp.expires_in) ? resp.expires_in : DEFAULT_EXPIRES_IN_S) * 1000; const build_token_exchange_body = (p: { code: string; @@ -45,8 +49,8 @@ const build_refresh_body = (p: { client_id: p.client_id, }); -// A token endpoint may rotate the refresh token or omit it; when omitted, keep -// the previous one so subsequent refreshes still work. The token endpoint never +// A token endpoint may rotate the refresh token or omit it; when omitted (or not +// a string), keep the previous one so subsequent refreshes still work. The token endpoint never // returns the principal, so carry the previous `user` forward — otherwise the // first silent refresh would wipe the identity shown by `auth status`. const to_oauth_record = ( @@ -56,13 +60,14 @@ const to_oauth_record = ( ): Oauth_record=>({ type: 'oauth', access_token: resp.access_token, - refresh_token: resp.refresh_token ?? prev?.refresh_token, + refresh_token: typeof resp.refresh_token === 'string' && resp.refresh_token ? resp.refresh_token : prev?.refresh_token, expires_at: expires_at_from(resp, now), user: prev?.user, }); export { DEFAULT_SKEW_MS, + TOKEN_TIMEOUT_MS, needs_refresh, expires_at_from, build_token_exchange_body, diff --git a/src/commands/profile.ts b/src/commands/profile.ts index 0ea07b8..558672b 100644 --- a/src/commands/profile.ts +++ b/src/commands/profile.ts @@ -112,9 +112,18 @@ const handle_rename = async( let credential_moved = false; if (cred) { - await deps.store.set(new_name, cred); - await deps.store.remove(old_name); - credential_moved = true; + // One locked step that moves what the file holds by then, so a refresh of the old key by + // another process is neither lost in between nor overwritten by the copy read above. + credential_moved = await deps.store.with_lock(async()=>{ + const latest = await deps.store.get(old_name); + if (!latest) + { + return false; + } + await deps.store.set(new_name, latest); + await deps.store.remove(old_name); + return true; + }); } const current_updated = current_profile_name(env) === new_name; if (wants_json(g)) diff --git a/src/credentials/file-store.ts b/src/credentials/file-store.ts index 723279f..9944aef 100644 --- a/src/credentials/file-store.ts +++ b/src/credentials/file-store.ts @@ -1,19 +1,30 @@ +import {AsyncLocalStorage} from 'async_hooks'; +import crypto from 'crypto'; import fs from 'fs'; import path from 'path'; import {credentials_file} from '../config'; import {RuntimeError} from '../utils/errors'; +import {take_lock, type Lock_opts} from './lock'; 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']; + // 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). +// Every write is a read-modify-write of the whole file under the lock beside it. class FileCredentialStore implements CredentialStore { private readonly file: string; + private readonly lock_opts: Lock_opts; + private readonly locked = new AsyncLocalStorage(); - constructor(file: string) + constructor(file: string, opts: {lock?: Lock_opts} = {}) { this.file = file; + this.lock_opts = opts.lock ?? {}; } async get(key: string): Promise @@ -23,21 +34,25 @@ class FileCredentialStore implements CredentialStore { async set(key: string, record: Credential_record): Promise { - const map = this.read(); - map[key] = record; - this.write(map); + await this.with_lock(async()=>{ + const map = this.read(); + map[key] = record; + await this.write(map); + }); } - async remove(key: string): Promise + async remove(key: string, only_if?: (record: Credential_record) => boolean): Promise { - const map = this.read(); - if (!(key in map)) - { - return false; - } - delete map[key]; - this.write(map); - return true; + return this.with_lock(async()=>{ + const map = this.read(); + if (!(key in map) || (only_if && !only_if(map[key]))) + { + return false; + } + delete map[key]; + await this.write(map); + return true; + }); } async keys(): Promise @@ -45,6 +60,20 @@ class FileCredentialStore implements CredentialStore { return Object.keys(this.read()); } + async with_lock(fn: () => Promise): Promise + { + if (this.locked.getStore()) + { + return fn(); + } + const release = await take_lock(`${this.file}.lock`, this.lock_opts); + try { + return await this.locked.run(true, fn); + } finally { + await release(); + } + } + private read(): Key_map { let raw: string; @@ -85,15 +114,29 @@ 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 write(map: Key_map): void + private async write(map: Key_map): Promise { const dir = path.dirname(this.file); fs.mkdirSync(dir, {recursive: true, mode: 0o700}); fs.chmodSync(dir, 0o700); - const tmp = `${this.file}.${process.pid}.tmp`; + // Two processes can share a pid, each in a pid namespace of its own: the name can't rest on it alone. + 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); - fs.renameSync(tmp, this.file); + for (let attempt = 0; ; attempt++) + { + try { + fs.renameSync(tmp, this.file); + return; + } catch (e) { + if (attempt >= RENAME_RETRY_MS.length || !RENAME_BUSY.includes(String((e as NodeJS.ErrnoException).code))) + { + fs.rmSync(tmp, {force: true}); + throw e; + } + } + await new Promise(resolve=>setTimeout(resolve, RENAME_RETRY_MS[attempt])); + } } } diff --git a/src/credentials/lock.ts b/src/credentials/lock.ts new file mode 100644 index 0000000..b2cdb29 --- /dev/null +++ b/src/credentials/lock.ts @@ -0,0 +1,229 @@ +import crypto from 'crypto'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import {TOKEN_TIMEOUT_MS} from '../auth/token'; +import {RuntimeError} from '../utils/errors'; + +// A lock file beside the credentials file, created exclusively, so one reply process at a time +// reads, refreshes and writes the sign-in. Several commands started together would otherwise each +// spend the same one-time refresh token, and all but one would be refused. +// +// Only a create puts a lock in place, and it fails while one is there. Every removal of a lock, a +// 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. + +type Lock_opts = { + wait_ms?: number; // how long to wait for another holder before giving up + stale_ms?: number; // a lock held longer than this is taken over, its holder alive or not +}; + +// The longest a holder needs is one token request and one write. A waiter outlasts a stale lock, +// so a holder that hangs never blocks the others for good. +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. +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. +const CREATE_GRACE_MS = 1_000; +const RELEASE_RETRY_MS = [20, 40, 80, 160, 320]; +const WINDOWS_BUSY = ['EPERM', 'EACCES', 'EBUSY']; + +// 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. +const PID_NS = ((): string | undefined=>{ + try { + return fs.readlinkSync('/proc/self/ns/pid'); + } catch { + return undefined; + } +})(); + +// The locks this process let go of but couldn't delete, by id: the only locks with this process's +// 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) + { + super('Another reply process kept the credential store locked.', { + code: 'store.locked', detail: file, + hint: 'Run the command again. If no other reply process is running, delete the lock file.', + }); + this.name = 'Lock_timeout_error'; + } +} + +const lock_error = (file: string, e: unknown): RuntimeError=>new RuntimeError('Could not lock the credential store.', { + code: 'store.lock', detail: file, hint: (e as Error).message, +}); + +const alive = (pid: number): boolean=>{ + try { + process.kill(pid, 0); + return true; + } catch (e) { + return (e as NodeJS.ErrnoException).code === 'EPERM'; + } +}; + +const read_lock = (file: string): {text: string; mtime_ms: number} | undefined=>{ + try { + return {text: fs.readFileSync(file, 'utf8'), mtime_ms: fs.statSync(file).mtimeMs}; + } catch { + return undefined; + } +}; + +const quietly = (fn: () => void): void=>{ + try { + fn(); + } catch { + // Best effort: a lock or guard left behind is taken over by the rules above. + } +}; + +// A lock that can't be read as a holder (cut off before it was written) is judged by the file's age. +// Its pid is trusted only on the host and in the pid namespace that wrote it; anywhere else, a pid +// that looks gone, or looks like this process's own, may be a live peer's. +const is_stale = (held: {text: string; mtime_ms: number}, stale_ms: number): boolean=>{ + let holder: {pid?: unknown; host?: unknown; ns?: unknown; id?: unknown; taken_at?: unknown} | null = null; + try { + holder = JSON.parse(held.text); + } catch { + holder = null; + } + const taken_at = typeof holder?.taken_at === 'number' ? holder.taken_at : held.mtime_ms; + if (Date.now() - taken_at > stale_ms) + { + return true; + } + if (typeof holder?.pid !== 'number' || holder.host !== os.hostname() || holder.ns !== PID_NS) + { + return false; + } + if (holder.pid === process.pid) + { + return typeof holder.id === 'string' && left_here.has(holder.id); + } + return !alive(holder.pid); +}; + +// One attempt at the guard; what lets it go, or undefined when another process has it. +const try_guard = (file: string): (() => void) | undefined=>{ + const guard = `${file}.guard`; + try { + fs.writeFileSync(guard, JSON.stringify({pid: process.pid, id: new_id()}), {flag: 'wx', mode: 0o600}); + return ()=>quietly(()=>fs.unlinkSync(guard)); + } catch { + const held = read_lock(guard); + if (held && Date.now() - held.mtime_ms > GUARD_STALE_MS) + { + quietly(()=>{ + if (fs.readFileSync(guard, 'utf8') === held.text) + { + fs.unlinkSync(guard); + } + }); + } + return undefined; + } +}; + +// Removes the lock if it still reads `text`. False when it doesn't, or the guard is busy. +const remove_if_still = (file: string, text: string): boolean=>{ + const release_guard = try_guard(file); + if (!release_guard) + { + return false; + } + try { + if (fs.readFileSync(file, 'utf8') !== text) + { + return false; + } + fs.unlinkSync(file); + return true; + } catch { + return false; + } finally { + release_guard(); + } +}; + +// Letting go never fails the command. A lock left behind is taken over by this process's next write +// at once, and by any other process once this one has ended or the lock is stale by its age. +const release = async(file: string, mine: string, id: string): Promise=>{ + for (const wait of [...RELEASE_RETRY_MS, 0]) + { + if (remove_if_still(file, mine) || read_lock(file)?.text !== mine) + { + return; + } + if (wait) + { + await new Promise(resolve=>setTimeout(resolve, wait)); + } + } + left_here.add(id); +}; + +// Takes the lock, waiting for a live holder, and returns what lets it go. +const take_lock = async(file: string, opts: Lock_opts = {}): Promise<() => Promise>=>{ + const wait_ms = opts.wait_ms ?? LOCK_WAIT_MS; + const stale_ms = opts.stale_ms ?? LOCK_STALE_MS; + const started = Date.now(); + let refused_since: number | undefined; + fs.mkdirSync(path.dirname(file), {recursive: true, mode: 0o700}); + for (;;) + { + const id = new_id(); + const mine = JSON.stringify({pid: process.pid, host: os.hostname(), ns: PID_NS, id, taken_at: Date.now()}); + let windows_refusal: unknown; + try { + fs.writeFileSync(file, mine, {flag: 'wx', mode: 0o600}); + return ()=>release(file, mine, id); + } catch (e) { + const code = (e as NodeJS.ErrnoException).code; + if (process.platform === 'win32' && WINDOWS_BUSY.includes(String(code))) + { + windows_refusal = e; + } + else if (code !== 'EEXIST') + { + throw lock_error(file, e); + } + } + const held = read_lock(file); + if (held) + { + refused_since = undefined; + if (is_stale(held, stale_ms) && remove_if_still(file, held.text)) + { + continue; + } + } + else if (windows_refusal) + { + refused_since ??= Date.now(); + if (Date.now() - refused_since >= CREATE_GRACE_MS) + { + throw lock_error(file, windows_refusal); + } + } + if (Date.now() - started >= wait_ms) + { + throw new Lock_timeout_error(file); + } + await new Promise(resolve=>setTimeout(resolve, POLL_MS + Math.random() * POLL_MS)); + } +}; + +export {take_lock, Lock_timeout_error}; +export type {Lock_opts}; diff --git a/src/credentials/types.ts b/src/credentials/types.ts index 7384816..9faa430 100644 --- a/src/credentials/types.ts +++ b/src/credentials/types.ts @@ -30,8 +30,12 @@ type Credential_record = Oauth_record | Api_key_record; interface CredentialStore { get(key: string): Promise; set(key: string, record: Credential_record): Promise; - remove(key: string): Promise; + // With only_if, the record is removed only while only_if holds for it, decided on the same read + // the removal rewrites. + remove(key: string, only_if?: (record: Credential_record) => boolean): Promise; keys(): Promise; + // Runs fn while no other process writes the store; set and remove inside it don't wait again. + with_lock(fn: () => Promise): Promise; } export type {Principal, Oauth_record, Api_key_record, Credential_record, CredentialStore}; diff --git a/src/utils/client.ts b/src/utils/client.ts index 1ef4e79..8835c2e 100644 --- a/src/utils/client.ts +++ b/src/utils/client.ts @@ -292,5 +292,5 @@ const create_client = ( get(base_url, token, endpoint, {...opts, headers: {...headers, ...opts?.headers}}), }); -export {request, get, request_raw, create_client, parse_retry_after, sleep}; +export {request, get, request_raw, create_client, parse_retry_after, failure_detail, sleep}; export type {Request_opts, Client, Raw_response, Call_kind}; diff --git a/src/utils/errors.ts b/src/utils/errors.ts index 690b9ca..34852bb 100644 --- a/src/utils/errors.ts +++ b/src/utils/errors.ts @@ -59,13 +59,15 @@ abstract class CliError extends Error { class UsageError extends CliError { readonly exit_code = 2; - constructor(message: string, opts: {code?: string; hint?: string} = {}) + constructor(message: string, opts: {code?: string; hint?: string; detail?: string; details?: Record} = {}) { - super(message); + super(opts.detail ? `${message}\n Detail: ${opts.detail}` : message); this.name = 'UsageError'; this.title = message; this.code = opts.code; this.hint = opts.hint; + this.detail = opts.detail; + this.details = opts.details; } }