diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 03caef6..d015c6c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,10 +21,11 @@ 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. 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. +local `127.0.0.1` listener with an injected browser stub. Some tests run built +CLI processes (`dist/`) against a fake identity server on `127.0.0.1` (two +refreshing one sign-in together, a logout during a refresh, a logout the server +refuses), 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 @@ -67,9 +68,12 @@ reads, changes and rewrites the whole file while holding `credentials.json.lock` 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 +for about 5 s in all, before the write fails. A refresh and a logout also read the +record once under the lock before their request to the identity server, and that +read isn't retried: a refused read fails the command at once, before anything is +sent, which keeps their time under the lock within the sum given below. 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 @@ -100,6 +104,25 @@ endpoint's HTTP status) and `error` (its OAuth error code) when it answered, and 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. +`auth logout` ends an OAuth sign-in at the identity server before it removes the +record. Holding the lock once, it reads the record, posts its refresh token to the +revocation endpoint (`/connect/revocation`, RFC 7009, with +`token_type_hint=refresh_token` and the CLI's client id) and removes the record, +so a refresh by another process can't store a newer token in between that would +stay valid at the server. The revocation times out after 20 s, as the token +request does, so a logout holds the lock no longer than a refresh: one request of +up to 20 s and one write of about 5 s at most, inside the 30 s after which a lock +is taken over. Only a stall past that (a suspended machine, say) lets another +process take the lock over and store a newer token; the removal's own read sees +that the record changed, and the logout reports the sign-in as not ended. The +record is removed whatever the answer. A `2xx` counts as confirmed (RFC 7009 +answers `200` for a token the server doesn't know, too). A redirect isn't +followed, so the token is posted nowhere else. A redirect, another status, a +timeout, a network error or a record that changed leaves one warning line on +stderr and `revoked: false` under `--json`. Nothing is sent for an API-key record +or when nothing is stored, and an API key, stored or from `--api-key` or +`REPLY_API_KEY`, is never sent. + ## Credential resolution Resolved in strict order, first hit wins: diff --git a/README.md b/README.md index 4163025..0a723da 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ Inspect and manage the active credential: ```sh reply auth status # who you're signed in as, and how โ€” no secrets shown reply auth whoami # verify the stored credential against the API -reply auth logout # remove the stored credential +reply auth logout # end the sign-in at Reply and remove the stored credential ``` Pass a key for a single command with `--api-key` or the `REPLY_API_KEY` @@ -130,6 +130,18 @@ server refuses outright fails with `auth.refresh_failed` (exit 2) and needs a ne (`status`, and `error`, its OAuth error code) or why no answer came (`reason`: `timeout`, `network`, `unreadable` or `lock_wait`). Tokens are never printed. +`reply auth logout` ends an OAuth login at Reply too: it revokes the stored refresh +token at the sign-in server, then removes the stored credential, so the login can't +be refreshed again from anywhere. If the sign-in server can't be reached, doesn't +answer within 20 s, refuses or redirects, the credential is still removed and a +warning on stderr says the login may still be valid at Reply. With `--json` the +result is `{"logged_out":true,"revoked":true}`, or `"revoked":false` when the logout +couldn't confirm the login ended at Reply; `revoked` is left out when there was +nothing to revoke (a stored API key, +or nothing stored). A logout always acts on the stored credential, whatever +`--api-key` or `REPLY_API_KEY` says, and an API key is never sent to the sign-in +server. + ## Profiles Profiles keep more than one Reply.io account signed in at once โ€” each stores its @@ -787,7 +799,8 @@ sets it for each command it runs. The value must be one lower-case name of up to 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. The token -requests a sign-in and its refreshes make carry the same User-Agent. +requests a sign-in and its refreshes make, and the revocation a logout sends, +carry the same User-Agent. ## Contributing diff --git a/src/__tests__/auth/oauth-flow.test.ts b/src/__tests__/auth/oauth-flow.test.ts index 83a6d66..d1f56f2 100644 --- a/src/__tests__/auth/oauth-flow.test.ts +++ b/src/__tests__/auth/oauth-flow.test.ts @@ -1,11 +1,15 @@ import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest'; import http from 'http'; +import type {AddressInfo} from 'net'; import {URL} from 'url'; +const real_fetch = globalThis.fetch; const mock_fetch = vi.fn(); vi.stubGlobal('fetch', mock_fetch); -import {build_authorize_url, run_login, refresh_stored, browser_open_command, CLIENT_ID, SCOPE} from '../../auth/oauth-flow'; +import { + build_authorize_url, run_login, refresh_stored, revoke_refresh_token, 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'; @@ -158,4 +162,23 @@ describe('auth/oauth-flow', ()=>{ }); }); }); + + describe('revoke_refresh_token', ()=>{ + // Breaks if a revocation that got no answer in time is taken for one that couldn't reach the + // server: Node names the abort a TimeoutError, and a check that misses it makes a logout warn + // that the sign-in server could not be reached. + it('comes back unconfirmed, as a timeout, when the server never answers', async()=>{ + const server = http.createServer(()=>{ /* takes the request and never answers */ }); + await new Promise(resolve=>server.listen(0, '127.0.0.1', resolve)); + const {port} = server.address() as AddressInfo; + mock_fetch.mockImplementationOnce(real_fetch); + try { + expect(await revoke_refresh_token({authority: `http://127.0.0.1:${port}`, refresh_token: 'RT', timeout_ms: 100})) + .toEqual({revoked: false, reason: 'timeout'}); + } finally { + server.closeAllConnections(); + await new Promise(resolve=>server.close(()=>resolve())); + } + }); + }); }); diff --git a/src/__tests__/auth/refresh-processes.test.ts b/src/__tests__/auth/refresh-processes.test.ts index f0d8937..4464a86 100644 --- a/src/__tests__/auth/refresh-processes.test.ts +++ b/src/__tests__/auth/refresh-processes.test.ts @@ -6,17 +6,24 @@ 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. +// The built CLI: these tests run 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. +// Long enough for a second process to start and reach the sign-in server while the first waits. const HOLD_MS = 2_000; +type Seen = {path: string; user_agent?: string; body: string}; + type Fake_reply = { url: string; refreshes: number; refresh_tokens: Set; access_tokens: Set; + seen: Seen[]; + revocation_status: number; + on_revocation?: () => void; + hold_ms: number; + release: () => void; close: () => Promise; }; @@ -33,9 +40,17 @@ const send_json = (res: http.ServerResponse, status: number, body: unknown): voi }; // 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. +// refresh tokens, as Reply's does, and answers a spent one with invalid_grant. A refresh takes +// effect when it arrives and only its answer waits: the first one is held until a second one +// arrives, the test calls `release`, or `hold_ms` passes. So two processes that refresh at once +// both reach it with the same token, and a process that reads the file meanwhile still finds the +// spent one. +// +// Its revocation endpoint (RFC 7009) answers 200 for a token revoked and for one it doesn't know, +// and accepts only the request the CLI is meant to send: a refresh token named as one, for the +// CLI's client. `revocation_status` set to an error makes it refuse, revoking nothing; set to 307 +// it redirects to `/moved`, which would revoke and confirm. `on_revocation` runs as a revocation +// arrives, before it is answered. const start_fake_reply = async(): Promise=>{ let next = 1; let release_first: (() => void) | undefined; @@ -43,6 +58,11 @@ const start_fake_reply = async(): Promise=>{ refreshes: 0, refresh_tokens: new Set(['rt-0']), access_tokens: new Set(), + seen: [] as Seen[], + revocation_status: 200, + on_revocation: undefined as (() => void) | undefined, + hold_ms: HOLD_MS, + release: ()=>release_first?.(), }; const answer_refresh = (form: URLSearchParams): [number, unknown]=>{ @@ -57,11 +77,30 @@ const start_fake_reply = async(): Promise=>{ return [200, {access_token: `at-${n}`, refresh_token: `rt-${n}`, expires_in: 3600, token_type: 'Bearer'}]; }; + const answer_revocation = (form: URLSearchParams, status: number): [number, unknown]=>{ + if (form.get('client_id') !== 'Reply.Cli') + { + return [400, {error: 'invalid_client'}]; + } + if (form.get('token_type_hint') !== 'refresh_token' || !form.get('token')) + { + return [400, {error: 'unsupported_token_type'}]; + } + if (status !== 200) + { + return [status, {error: 'server_error'}]; + } + fake.refresh_tokens.delete(form.get('token') ?? ''); + return [200, {}]; + }; + const server = http.createServer(async(req, res)=>{ const body = await read_body(req); + fake.seen.push({path: req.url ?? '', user_agent: req.headers['user-agent'], body}); if (req.method === 'POST' && req.url === '/connect/token') { fake.refreshes += 1; + const [status, answer] = answer_refresh(new URLSearchParams(body)); if (release_first) { release_first(); @@ -72,11 +111,29 @@ const start_fake_reply = async(): Promise=>{ { await new Promise(resolve=>{ release_first = resolve; - setTimeout(resolve, HOLD_MS); + setTimeout(resolve, fake.hold_ms); }); release_first = undefined; } - const [status, answer] = answer_refresh(new URLSearchParams(body)); + send_json(res, status, answer); + return; + } + if (req.method === 'POST' && req.url === '/connect/revocation') + { + fake.on_revocation?.(); + if (fake.revocation_status === 307) + { + res.writeHead(307, {Location: '/moved'}); + res.end(); + return; + } + const [status, answer] = answer_revocation(new URLSearchParams(body), fake.revocation_status); + send_json(res, status, answer); + return; + } + if (req.method === 'POST' && req.url === '/moved') + { + const [status, answer] = answer_revocation(new URLSearchParams(body), 200); send_json(res, status, answer); return; } @@ -101,10 +158,23 @@ const start_fake_reply = async(): Promise=>{ }); }; +// An address nothing listens on: a port the system handed out, closed again. +const closed_url = async(): Promise=>{ + const server = http.createServer(); + await new Promise(resolve=>server.listen(0, '127.0.0.1', resolve)); + const {port} = server.address() as AddressInfo; + await new Promise(resolve=>server.close(()=>resolve())); + return `http://127.0.0.1:${port}`; +}; + type Run = {code: number | null; stdout: string; stderr: string}; -const run_cli = (args: string[], env: NodeJS.ProcessEnv): Promise=>new Promise(resolve=>{ +const run_cli = (args: string[], env: NodeJS.ProcessEnv, on_spawn?: () => void): Promise=>new Promise(resolve=>{ const child = spawn(process.execPath, [CLI, ...args], {env, stdio: ['ignore', 'pipe', 'pipe']}); + if (on_spawn) + { + child.on('spawn', on_spawn); + } let stdout = ''; let stderr = ''; child.stdout.on('data', chunk=>{ stdout += chunk; }); @@ -112,11 +182,47 @@ const run_cli = (args: string[], env: NodeJS.ProcessEnv): Promise=>new Prom child.on('close', code=>resolve({code, stdout, stderr})); }); -describe('two reply processes refreshing one expired sign-in together', ()=>{ +const until = async(done: () => boolean, ms = 10_000): Promise=>{ + const end = Date.now() + ms; + while (!done()) + { + if (Date.now() > end) + { + throw new Error(`still waiting after ${ms} ms`); + } + await new Promise(r=>setTimeout(r, 20)); + } +}; + +// Nothing outside the temp dir: no credential, profile or home from the machine running the test. +const isolated_env = (dir: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv=>{ + const env: NodeJS.ProcessEnv = Object.fromEntries( + Object.entries(process.env).filter(([name])=>!name.startsWith('REPLY_'))); + return 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, + }, extra); +}; + +const oauth_record = (expires_at: number)=>({type: 'oauth', access_token: 'at-0', refresh_token: 'rt-0', expires_at}); + +// Points the profile at `authority` and stores `record` as its only credential. +const sign_in = (dir: string, authority: string, record: unknown): void=>{ + fs.writeFileSync(path.join(dir, 'config.json'), + JSON.stringify({profiles: {[PROFILE]: {authority, api_base: authority}}})); + fs.writeFileSync(path.join(dir, 'credentials.json'), JSON.stringify({[PROFILE]: record})); +}; + +const stored = (dir: string): unknown=>JSON.parse(fs.readFileSync(path.join(dir, 'credentials.json'), 'utf8'))[PROFILE]; + +const warnings = (r: Run): string[]=>r.stderr.split('\n').filter(l=>l.includes('may still be valid at Reply')); + +describe('reply processes against one sign-in', ()=>{ let dir: string; let fake: Fake_reply; beforeEach(async()=>{ + expect(fs.existsSync(CLI), `${CLI} is missing: run \`npm run build\` first`).toBe(true); dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-race-')); fake = await start_fake_reply(); }); @@ -128,22 +234,9 @@ describe('two reply processes refreshing one expired sign-in together', ()=>{ // 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, - }); + it('two processes refreshing one expired sign-in together both end signed in, on one refresh', async()=>{ + sign_in(dir, fake.url, oauth_record(Date.now() - 60_000)); + const env = isolated_env(dir); const runs = await Promise.all([ run_cli(['auth', 'whoami', '--json'], env), @@ -156,10 +249,127 @@ describe('two reply processes refreshing one expired sign-in together', ()=>{ 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); + const record = stored(dir) as {expires_at: number; refresh_token: string}; + expect(record).toMatchObject({type: 'oauth', access_token: 'at-1', refresh_token: 'rt-1'}); + expect(record.expires_at).toBeGreaterThan(Date.now()); + expect(fake.refresh_tokens.has(record.refresh_token)).toBe(true); + expect(fs.existsSync(path.join(dir, 'credentials.json.lock'))).toBe(false); + }, 30_000); + + // Breaks if a logout reads the refresh token outside the credentials lock: while another process + // refreshes, it would revoke the spent token and leave the new one alive at Reply after the person + // signed out. Breaks too if the revocation doesn't name the token as a refresh token or carry the + // CLI's client id (the fake refuses it), or goes out under another User-Agent than the token + // requests. + it('a logout while another process refreshes ends the refreshed sign-in at Reply', async()=>{ + sign_in(dir, fake.url, oauth_record(Date.now() - 60_000)); + const env = isolated_env(dir, {REPLY_CLIENT: 'some-app/1.2.3'}); + // The refresh's answer waits for the test, not a clock started before the logout spawned: the + // logout gets HOLD_MS from its own start to read the file while it still holds the spent token. + fake.hold_ms = 20_000; + + const whoami = run_cli(['auth', 'whoami', '--json'], env); + await until(()=>fake.refreshes === 1); + const logout = await run_cli(['auth', 'logout', '--json'], env, ()=>setTimeout(fake.release, HOLD_MS)); + const refreshed = await whoami; + + expect([refreshed.code, logout.code], refreshed.stderr + logout.stderr).toEqual([0, 0]); + expect(JSON.parse(logout.stdout)).toEqual({logged_out: true, revoked: true}); + expect(fake.refresh_tokens.size).toBe(0); + expect(stored(dir)).toBeUndefined(); + const sign_in_requests = fake.seen.filter(s=>s.path.startsWith('/connect/')); + expect(sign_in_requests.map(s=>s.path).sort()).toEqual(['/connect/revocation', '/connect/token']); + expect(new Set(sign_in_requests.map(s=>s.user_agent))).toEqual(new Set([expect.stringMatching(/^some-app\/1\.2\.3 reply-cli\//)])); + }, 30_000); + + // Breaks if a revocation that fails keeps the local record or fails the command (the person asked + // to be signed out here), if nothing says the sign-in may live on at Reply, or if a token is + // printed. Breaks too if a redirect is followed: it would post the refresh token wherever the + // redirect points, and a page that answers there would count as confirmed. + it('a logout the sign-in server refuses, redirects, or can\'t be reached for, still signs out here and says so', async()=>{ + const env = isolated_env(dir); + + fake.revocation_status = 503; + sign_in(dir, fake.url, oauth_record(Date.now() + 3_600_000)); + const refused = await run_cli(['auth', 'logout', '--json'], env); + expect(refused.code, refused.stderr).toBe(0); + expect(JSON.parse(refused.stdout)).toEqual({logged_out: true, revoked: false}); + expect(refused.stderr.trim().split('\n')).toEqual(warnings(refused)); + expect(warnings(refused)).toHaveLength(1); + expect(fake.refresh_tokens.has('rt-0')).toBe(true); + expect(stored(dir)).toBeUndefined(); + + fake.revocation_status = 307; + sign_in(dir, fake.url, oauth_record(Date.now() + 3_600_000)); + const redirected = await run_cli(['auth', 'logout', '--json'], env); + expect(redirected.code, redirected.stderr).toBe(0); + expect(JSON.parse(redirected.stdout)).toEqual({logged_out: true, revoked: false}); + expect(warnings(redirected)).toEqual([expect.stringContaining('HTTP 307')]); + expect(fake.seen.map(s=>s.path)).not.toContain('/moved'); + expect(fake.refresh_tokens.has('rt-0')).toBe(true); + expect(stored(dir)).toBeUndefined(); + + sign_in(dir, await closed_url(), oauth_record(Date.now() + 3_600_000)); + const unreachable = await run_cli(['auth', 'logout'], env); + expect(unreachable.code, unreachable.stderr).toBe(0); + expect(unreachable.stderr).toContain('Logged out.'); + expect(warnings(unreachable)).toHaveLength(1); + expect(stored(dir)).toBeUndefined(); + + for (const r of [refused, redirected, unreachable]) + { + expect(r.stdout + r.stderr).not.toMatch(/rt-0|at-0/); + } + }, 30_000); + + // Breaks if a logout reports the sign-in ended at Reply after the record changed under it while + // its revocation was out. That happens when it stalls past the lock's stale limit (a suspended + // machine) and another process takes the lock over and stores a refreshed token: the token + // revoked is then the spent one, and the new one is still live at Reply. + it('a logout whose record changed during the revocation says the sign-in may still be valid', async()=>{ + sign_in(dir, fake.url, oauth_record(Date.now() + 3_600_000)); + fake.on_revocation = ()=>{ + // What a process that took the lock over leaves: rt-0 refreshed to rt-1, and rt-1 stored. + fake.refresh_tokens.delete('rt-0'); + fake.refresh_tokens.add('rt-1'); + sign_in(dir, fake.url, {type: 'oauth', access_token: 'at-1', refresh_token: 'rt-1', expires_at: Date.now() + 3_600_000}); + }; + + const logout = await run_cli(['auth', 'logout', '--json'], isolated_env(dir)); + + expect(logout.code, logout.stderr).toBe(0); + expect(JSON.parse(logout.stdout)).toEqual({logged_out: true, revoked: false}); + expect(logout.stderr.trim().split('\n')).toEqual(warnings(logout)); + expect(warnings(logout)).toHaveLength(1); + expect(fake.refresh_tokens.has('rt-1')).toBe(true); + expect(stored(dir)).toBeUndefined(); + expect(logout.stdout + logout.stderr).not.toMatch(/rt-[01]|at-[01]/); + }, 30_000); + + // Breaks if an API key, stored or from --api-key or REPLY_API_KEY, is ever posted to the sign-in + // server, if a logout with no sign-in to end sends anything or reports a revocation, or if a key + // in play keeps a stored OAuth sign-in from being ended at Reply. + it('a logout sends only a stored refresh token, never an API key', async()=>{ + const env = isolated_env(dir, {REPLY_API_KEY: 'env-key'}); + + sign_in(dir, fake.url, {type: 'api_key', key: 'stored-key'}); + const api_key_logout = await run_cli(['auth', 'logout', '--json', '--api-key', 'flag-key'], env); + expect(api_key_logout.code, api_key_logout.stderr).toBe(0); + expect(JSON.parse(api_key_logout.stdout)).toEqual({logged_out: true}); + expect(stored(dir)).toBeUndefined(); + + const nothing_stored = await run_cli(['auth', 'logout', '--json'], env); + expect(nothing_stored.code, nothing_stored.stderr).toBe(0); + expect(JSON.parse(nothing_stored.stdout)).toEqual({logged_out: false}); + expect(fake.seen).toEqual([]); + + sign_in(dir, fake.url, oauth_record(Date.now() + 3_600_000)); + const oauth_logout = await run_cli(['auth', 'logout', '--json', '--api-key', 'flag-key'], env); + expect(oauth_logout.code, oauth_logout.stderr).toBe(0); + expect(JSON.parse(oauth_logout.stdout)).toEqual({logged_out: true, revoked: true}); + expect(fake.refresh_tokens.has('rt-0')).toBe(false); + expect(stored(dir)).toBeUndefined(); + expect(fake.seen.map(s=>s.path)).toEqual(['/connect/revocation']); + expect(fake.seen[0].body).not.toMatch(/stored-key|env-key|flag-key/); }, 30_000); }); diff --git a/src/auth/oauth-flow.ts b/src/auth/oauth-flow.ts index c641533..974cde2 100644 --- a/src/auth/oauth-flow.ts +++ b/src/auth/oauth-flow.ts @@ -298,6 +298,48 @@ const refresh_stored = async(p: { return to_oauth_record(resp, now, p.record); }; +// What became of a revocation: confirmed, or why not. Never a token or the request body. +type Revocation = + | {revoked: true} + | {revoked: false; status?: number; reason?: 'timeout' | 'network'}; + +// Ends a refresh token at the sign-in server (RFC 7009), so the sign-in can't be refreshed again. The +// server answers 200 for a token it revoked and for one it doesn't know, so any 2xx counts as +// confirmed. A redirect isn't followed: following one would post the token wherever it points, and +// a page answering there would read as confirmed. It doesn't throw: a logout removes the stored +// record whatever the server says. A logout holds the credentials lock across it, so it waits no +// longer than a token request. +const revoke_refresh_token = async(p: { + authority: string; + refresh_token: string; + client_id?: string; + timeout_ms?: number; +}): Promise=>{ + const timeout_ms = p.timeout_ms ?? TOKEN_TIMEOUT_MS; + try { + const res = await fetch(`${p.authority}/connect/revocation`, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': user_agent(), + }, + body: new URLSearchParams({ + token: p.refresh_token, + token_type_hint: 'refresh_token', + client_id: p.client_id ?? CLIENT_ID, + }).toString(), + redirect: 'manual', + signal: AbortSignal.timeout(timeout_ms), + }); + // The answer's body says nothing more (RFC 7009 ยง2.2); dropping it frees the connection. + await res.body?.cancel().catch(()=>undefined); + return res.ok ? {revoked: true} : {revoked: false, status: res.status}; + } catch (e) { + const timed_out = (e as Error)?.name === 'TimeoutError' || (e as Error)?.name === 'AbortError'; + return {revoked: false, reason: timed_out ? 'timeout' : 'network'}; + } +}; + // Full authorization-code + PKCE loopback login. `open` is injectable so the // loopback can be exercised without a real browser/IdP in tests. const run_login = async(opts: { @@ -323,6 +365,6 @@ const run_login = async(opts: { export { CLIENT_ID, SCOPE, Token_request_error, - build_authorize_url, run_login, exchange_code, refresh_stored, browser_open_command, + build_authorize_url, run_login, exchange_code, refresh_stored, revoke_refresh_token, browser_open_command, }; -export type {Token_failure}; +export type {Token_failure, Revocation}; diff --git a/src/commands/auth.ts b/src/commands/auth.ts index a5517a5..45f2c47 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -5,8 +5,9 @@ import {build_context, type Cli_context} from '../context'; import {create_client} from '../utils/client'; import {resolve_credential} from '../auth/resolve'; import {resolve_request_identity} from '../auth/request-identity'; -import {run_login} from '../auth/oauth-flow'; +import {run_login, revoke_refresh_token} from '../auth/oauth-flow'; import {describe_status} from '../auth/status'; +import {TOKEN_TIMEOUT_MS} from '../auth/token'; import {UsageError} from '../utils/errors'; import {success, info, warn, print, pc, type Print_opts} from '../utils/output'; import type {Api_key_record, Credential_record, Principal} from '../credentials/types'; @@ -171,19 +172,71 @@ const handle_login_token = async( success(`Stored API key for ${principal_label(user)}${profile_note(ctx.profile)}.`); }; +// A logout's revocation, or 'replaced' when the record changed under the logout while it was out. +type Logout_revocation = + | {revoked: true} + | {revoked: false; status?: number; reason?: 'timeout' | 'network' | 'replaced'}; + +const revocation_failure = (r: Extract): string=>{ + if (r.reason === 'replaced') + { + return 'the stored sign-in changed while the logout was ending it'; + } + if (r.status !== undefined) + { + return `the sign-in server answered HTTP ${r.status}`; + } + return r.reason === 'timeout' + ? `the sign-in server did not answer within ${TOKEN_TIMEOUT_MS / 1000} s` + : 'the sign-in server could not be reached'; +}; + +// The stored record is the one logged out, whatever key --api-key or the environment supplies. Its +// read, the revocation of its refresh token and its removal share one hold of the credentials lock, +// so a refresh by another process can't store a newer token in between. Only a stall past the +// lock's stale limit (a suspended machine, say) lets another process take the lock over and store +// one; the removal's own read sees that, and the logout then reports the sign-in as not ended, +// since the token it revoked is no longer the live one. The record is removed whatever the server +// says. const handle_logout = async(ctx: Cli_context, g: Global_opts): Promise=>{ - const removed = await ctx.store.remove(ctx.key); + type Logout = {removed: boolean; revocation?: Logout_revocation}; + const {removed, revocation} = await ctx.store.with_lock(async(): Promise=>{ + const record = await ctx.store.get(ctx.key); + if (!record) + { + return {removed: false}; + } + if (record.type !== 'oauth' || !record.refresh_token) + { + return {removed: await ctx.store.remove(ctx.key)}; + } + const token = record.refresh_token; + let revocation: Logout_revocation = await revoke_refresh_token({authority: ctx.authority, refresh_token: token}); + const removed = await ctx.store.remove(ctx.key, r=>{ + if (revocation.revoked && (r.type !== 'oauth' || r.refresh_token !== token)) + { + revocation = {revoked: false, reason: 'replaced'}; + } + return true; + }); + return {removed, revocation}; + }); if (wants_json(g)) { - print({logged_out: removed}, print_opts(g)); - return; + print({logged_out: removed, ...(revocation ? {revoked: revocation.revoked} : {})}, print_opts(g)); } - if (removed) + else if (removed) { success('Logged out.'); - return; } - info('No stored credential to remove.'); + else + { + info('No stored credential to remove.'); + } + if (revocation && !revocation.revoked) + { + warn(`The sign-in may still be valid at Reply: ${revocation_failure(revocation)}.`); + } }; const handle_status = async(ctx: Cli_context, g: Global_opts): Promise=>{ @@ -291,7 +344,7 @@ auth_command auth_command .command('logout') - .description('Remove the stored credential') + .description('End the stored sign-in at Reply and remove the stored credential') .action(async function(this: Command) { const g = read_globals(this); await handle_logout(build_context({profile: g.profile}), g); diff --git a/src/credentials/file-store.ts b/src/credentials/file-store.ts index a629c25..a5eb1fa 100644 --- a/src/credentials/file-store.ts +++ b/src/credentials/file-store.ts @@ -11,8 +11,8 @@ type Key_map = Record; // 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. +// those refusals from one copy of these waits: about 5 s in all, so that with its request to the +// sign-in server a refresh or a logout 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']; diff --git a/src/credentials/lock.ts b/src/credentials/lock.ts index 335d314..f371196 100644 --- a/src/credentials/lock.ts +++ b/src/credentials/lock.ts @@ -26,7 +26,8 @@ type Lock_opts = { 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, +// The longest a holder needs is one request to the sign-in server (a refresh's token request or a +// logout's revocation, each bounded by TOKEN_TIMEOUT_MS) 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;