From a3cb41878d28dab49eaac2f7b0f43bd8465a1cac Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:40:33 -0700 Subject: [PATCH 1/6] chore(main): release 0.24.0 (#259) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 23 +++++++++++++++++++++++ package.json | 2 +- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 97bce112..fc5553b0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.23.0" + ".": "0.24.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index b72f2c60..39e2b876 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.24.0](https://github.com/workos/cli/compare/v0.23.0...v0.24.0) (2026-10-21) + + +### ⚠ BREAKING CHANGES + +* The npm package no longer exports a library API — `main`/`exports` are gone and it only provides the `workos` binary. Development now requires Bun >= 1.3.0 instead of Node >= 22.11. + +### Features + +* Download migrations and emulate bundles at runtime ([#203](https://github.com/workos/cli/issues/203)) ([b07f661](https://github.com/workos/cli/commit/b07f661f4f647c6afee5b9184a7507cb1fe418e8)) +* **skills:** offer to update stale skills after commands ([#237](https://github.com/workos/cli/issues/237)) ([6f27596](https://github.com/workos/cli/commit/6f275967d1e2bc130ca695a052068f107c0b5bf1)) +* switch installer to Claude Opus 5.5 and bump @workos/skills to 0.8.0 ([#265](https://github.com/workos/cli/issues/265)) ([d7912fa](https://github.com/workos/cli/commit/d7912fa7ee5eac0a42fb9c98da8f46400619b458)) + + +### Bug Fixes + +* **installer:** coordinate spinner and prompt ownership ([#256](https://github.com/workos/cli/issues/256)) ([098ddb0](https://github.com/workos/cli/commit/098ddb0bec4a9ef29a4dc6cb6a7b911514c9550b)) +* **installer:** give the agent its rules, unbreak non-JS installs, and run evals through the real installer ([#266](https://github.com/workos/cli/issues/266)) ([8b223d6](https://github.com/workos/cli/commit/8b223d6aa9f2e24bee8583a8a163fbbb6d71d414)) +* **installer:** recover unauthorized dashboard configuration safely ([#255](https://github.com/workos/cli/issues/255)) ([28e3ce4](https://github.com/workos/cli/commit/28e3ce4d94117d1c8b88558dbbf7492a598a6d3f)) +* **installer:** remove commit and pull request prompts ([#257](https://github.com/workos/cli/issues/257)) ([4da43d9](https://github.com/workos/cli/commit/4da43d9520267603335120e984a3ebdd528cc502)) +* **installer:** stop loading user Claude Code settings in the installer agent ([#267](https://github.com/workos/cli/issues/267)) ([0d2a1c3](https://github.com/workos/cli/commit/0d2a1c38f969f403ee9c5a31935a14514d8b20c2)) +* **ruby:** improve Rails setup and prepare Fizzy acceptance ([#258](https://github.com/workos/cli/issues/258)) ([dea3326](https://github.com/workos/cli/commit/dea3326b3e04d43637f8e4e7ad93d070598e61d2)) + ## [0.23.0](https://github.com/workos/cli/compare/v0.22.0...v0.23.0) (2026-09-25) diff --git a/package.json b/package.json index 569eacf0..ae7b9ad3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workos", - "version": "0.23.0", + "version": "0.24.0", "type": "module", "description": "The Official Workos CLI", "repository": { From f9dd43f45a6bf04e589ce46697371c9ade93e568 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Wed, 11 Nov 2026 18:25:46 -0800 Subject: [PATCH 2/6] feat(wif): retry the exchange and API 401s, and say what to fix on every OAuth error Retry the token exchange on a network error or 5xx, up to three attempts, requesting a fresh GitHub OIDC token each time because WorkOS accepts each one once. Never retry a 4xx. Re-exchange and re-send an API call once when the API answers 401. Handle unauthorized_client, and make each OAuth error hint name the setting to change. --- src/commands/api/request.ts | 27 ++-- src/lib/wif.spec.ts | 287 +++++++++++++++++++++++++++++++++++- src/lib/wif.ts | 148 ++++++++++++++++--- src/lib/workos-api.ts | 20 ++- src/utils/exit-codes.ts | 1 + 5 files changed, 440 insertions(+), 43 deletions(-) diff --git a/src/commands/api/request.ts b/src/commands/api/request.ts index 0057c85c..e7781215 100644 --- a/src/commands/api/request.ts +++ b/src/commands/api/request.ts @@ -1,5 +1,6 @@ import { resolveApiKeyAsync, resolveApiBaseUrl } from '../../lib/api-key.js'; -import { wifAuthHeaders } from '../../lib/wif.js'; +import { sendWithWifAuth } from '../../lib/wif.js'; +import { CliExit } from '../../utils/cli-exit.js'; export interface ApiRequestOptions { method: string; @@ -25,12 +26,7 @@ export async function apiRequest(options: ApiRequestOptions): Promise = { - // An API key passes through as `Bearer `; a WIF token is refreshed - // if needed and carries x-url-environment-id when configured. - ...(await wifAuthHeaders(apiKey)), - Accept: 'application/json', - }; + const headers: Record = { Accept: 'application/json' }; if (options.body !== undefined) { headers['Content-Type'] = 'application/json'; @@ -38,12 +34,19 @@ export async function apiRequest(options: ApiRequestOptions): Promise`; a WIF token is refreshed + // if needed, carries x-url-environment-id when configured, and is + // exchanged again once if the API answers 401. + response = await sendWithWifAuth(apiKey, (authHeaders) => + fetch(url, { + method: options.method, + headers: { ...authHeaders, ...headers }, + body: options.body, + }), + ); } catch (err) { + // A failed WIF exchange has already reported its own error. + if (err instanceof CliExit) throw err; const detail = err instanceof Error ? err.message : String(err); throw new Error(`Failed to connect to WorkOS API: ${detail}`, err instanceof Error ? { cause: err } : undefined); } diff --git a/src/lib/wif.spec.ts b/src/lib/wif.spec.ts index ca6e0bd0..cc4640d2 100644 --- a/src/lib/wif.spec.ts +++ b/src/lib/wif.spec.ts @@ -11,6 +11,7 @@ const { getWifState, isWifAccessToken, resetWifCacheForTests, + setWifRetryBackoffForTests, WIF_GRANT_TYPE, ENVIRONMENT_ID_HEADER, } = await import('./wif.js'); @@ -100,6 +101,7 @@ describe('workload identity federation (wif)', () => { activeEnv = undefined; resetWifCacheForTests(); + setWifRetryBackoffForTests(0); resetRegisteredSecretsForTests(); setOutputMode('human'); @@ -402,7 +404,7 @@ describe('workload identity federation (wif)', () => { tokenHandler = () => json({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 300 }); expect(await getWifAccessToken()).toBe(ACCESS_TOKEN); - expect(tokenCalls()).toHaveLength(2); + expect(tokenCalls()).toHaveLength(4); }); }); @@ -471,10 +473,11 @@ describe('workload identity federation (wif)', () => { it.each([ ['invalid_grant', 'trust rules'], ['invalid_target', 'audience'], - ['invalid_client', 'WORKOS_CLIENT_ID'], - ['invalid_scope', 'WORKOS_WIF_SCOPE'], + ['invalid_client', 'Set WORKOS_CLIENT_ID to the client ID'], + ['unauthorized_client', 'Check that WORKOS_CLIENT_ID is an M2M application with an enabled GitHub trust rule'], + ['invalid_scope', 'Set WORKOS_WIF_SCOPE to scopes the application has, or unset it'], ['invalid_request', '/oauth2/token'], - ])('%s: names the error, includes error_description and a hint', async (error, hint) => { + ])('%s: names the error, includes error_description and says what to fix', async (error, hint) => { tokenHandler = () => json({ error, error_description: `server says ${error} happened` }, 400); const exit = await expectCliExit(resolveApiKeyAsync()); @@ -484,6 +487,31 @@ describe('workload identity federation (wif)', () => { expect(message).toContain(error); expect(message).toContain(`server says ${error} happened`); expect(message).toContain(hint); + // A 4xx is final: one GitHub token, one exchange. + expect(githubCalls()).toHaveLength(1); + expect(tokenCalls()).toHaveLength(1); + }); + + it('invalid_grant and invalid_target say which settings to compare', async () => { + tokenHandler = () => json({ error: 'invalid_grant' }, 400); + await expectCliExit(resolveApiKeyAsync()); + expect(stderr.join('\n')).toContain("Check the trust rule's repository, ref and audience against this run"); + + stderr.length = 0; + tokenHandler = () => json({ error: 'invalid_target' }, 400); + await expectCliExit(resolveApiKeyAsync()); + expect(stderr.join('\n')).toContain("Set the trust rule's audience and WORKOS_WIF_AUDIENCE to the same value"); + }); + + it('unauthorized_client exits 4 and names every condition to check', async () => { + tokenHandler = () => json({ error: 'unauthorized_client' }, 400); + + const exit = await expectCliExit(resolveApiKeyAsync()); + expect(exit.context?.errorCode).toBe('wif_unauthorized_client'); + expect(exit.exitCode).toBe(4); + const message = stderr.join('\n'); + expect(message).toContain('turned on for your WorkOS team'); + expect(message).toContain('non-production environment'); }); it('non-JSON response: generic message with the HTTP status', async () => { @@ -506,6 +534,7 @@ describe('workload identity federation (wif)', () => { expect(exit.context?.errorCode).toBe('wif_exchange_failed'); expect(stderr.join('\n')).toContain('Could not reach WORKOS_WIF_TOKEN_URL'); expect(stderr.join('\n')).toContain('ECONNREFUSED'); + expect(stderr.join('\n')).toContain('Check that WORKOS_WIF_TOKEN_URL is right and reachable'); }); it('success status without access_token: generic message with the HTTP status', async () => { @@ -538,6 +567,238 @@ describe('workload identity federation (wif)', () => { }); }); + describe('retries', () => { + function assertionOf(call: FetchCall): string | null { + return new URLSearchParams(String(call.init?.body)).get('assertion'); + } + + describe('API 401', () => { + /** 401 for the first access token, 200 for any later one. */ + function rejectFirstToken(): void { + apiHandler = (_url, init) => + new Headers(init?.headers).get('authorization') === `Bearer ${ACCESS_TOKEN}` + ? json({ message: 'Unauthorized' }, 401) + : json({ data: [], list_metadata: { before: null, after: null } }); + } + + it('apiRequest exchanges again and re-sends once with the new token', async () => { + process.env.WORKOS_ENVIRONMENT_ID = 'environment_01ABC'; + rejectFirstToken(); + + const response = await apiRequest({ + method: 'POST', + path: '/organizations', + body: '{"name":"acme"}', + baseUrl: API_BASE, + }); + + expect(response.status).toBe(200); + const sent = apiCalls(); + expect(sent.map((c) => headersOf(c).get('authorization'))).toEqual([ + `Bearer ${ACCESS_TOKEN}`, + `Bearer ${ACCESS_TOKEN_2}`, + ]); + for (const call of sent) { + expect(call.init?.method).toBe('POST'); + expect(call.init?.body).toBe('{"name":"acme"}'); + expect(headersOf(call).get(ENVIRONMENT_ID_HEADER)).toBe('environment_01ABC'); + } + // The second exchange used its own GitHub OIDC token. + expect(githubCalls()).toHaveLength(2); + expect(tokenCalls()).toHaveLength(2); + }); + + it('workosRequest and the SDK client re-send once too', async () => { + rejectFirstToken(); + const token = await resolveApiKeyAsync(); + + await workosRequest({ method: 'GET', path: '/audit_logs/actions', apiKey: token, baseUrl: API_BASE }); + expect(apiCalls().map((c) => headersOf(c).get('authorization'))).toEqual([ + `Bearer ${ACCESS_TOKEN}`, + `Bearer ${ACCESS_TOKEN_2}`, + ]); + + // The SDK client still holds the first token; it now sends the replacement. + resetWifCacheForTests(); + accessTokens = [ACCESS_TOKEN, ACCESS_TOKEN_2]; + calls = []; + const stale = await resolveApiKeyAsync(); + await createWorkOSClient(stale, API_BASE).sdk.organizations.listOrganizations(); + expect(apiCalls().map((c) => headersOf(c).get('authorization'))).toEqual([ + `Bearer ${ACCESS_TOKEN}`, + `Bearer ${ACCESS_TOKEN_2}`, + ]); + expect(tokenCalls()).toHaveLength(2); + }); + + it('a second 401 is returned, with no third request and no third exchange', async () => { + apiHandler = () => json({ message: 'Unauthorized' }, 401); + + const response = await apiRequest({ method: 'GET', path: '/organizations', baseUrl: API_BASE }); + + expect(response.status).toBe(401); + expect(apiCalls()).toHaveLength(2); + expect(tokenCalls()).toHaveLength(2); + }); + + it.each([403, 404, 500])('does not re-send or exchange again on %i', async (status) => { + apiHandler = () => json({ message: 'nope' }, status); + + const response = await apiRequest({ method: 'GET', path: '/organizations', baseUrl: API_BASE }); + + expect(response.status).toBe(status); + expect(apiCalls()).toHaveLength(1); + expect(tokenCalls()).toHaveLength(1); + }); + + it('never re-sends an API key request', async () => { + process.env.WORKOS_API_KEY = 'sk_test_env_key'; + apiHandler = () => json({ message: 'Unauthorized' }, 401); + + const response = await apiRequest({ method: 'GET', path: '/organizations', baseUrl: API_BASE }); + + expect(response.status).toBe(401); + expect(apiCalls()).toHaveLength(1); + expect(tokenCalls()).toHaveLength(0); + }); + + it('concurrent 401s share one re-exchange', async () => { + rejectFirstToken(); + const token = await resolveApiKeyAsync(); + + await Promise.all([ + workosRequest({ method: 'GET', path: '/a', apiKey: token, baseUrl: API_BASE }), + workosRequest({ method: 'GET', path: '/b', apiKey: token, baseUrl: API_BASE }), + workosRequest({ method: 'GET', path: '/c', apiKey: token, baseUrl: API_BASE }), + ]); + + expect(tokenCalls()).toHaveLength(2); + expect(apiCalls()).toHaveLength(6); + }); + + it('a failed re-exchange exits with the WIF error, not a connection error', async () => { + const token = await resolveApiKeyAsync(); + apiHandler = () => json({ message: 'Unauthorized' }, 401); + tokenHandler = () => json({ error: 'invalid_grant', error_description: 'trust disabled' }, 400); + + for (const run of [ + () => apiRequest({ method: 'GET', path: '/organizations', apiKey: token, baseUrl: API_BASE }), + () => workosRequest({ method: 'GET', path: '/organizations', apiKey: token, baseUrl: API_BASE }), + ]) { + const exit = await expectCliExit(run()); + expect(exit.context?.errorCode).toBe('wif_invalid_grant'); + } + }); + }); + + describe('token exchange', () => { + it.each([500, 502, 503])('retries a %i with a fresh GitHub OIDC token', async (status) => { + const jwts = ['github-jwt-attempt-1', 'github-jwt-attempt-2']; + githubHandler = () => json({ value: jwts.shift() }); + const responses = [ + () => new Response('upstream down', { status }), + () => json({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 300 }), + ]; + tokenHandler = () => responses.shift()!(); + + expect(await getWifAccessToken()).toBe(ACCESS_TOKEN); + + expect(githubCalls()).toHaveLength(2); + expect(tokenCalls().map(assertionOf)).toEqual(['github-jwt-attempt-1', 'github-jwt-attempt-2']); + expect(stderr).toEqual([]); + }); + + it('retries a network error with a fresh GitHub OIDC token', async () => { + const jwts = ['github-jwt-attempt-1', 'github-jwt-attempt-2']; + githubHandler = () => json({ value: jwts.shift() }); + let attempt = 0; + tokenHandler = () => { + if (++attempt === 1) throw new TypeError('fetch failed: ECONNRESET'); + return json({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 300 }); + }; + + expect(await getWifAccessToken()).toBe(ACCESS_TOKEN); + + expect(tokenCalls().map(assertionOf)).toEqual(['github-jwt-attempt-1', 'github-jwt-attempt-2']); + }); + + it('gives up after three attempts and says so', async () => { + tokenHandler = () => json({ error: 'server_error', error_description: 'try later' }, 503); + + const exit = await expectCliExit(resolveApiKeyAsync()); + + expect(exit.context?.errorCode).toBe('wif_exchange_failed'); + expect(exit.exitCode).toBe(1); + expect(githubCalls()).toHaveLength(3); + expect(tokenCalls()).toHaveLength(3); + const message = stderr.join('\n'); + expect(message).toContain('HTTP 503'); + expect(message).toContain('Gave up after 3 attempts'); + expect(message).toContain('re-run the job'); + }); + + it('gives up after three network errors', async () => { + tokenHandler = () => { + throw new TypeError('fetch failed: ECONNREFUSED'); + }; + + await expectCliExit(resolveApiKeyAsync()); + + expect(githubCalls()).toHaveLength(3); + expect(tokenCalls()).toHaveLength(3); + expect(stderr.join('\n')).toContain('Gave up after 3 attempts'); + }); + + it.each([400, 401, 403, 404, 429])('does not retry a %i', async (status) => { + tokenHandler = () => json({ error: 'something_else' }, status); + + const exit = await expectCliExit(resolveApiKeyAsync()); + + expect(exit.context?.errorCode).toBe('wif_exchange_failed'); + expect(githubCalls()).toHaveLength(1); + expect(tokenCalls()).toHaveLength(1); + expect(stderr.join('\n')).not.toContain('attempts'); + }); + + it('stops retrying when a later attempt gets a 4xx', async () => { + const responses = [ + () => new Response('upstream down', { status: 503 }), + () => json({ error: 'invalid_grant' }, 400), + ]; + tokenHandler = () => responses.shift()!(); + + const exit = await expectCliExit(resolveApiKeyAsync()); + + expect(exit.context?.errorCode).toBe('wif_invalid_grant'); + expect(tokenCalls()).toHaveLength(2); + }); + + it('does not retry a failed GitHub OIDC request', async () => { + githubHandler = () => new Response('oops', { status: 500 }); + + await expectCliExit(resolveApiKeyAsync()); + + expect(githubCalls()).toHaveLength(1); + expect(tokenCalls()).toHaveLength(0); + }); + + it('waits between attempts, doubling each time', async () => { + setWifRetryBackoffForTests(500); // beforeEach puts it back to 0 + const waits: number[] = []; + vi.spyOn(globalThis, 'setTimeout').mockImplementation(((fn: () => void, ms?: number) => { + waits.push(ms ?? 0); + fn(); + return 0; + }) as unknown as typeof setTimeout); + tokenHandler = () => new Response('upstream down', { status: 503 }); + + await expectCliExit(resolveApiKeyAsync()); + + expect(waits).toEqual([500, 1000]); + }); + }); + }); + it('never leaks either token', async () => { // Fresh values used only here, so redaction can't lean on an earlier test // having registered them. The GitHub token is deliberately not JWT-shaped, @@ -608,6 +869,24 @@ describe('workload identity federation (wif)', () => { apiHandler = () => json({ message: 'Unauthorized' }, 401); await workosRequest({ method: 'GET', path: '/organizations', apiKey: token, baseUrl: API_BASE }); }); + // A 401 that leads to a failed re-exchange, through each request layer. + const failReExchange = (): void => { + apiHandler = () => json({ message: 'Unauthorized' }, 401); + tokenHandler = () => + json({ error: 'unauthorized_client', error_description: `no ${accessToken} for ${githubToken}` }, 400); + }; + await capture(async () => { + const token = await resolveApiKeyAsync(); + failReExchange(); + await apiRequest({ method: 'GET', path: '/organizations', apiKey: token, baseUrl: API_BASE }); + }); + tokenHandler = () => json({ access_token: accessToken, token_type: 'Bearer', expires_in: 300 }); + await capture(async () => { + const token = await resolveApiKeyAsync(); + failReExchange(); + await createWorkOSClient(token, API_BASE).sdk.organizations.listOrganizations(); + }); + expect(stderr.join('\n')).toContain('unauthorized_client'); apiHandler = () => json({ data: [], list_metadata: { before: null, after: null } }); // A later exchange fails and the server echoes both the new assertion and the access token it issued earlier. diff --git a/src/lib/wif.ts b/src/lib/wif.ts index 9005bbc2..197fab9a 100644 --- a/src/lib/wif.ts +++ b/src/lib/wif.ts @@ -14,6 +14,11 @@ * win; WIF applies only when getWifState() is 'ready'; otherwise the stored * profile key and today's errors apply unchanged. * + * Retries are bounded. An exchange that fails with a network error or a 5xx + * is retried with a fresh GitHub OIDC token each time, because WorkOS accepts + * each one once; a 4xx is never retried. An API call answered with 401 is + * re-sent once with a newly exchanged token (see sendWithWifAuth). + * * The access token is cached in memory only and never written to disk, a * profile or config. Neither the GitHub JWT nor the WorkOS access token may * appear in output, errors, logs or telemetry: both are registered with the @@ -33,6 +38,10 @@ const REFRESH_MARGIN_MAX_MS = 60_000; const REFRESH_MARGIN_FRACTION = 0.2; /** Lifetime to assume when the server omits `expires_in`: the documented minimum (5 min). */ const DEFAULT_LIFETIME_SECONDS = 300; +/** Exchange attempts in total (the first try plus retries) when the token endpoint is unreachable or answers 5xx. */ +const MAX_EXCHANGE_ATTEMPTS = 3; +/** Wait before the second attempt; doubles for each one after. */ +const DEFAULT_RETRY_BACKOFF_MS = 500; /** Cap on server-provided `error_description` text echoed into an error message. */ const MAX_DESCRIPTION_LENGTH = 500; @@ -51,11 +60,20 @@ const ID_TOKEN_PERMISSION_HINT = /** OAuth errors the token endpoint returns, with a one-line hint each. Exit code: `wif_`. */ const OAUTH_ERROR_HINTS: Record = { invalid_grant: - "The M2M application's trust rules didn't match this repository or ref, or the GitHub OIDC token expired.", - invalid_target: `The resource or audience is wrong: the trust rule's audience must match WORKOS_WIF_AUDIENCE (default ${WIF_DEFAULT_AUDIENCE}).`, - invalid_client: 'Check that WORKOS_CLIENT_ID is the client ID of the M2M application that has the GitHub trust rule.', + "None of the M2M application's trust rules matched this workflow run, or the GitHub OIDC token expired or was already used. " + + "Check the trust rule's repository, ref and audience against this run, and that the trust rule is enabled, then re-run the job.", + invalid_target: `The resource or audience is wrong. Set the trust rule's audience and WORKOS_WIF_AUDIENCE to the same value (default ${WIF_DEFAULT_AUDIENCE}).`, + invalid_client: + 'Set WORKOS_CLIENT_ID to the client ID of the M2M application that has the GitHub trust rule, ' + + 'and check that WORKOS_WIF_TOKEN_URL belongs to the same WorkOS environment as that application.', + unauthorized_client: + "This client isn't allowed to use workload identity federation. " + + 'Check that WORKOS_CLIENT_ID is an M2M application with an enabled GitHub trust rule, ' + + 'that workload identity federation is turned on for your WorkOS team, ' + + 'and that the application targets a non-production environment.', invalid_scope: - 'WORKOS_WIF_SCOPE asked for a scope the M2M application is not allowed. Fix or unset WORKOS_WIF_SCOPE.', + 'The requested scope is not one the M2M application may be granted. ' + + "Set WORKOS_WIF_SCOPE to scopes the application has, or unset it to get the application's default scopes.", invalid_request: 'The token request was malformed. Check that WORKOS_WIF_TOKEN_URL points at the /oauth2/token endpoint.', }; @@ -140,7 +158,8 @@ export function getWifAccessToken(): Promise { /** * Request headers for a REST credential. An API key passes through exactly as * before; a WIF token is refreshed if needed and gets `x-url-environment-id` - * when WORKOS_ENVIRONMENT_ID is set (machine tokens need it). + * when WORKOS_ENVIRONMENT_ID is set. The header is optional: the M2M + * application is bound to one environment, and a value that is sent must match it. */ export async function wifAuthHeaders(credential: string): Promise> { if (!isWifAccessToken(credential)) return { Authorization: `Bearer ${credential}` }; @@ -152,21 +171,57 @@ export async function wifAuthHeaders(credential: string): Promise) => Promise, +): Promise { + const authHeaders = await wifAuthHeaders(credential); + const response = await send(authHeaders); + if (response.status !== 401 || !isWifAccessToken(credential)) return response; + + discardWifAccessToken(authHeaders.Authorization.slice('Bearer '.length)); + const retryHeaders = await wifAuthHeaders(credential); + // Release the first response's connection; its body is never read. + await response.body?.cancel().catch(() => undefined); + return send(retryHeaders); +} + /** * fetch for the WorkOS SDK, which fixes its Authorization header at * construction: re-applies wifAuthHeaders() on every request so a long run - * never sends an expired token. + * never sends an expired token, and re-sends once on a 401. */ export function createWifFetch(credential: string): typeof fetch { return async (input, init) => { - const headers = new Headers(init?.headers); - for (const [name, value] of Object.entries(await wifAuthHeaders(credential))) { - headers.set(name, value); - } - return fetch(input, { ...init, headers }); + // A Request or a stream body can be consumed only once, so those are not re-sent. + const replayable = + !(input instanceof Request) && + (init?.body == null || typeof init.body === 'string' || init.body instanceof URLSearchParams); + const send = (authHeaders: Record): Promise => { + const headers = new Headers(init?.headers); + for (const [name, value] of Object.entries(authHeaders)) headers.set(name, value); + return fetch(input, { ...init, headers }); + }; + return replayable ? sendWithWifAuth(credential, send) : send(await wifAuthHeaders(credential)); }; } +let retryBackoffMs = DEFAULT_RETRY_BACKOFF_MS; + /** Test-only: forget cached and issued tokens. */ export function resetWifCacheForTests(): void { cached = undefined; @@ -174,9 +229,14 @@ export function resetWifCacheForTests(): void { issuedTokens.clear(); } +/** Test-only: shorten the wait between exchange attempts. */ +export function setWifRetryBackoffForTests(ms: number): void { + retryBackoffMs = ms; +} + function resolveTokenUrl(): string { const raw = process.env.WORKOS_WIF_TOKEN_URL; - // No default yet: the WorkOS side of this grant (`management-api-oauth`) is + // No default yet: the WorkOS side of this grant (`workos-api-workload-identity`) is // still being built and has no production endpoint. The default will come // once the server ships. if (!raw) { @@ -288,12 +348,36 @@ async function requestGitHubIdToken(audience: string): Promise { return value; } +/** A failed attempt that is worth repeating: `fail` reports it if no attempt is left. */ +interface RetryableFailure { + fail: (attempts: number) => never; +} + +function attemptsSuffix(attempts: number): string { + return attempts > 1 ? ` Gave up after ${attempts} attempts.` : ''; +} + +/** + * Exchange with bounded retries. Only a network error or a 5xx from the token + * endpoint is retried; every 4xx (and any GitHub-side failure) exits at once. + */ async function exchangeForAccessToken(): Promise { // Fail on configuration before any network call. const tokenUrl = resolveTokenUrl(); const audience = process.env.WORKOS_WIF_AUDIENCE || WIF_DEFAULT_AUDIENCE; - const assertion = await requestGitHubIdToken(audience); + for (let attempt = 1; ; attempt++) { + // A fresh GitHub OIDC token for every attempt: WorkOS accepts each one + // once, and a failed attempt may already have consumed it. + const assertion = await requestGitHubIdToken(audience); + const result = await attemptExchange(tokenUrl, assertion); + if ('value' in result) return result; + if (attempt >= MAX_EXCHANGE_ATTEMPTS) result.fail(attempt); + await new Promise((resolve) => setTimeout(resolve, retryBackoffMs * 2 ** (attempt - 1))); + } +} + +async function attemptExchange(tokenUrl: string, assertion: string): Promise { const form = new URLSearchParams({ grant_type: WIF_GRANT_TYPE, assertion, @@ -313,10 +397,16 @@ async function exchangeForAccessToken(): Promise { body: form.toString(), }); } catch (error) { - exitWithError({ - code: WIF_ERROR_CODES.exchangeFailed, - message: `Could not reach WORKOS_WIF_TOKEN_URL for the WIF token exchange: ${describeNetworkError(error)}`, - }); + const detail = describeNetworkError(error); + return { + fail: (attempts) => + exitWithError({ + code: WIF_ERROR_CODES.exchangeFailed, + message: + `Could not reach WORKOS_WIF_TOKEN_URL for the WIF token exchange: ${detail}.${attemptsSuffix(attempts)} ` + + 'Check that WORKOS_WIF_TOKEN_URL is right and reachable from this runner, then re-run the job.', + }), + }; } const body = await readJsonObject(response); @@ -325,12 +415,30 @@ async function exchangeForAccessToken(): Promise { typeof body?.error_description === 'string' && body.error_description ? redactRegisteredSecrets(body.error_description).slice(0, MAX_DESCRIPTION_LENGTH) : undefined; + const status = response.status; + + if (status >= 500) { + let reason: string; + if (!body) reason = 'the response was not JSON'; + else if (oauthError) reason = `${oauthError}${description ? `: ${description}` : ''}`; + else reason = 'unexpected error response'; + return { + fail: (attempts) => + exitWithError({ + code: WIF_ERROR_CODES.exchangeFailed, + message: + `WIF token exchange at WORKOS_WIF_TOKEN_URL failed (HTTP ${status}): ${reason}.${attemptsSuffix(attempts)} ` + + 'This is a server-side failure; re-run the job, and check WORKOS_WIF_TOKEN_URL if it keeps happening.', + apiContext: { status }, + }), + }; + } if (oauthError && Object.hasOwn(OAUTH_ERROR_HINTS, oauthError)) { exitWithError({ code: `wif_${oauthError}`, message: `WorkOS rejected the WIF token exchange with ${oauthError}${description ? `: ${description}` : ''}. ${OAUTH_ERROR_HINTS[oauthError]}`, - apiContext: { status: response.status, code: oauthError }, + apiContext: { status, code: oauthError }, }); } @@ -343,8 +451,8 @@ async function exchangeForAccessToken(): Promise { else reason = 'the response had no access_token'; exitWithError({ code: WIF_ERROR_CODES.exchangeFailed, - message: `WIF token exchange at WORKOS_WIF_TOKEN_URL failed (HTTP ${response.status}): ${reason}.`, - apiContext: { status: response.status }, + message: `WIF token exchange at WORKOS_WIF_TOKEN_URL failed (HTTP ${status}): ${reason}. Check that WORKOS_WIF_TOKEN_URL is the /oauth2/token endpoint of your WorkOS environment.`, + apiContext: { status }, }); } registerSecret(accessToken); diff --git a/src/lib/workos-api.ts b/src/lib/workos-api.ts index 3e7d355c..8abcd7c0 100644 --- a/src/lib/workos-api.ts +++ b/src/lib/workos-api.ts @@ -3,7 +3,8 @@ * Thin fetch wrapper with auth, error parsing, and query param support. */ -import { wifAuthHeaders } from './wif.js'; +import { sendWithWifAuth } from './wif.js'; +import { CliExit } from '../utils/cli-exit.js'; const DEFAULT_BASE_URL = 'https://api.workos.com'; @@ -51,11 +52,9 @@ export async function workosRequest(options: WorkOSRequestOptions): Promise`; a WIF token is refreshed if - // needed and carries x-url-environment-id when configured. - const headers: Record = await wifAuthHeaders(apiKey); + const headers: Record = {}; - const fetchOptions: RequestInit = { method, headers }; + const fetchOptions: RequestInit = { method }; if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) { headers['Content-Type'] = 'application/json'; @@ -64,8 +63,15 @@ export async function workosRequest(options: WorkOSRequestOptions): Promise`; a WIF token is refreshed if + // needed, carries x-url-environment-id when configured, and is exchanged + // again once if the API answers 401. + response = await sendWithWifAuth(apiKey, (authHeaders) => + fetch(url, { ...fetchOptions, headers: { ...authHeaders, ...headers } }), + ); + } catch (error) { + // A failed WIF exchange has already reported its own error. + if (error instanceof CliExit) throw error; throw new WorkOSApiError('Failed to connect to WorkOS API. Check your internet connection.', 0); } diff --git a/src/utils/exit-codes.ts b/src/utils/exit-codes.ts index a6ab7baf..ffc9883a 100644 --- a/src/utils/exit-codes.ts +++ b/src/utils/exit-codes.ts @@ -38,6 +38,7 @@ const ERROR_CODE_MAP: Record Date: Wed, 11 Nov 2026 18:25:46 -0800 Subject: [PATCH 3/6] docs(wif): document retries, unauthorized_client and the optional environment ID --- README.md | 6 +- .../.github/workflows/wif-test.yml | 5 +- examples/wif-github-actions/README.md | 56 +++++++++++-------- src/commands/debug.ts | 3 +- src/lib/workos-client.ts | 2 +- 5 files changed, 43 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 0e35937a..130c38cf 100644 --- a/README.md +++ b/README.md @@ -313,9 +313,9 @@ The remaining commands (`connection`, `directory`, `audit-log`, `api-key`, `vaul #### GitHub Actions without an API key (workload identity federation) -> Preview: the WorkOS server side is still being built (behind the `management-api-oauth` flag) and has no production endpoint yet. +> Preview: the WorkOS server side is still being built (behind the `workos-api-workload-identity` and `management-api-oauth` flags) and has no production endpoint yet. -In a GitHub Actions job with `permissions: id-token: write`, `WORKOS_CLIENT_ID` set to an M2M application's client ID, and no `WORKOS_API_KEY`, the REST commands above (plus `seed`, `setup-org`, `onboard-user`, `debug-sso`, `debug-sync`) exchange the job's GitHub OIDC token at `WORKOS_WIF_TOKEN_URL` for a short-lived WorkOS access token. The token is held in memory only and refreshed before it expires. `verify-login` refuses WIF tokens because it can't confirm the environment isn't production, and `migrations` ignores WIF. See [`examples/wif-github-actions`](examples/wif-github-actions/) for a workflow and setup guide. +In a GitHub Actions job with `permissions: id-token: write`, `WORKOS_CLIENT_ID` set to an M2M application's client ID, and no `WORKOS_API_KEY`, the REST commands above (plus `seed`, `setup-org`, `onboard-user`, `debug-sso`, `debug-sync`) exchange the job's GitHub OIDC token at `WORKOS_WIF_TOKEN_URL` for a short-lived WorkOS access token. The token is held in memory only and refreshed before it expires. A token exchange that hits a network error or a 5xx is retried up to three times in total, each with a fresh GitHub OIDC token, and an API call answered with 401 is re-sent once with a newly exchanged token. `verify-login` refuses WIF tokens because it can't confirm the environment isn't production, and `migrations` ignores WIF. See [`examples/wif-github-actions`](examples/wif-github-actions/) for a workflow and setup guide. #### organization @@ -696,7 +696,7 @@ workos install --api-key sk_test_xxx --client-id client_xxx 2>/dev/null | `WORKOS_WIF_TOKEN_URL` | Workload identity federation token endpoint (`https:///oauth2/token`). Required for WIF; no default until the server side ships | | `WORKOS_WIF_AUDIENCE` | Audience requested for the GitHub OIDC token (default `https://api.workos.com`); must match the M2M application's trust rule | | `WORKOS_WIF_SCOPE` | Optional `scope` sent with the WIF token exchange | -| `WORKOS_ENVIRONMENT_ID` | Sent as `x-url-environment-id` with WIF access tokens; machine tokens need it | +| `WORKOS_ENVIRONMENT_ID` | Optional. Sent as `x-url-environment-id` with WIF access tokens; when set it must be the environment the M2M application is bound to | | `WORKOS_API_URL` | Override the API base URL for all CLI commands (e.g. a local API) | | `WORKOS_API_BASE_URL` | Accepted alias for `WORKOS_API_URL` (what `workos dev` sets) | | `WORKOS_MODE` | Interaction mode: `human`, `agent`, or `ci` | diff --git a/examples/wif-github-actions/.github/workflows/wif-test.yml b/examples/wif-github-actions/.github/workflows/wif-test.yml index 6bf3708f..522ca2fb 100644 --- a/examples/wif-github-actions/.github/workflows/wif-test.yml +++ b/examples/wif-github-actions/.github/workflows/wif-test.yml @@ -2,8 +2,9 @@ # workload identity federation (WIF): the job's GitHub OIDC token is exchanged # for a short-lived WorkOS access token. See ../../README.md for setup. # -# The WorkOS server side (the `management-api-oauth` flag) is not deployed -# yet, so this only works against an environment where it has been enabled. +# The WorkOS server side (the `workos-api-workload-identity` and +# `management-api-oauth` flags) is not deployed yet, so this only works for a +# team where it has been enabled. name: WorkOS WIF test diff --git a/examples/wif-github-actions/README.md b/examples/wif-github-actions/README.md index acfb92b2..38cf33fe 100644 --- a/examples/wif-github-actions/README.md +++ b/examples/wif-github-actions/README.md @@ -2,7 +2,7 @@ This example calls the WorkOS API from a GitHub Actions workflow with **no `WORKOS_API_KEY`**. The job asks GitHub for an OIDC ID token, exchanges it at WorkOS for a short-lived access token (the OAuth `urn:ietf:params:oauth:grant-type:jwt-bearer` grant), and uses that token as the Bearer for API calls. -> **The server side isn't deployed yet.** The WorkOS token endpoint for this grant is still being built, behind the `management-api-oauth` feature flag, and there is no production endpoint. This example only works against an environment where that flag is on, with `WORKOS_WIF_TOKEN_URL` pointing at its token endpoint. +> **The server side isn't deployed yet.** The WorkOS token endpoint for this grant is still being built, behind the `workos-api-workload-identity` and `management-api-oauth` team feature flags, and there is no production endpoint. This example only works for a team that has those flags on, with `WORKOS_WIF_TOKEN_URL` pointing at its token endpoint. [`.github/workflows/wif-test.yml`](.github/workflows/wif-test.yml) has two jobs that do the same thing: @@ -29,12 +29,12 @@ The workflow runs only when you start it (`workflow_dispatch`). It needs `permis Under **Settings → Secrets and variables → Actions → Variables**, add these as **variables**, not secrets. None of them is a credential: -| Variable | Value | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| `WORKOS_CLIENT_ID` | Client ID of the M2M application from step 3 | -| `WORKOS_WIF_TOKEN_URL` | The token endpoint, shaped like `https:///oauth2/token` | -| `WORKOS_API_URL` | WorkOS API base URL. Leave it unset for `https://api.workos.com` | -| `WORKOS_ENVIRONMENT_ID` | The environment the M2M application belongs to (`environment_...`), sent as the `x-url-environment-id` header. Machine tokens need it | +| Variable | Value | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `WORKOS_CLIENT_ID` | Client ID of the M2M application from step 3 | +| `WORKOS_WIF_TOKEN_URL` | The token endpoint, shaped like `https:///oauth2/token` | +| `WORKOS_API_URL` | WorkOS API base URL. Leave it unset for `https://api.workos.com` | +| `WORKOS_ENVIRONMENT_ID` | Optional. The M2M application is bound to one environment and its tokens act on that environment. When set (`environment_...`), the value is sent as the `x-url-environment-id` header and must be that same environment | The CLI also reads `WORKOS_WIF_AUDIENCE` (default `https://api.workos.com`) and `WORKOS_WIF_SCOPE` (optional, sent as `scope` only when set). The workflow pins the audience to the default. @@ -42,8 +42,8 @@ The CLI also reads `WORKOS_WIF_AUDIENCE` (default `https://api.workos.com`) and In the WorkOS environment you're testing against: -1. Make sure the **`management-api-oauth`** feature flag is on for the environment. Without it the token endpoint rejects the grant. -2. Create an M2M application. Its client ID is `WORKOS_CLIENT_ID`. +1. Make sure the **`workos-api-workload-identity`** and **`management-api-oauth`** feature flags are on for the team. Without them the token endpoint rejects the grant with `unauthorized_client`. +2. Create an M2M application bound to the environment you want the workflow to act on. Its client ID is `WORKOS_CLIENT_ID`. Production environments are refused for now, so use a sandbox or staging environment. 3. Add a GitHub trust rule to the application: - **Issuer:** `https://token.actions.githubusercontent.com` - **Audience:** `https://api.workos.com`. It must match the `audience` the job requests (`WORKOS_WIF_AUDIENCE`). @@ -69,18 +69,30 @@ Both jobs go green. Both new organizations show up in the WorkOS dashboard for that environment. Delete them when you're done. +## Retries + +The CLI retries on its own, within limits: + +- **Token exchange:** if the token endpoint can't be reached or answers 5xx, the CLI tries up to three times in total, waiting 0.5 s and then 1 s. Each attempt requests a new GitHub OIDC token, because WorkOS accepts each one only once. A 4xx answer (`invalid_grant`, `invalid_client`, ...) is never retried: fix the configuration and re-run. +- **API calls:** the access token is exchanged again shortly before it expires. If the API still answers 401, the CLI exchanges once more and re-sends that request once. A second 401 is reported as is. + +The `curl` job does not retry. + ## Common errors -| Symptom | Fix | -| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `No OIDC token available` / CLI `wif_id_token_unavailable` | Add `permissions: id-token: write` to the workflow or job. | -| CLI `wif_token_url_missing` | Set the `WORKOS_WIF_TOKEN_URL` variable. There is no default until the server side ships. | -| `invalid_grant` | The trust rule didn't match: check the issuer, the `repository_id` value, and that the run's `ref` (branch) matches the rule. The GitHub token may also have expired. | -| `invalid_client` | `WORKOS_CLIENT_ID` isn't the M2M application with the trust rule, or that application is in another environment. | -| `invalid_target` | Resource or audience mismatch. The trust rule's audience must be `https://api.workos.com`, the same as `WORKOS_WIF_AUDIENCE`. | -| `invalid_scope` | `WORKOS_WIF_SCOPE` asks for a scope the application isn't allowed. Fix or unset it. | -| `invalid_request` | Malformed request, often a `WORKOS_WIF_TOKEN_URL` that isn't the `/oauth2/token` endpoint. | -| Token exchange fails with HTTP 404, or the response is not JSON | `WORKOS_WIF_TOKEN_URL` is wrong, or the `management-api-oauth` flag is off for the environment. | -| The API returns 401 or 403 after a successful exchange | Set `WORKOS_ENVIRONMENT_ID` to the M2M application's environment, and check `WORKOS_API_URL` points at the same deployment that issued the token. | -| The CLI job uses an API key instead of WIF | `WORKOS_API_KEY` (or `--api-key`) always wins. Remove it from the job's environment. | -| CLI `wif_unsupported_command` | That command can't use WIF (for example `workos verify-login`, which won't create users when it can't confirm the environment isn't production). Use a sandbox `WORKOS_API_KEY` for that step. `workos migrations` ignores WIF entirely. | +| Symptom | Fix | +| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `No OIDC token available` / CLI `wif_id_token_unavailable` | Add `permissions: id-token: write` to the workflow or job. | +| CLI `wif_token_url_missing` | Set the `WORKOS_WIF_TOKEN_URL` variable. There is no default until the server side ships. | +| `invalid_grant` | No trust rule matched: check the issuer, the `repository_id` value, the audience, that the run's `ref` (branch) matches the rule, and that the rule is enabled. The GitHub token may also have expired or been used already; re-run the job. | +| `invalid_client` | `WORKOS_CLIENT_ID` isn't the M2M application with the trust rule, or `WORKOS_WIF_TOKEN_URL` belongs to a different WorkOS environment than that application. | +| `unauthorized_client` | The client can't use workload identity federation. Check that it is an M2M application with an enabled GitHub trust rule, that the feature flags from step 3 are on for the team, and that the application targets a non-production environment. | +| `invalid_target` | Resource or audience mismatch. The trust rule's audience must be `https://api.workos.com`, the same as `WORKOS_WIF_AUDIENCE`. | +| `invalid_scope` | `WORKOS_WIF_SCOPE` asks for a scope the application may not be granted. Set it to scopes the application has, or unset it to get the application's default scopes. | +| `invalid_request` | Malformed request, often a `WORKOS_WIF_TOKEN_URL` that isn't the `/oauth2/token` endpoint. | +| Token exchange fails with HTTP 404, or the response is not JSON | `WORKOS_WIF_TOKEN_URL` is wrong. It must be the `/oauth2/token` endpoint of your WorkOS environment. | +| CLI `wif_exchange_failed` ending in `Gave up after 3 attempts` | The token endpoint was unreachable or answered 5xx three times in a row. Re-run the job, and check `WORKOS_WIF_TOKEN_URL` if it keeps happening. | +| The API returns 401 after a successful exchange | The CLI already exchanged again and re-sent the request once. Check that `WORKOS_API_URL` points at the same deployment that issued the token, and that `WORKOS_ENVIRONMENT_ID`, if set, is the environment the M2M application is bound to (or unset it). | +| The API returns 403 after a successful exchange | The token doesn't carry the scope that endpoint needs. Grant the scope to the M2M application, and include it in `WORKOS_WIF_SCOPE` if you set that variable. | +| The CLI job uses an API key instead of WIF | `WORKOS_API_KEY` (or `--api-key`) always wins. Remove it from the job's environment. | +| CLI `wif_unsupported_command` | That command can't use WIF (for example `workos verify-login`, which won't create users when it can't confirm the environment isn't production). Use a sandbox `WORKOS_API_KEY` for that step. `workos migrations` ignores WIF entirely. | diff --git a/src/commands/debug.ts b/src/commands/debug.ts index 97bade3d..1f2242cd 100644 --- a/src/commands/debug.ts +++ b/src/commands/debug.ts @@ -397,7 +397,8 @@ export const ENV_VAR_CATALOG: { name: string; effect: string }[] = [ { name: 'WORKOS_WIF_SCOPE', effect: 'Optional scope sent with the WIF token exchange' }, { name: 'WORKOS_ENVIRONMENT_ID', - effect: 'Environment ID sent as x-url-environment-id with WIF access tokens (machine tokens need it)', + effect: + 'Optional environment ID sent as x-url-environment-id with WIF access tokens (must match the M2M application)', }, // Interaction & output { name: 'WORKOS_MODE', effect: 'Controls interaction behavior: human, agent, or CI' }, diff --git a/src/lib/workos-client.ts b/src/lib/workos-client.ts index 6457b7dd..2e722442 100644 --- a/src/lib/workos-client.ts +++ b/src/lib/workos-client.ts @@ -107,7 +107,7 @@ export function createWorkOSClient(apiKey?: string, baseUrl?: string): WorkOSCLI apiHostname: url.hostname, ...(url.port && { port: Number(url.port) }), ...(url.protocol === 'http:' && { https: false }), - // A WIF token is short-lived and needs x-url-environment-id: re-apply + // A WIF token is short-lived and may carry x-url-environment-id: re-apply // both on every SDK request instead of the headers fixed at construction. ...(isWifAccessToken(key) && { fetchFn: createWifFetch(key) }), }); From aeaa5add99493993403c590391c79fc8e53da542 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Thu, 12 Nov 2026 14:03:09 -0800 Subject: [PATCH 4/6] fix(wif): retry a dropped response body and release a rejected response before re-exchanging A connection that dropped while the token response body was read ended the exchange as 'the response was not JSON' instead of being retried like any other network failure. A 401 response was cancelled only after the re-exchange, so a failed re-exchange left it open. --- src/lib/wif.spec.ts | 31 +++++++++++++++++++++++++++++++ src/lib/wif.ts | 14 +++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/lib/wif.spec.ts b/src/lib/wif.spec.ts index cc4640d2..c3c65f12 100644 --- a/src/lib/wif.spec.ts +++ b/src/lib/wif.spec.ts @@ -631,6 +631,21 @@ describe('workload identity federation (wif)', () => { expect(tokenCalls()).toHaveLength(2); }); + it('releases the rejected response even when the re-exchange fails', async () => { + const rejected = json({ message: 'Unauthorized' }, 401); + const cancel = vi.spyOn(rejected.body!, 'cancel'); + apiHandler = () => rejected; + let exchanges = 0; + tokenHandler = () => + ++exchanges === 1 + ? json({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 300 }) + : json({ error: 'unauthorized_client' }, 400); + + await expectCliExit(apiRequest({ method: 'GET', path: '/organizations', baseUrl: API_BASE })); + + expect(cancel).toHaveBeenCalled(); + }); + it('a second 401 is returned, with no third request and no third exchange', async () => { apiHandler = () => json({ message: 'Unauthorized' }, 401); @@ -722,6 +737,22 @@ describe('workload identity federation (wif)', () => { expect(tokenCalls().map(assertionOf)).toEqual(['github-jwt-attempt-1', 'github-jwt-attempt-2']); }); + it('retries when the connection drops while the response body is read', async () => { + const jwts = ['github-jwt-attempt-1', 'github-jwt-attempt-2']; + githubHandler = () => json({ value: jwts.shift() }); + let attempt = 0; + tokenHandler = () => { + if (++attempt > 1) return json({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 300 }); + const dropped = new Response(null, { status: 200 }); + dropped.text = () => Promise.reject(new TypeError('terminated')); + return dropped; + }; + + expect(await getWifAccessToken()).toBe(ACCESS_TOKEN); + + expect(tokenCalls().map(assertionOf)).toEqual(['github-jwt-attempt-1', 'github-jwt-attempt-2']); + }); + it('gives up after three attempts and says so', async () => { tokenHandler = () => json({ error: 'server_error', error_description: 'try later' }, 503); diff --git a/src/lib/wif.ts b/src/lib/wif.ts index 197fab9a..5ed2c0e6 100644 --- a/src/lib/wif.ts +++ b/src/lib/wif.ts @@ -194,9 +194,10 @@ export async function sendWithWifAuth( if (response.status !== 401 || !isWifAccessToken(credential)) return response; discardWifAccessToken(authHeaders.Authorization.slice('Bearer '.length)); - const retryHeaders = await wifAuthHeaders(credential); - // Release the first response's connection; its body is never read. + // Release the first response's connection before exchanging again, so a + // failed exchange does not leave it open. Its body is never read. await response.body?.cancel().catch(() => undefined); + const retryHeaders = await wifAuthHeaders(credential); return send(retryHeaders); } @@ -280,6 +281,10 @@ async function readJsonObject(response: Response): Promise | undefined { try { const parsed: unknown = JSON.parse(text); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) @@ -390,12 +395,15 @@ async function attemptExchange(tokenUrl: string, assertion: string): Promise Date: Sat, 14 Nov 2026 00:54:44 -0600 Subject: [PATCH 5/6] fix(wif): say the WorkOS access token lasts one hour The exchange now issues one-hour tokens. The comment on the fallback lifetime called five minutes the documented minimum. The fallback stays at 300 seconds, used only when the server omits expires_in, so the CLI exchanges again early. --- src/lib/wif.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/lib/wif.ts b/src/lib/wif.ts index 5ed2c0e6..b24bda7c 100644 --- a/src/lib/wif.ts +++ b/src/lib/wif.ts @@ -36,7 +36,11 @@ export const ENVIRONMENT_ID_HEADER = 'x-url-environment-id'; /** Refresh once less than this much lifetime is left, or less than 20% of it, whichever is smaller. */ const REFRESH_MARGIN_MAX_MS = 60_000; const REFRESH_MARGIN_FRACTION = 0.2; -/** Lifetime to assume when the server omits `expires_in`: the documented minimum (5 min). */ +/** + * Lifetime to assume when the server omits `expires_in`. WorkOS access tokens last one hour and the + * server says so in `expires_in`; this fallback is deliberately shorter, so the CLI exchanges again + * early instead of sending a token that may have expired. + */ const DEFAULT_LIFETIME_SECONDS = 300; /** Exchange attempts in total (the first try plus retries) when the token endpoint is unreachable or answers 5xx. */ const MAX_EXCHANGE_ATTEMPTS = 3; From b87625723b17c76c879c27797bc3805c00823784 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Tue, 17 Nov 2026 17:40:41 -0600 Subject: [PATCH 6/6] fix(wif): match the server in error hints, keep a stored key when WIF has no endpoint, and time out stalled requests - Hints no longer name an enabled switch or a per-trust audience, which the server does not have, and invalid_client mentions expired trust rules. - A job with a stored profile key and no WORKOS_WIF_TOKEN_URL keeps using the stored key. - The GitHub token request and each exchange attempt time out after 15 s. - A 401 or 403 with a WIF token says the token was refused instead of calling the API key invalid. - verify-login no longer exchanges a token it then refuses. --- README.md | 4 +- examples/wif-github-actions/README.md | 37 ++++++++-------- src/bin.ts | 1 - src/commands/api/index.spec.ts | 39 +++++++++++++++++ src/commands/api/index.ts | 15 +++++-- src/lib/api-error-handler.spec.ts | 23 ++++++++++ src/lib/api-error-handler.ts | 11 +++++ src/lib/api-key.spec.ts | 12 +++++ src/lib/api-key.ts | 17 ++++++-- src/lib/wif.spec.ts | 63 ++++++++++++++++++++++----- src/lib/wif.ts | 20 +++++++-- 11 files changed, 200 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 130c38cf..df496492 100644 --- a/README.md +++ b/README.md @@ -315,7 +315,7 @@ The remaining commands (`connection`, `directory`, `audit-log`, `api-key`, `vaul > Preview: the WorkOS server side is still being built (behind the `workos-api-workload-identity` and `management-api-oauth` flags) and has no production endpoint yet. -In a GitHub Actions job with `permissions: id-token: write`, `WORKOS_CLIENT_ID` set to an M2M application's client ID, and no `WORKOS_API_KEY`, the REST commands above (plus `seed`, `setup-org`, `onboard-user`, `debug-sso`, `debug-sync`) exchange the job's GitHub OIDC token at `WORKOS_WIF_TOKEN_URL` for a short-lived WorkOS access token. The token is held in memory only and refreshed before it expires. A token exchange that hits a network error or a 5xx is retried up to three times in total, each with a fresh GitHub OIDC token, and an API call answered with 401 is re-sent once with a newly exchanged token. `verify-login` refuses WIF tokens because it can't confirm the environment isn't production, and `migrations` ignores WIF. See [`examples/wif-github-actions`](examples/wif-github-actions/) for a workflow and setup guide. +In a GitHub Actions job with `permissions: id-token: write`, `WORKOS_CLIENT_ID` set to an M2M application's client ID, and no `WORKOS_API_KEY`, the REST commands above (plus `seed`, `setup-org`, `onboard-user`, `debug-sso`, `debug-sync`) exchange the job's GitHub OIDC token at `WORKOS_WIF_TOKEN_URL` for a short-lived WorkOS access token. What that token may do is decided by the server and by the scopes the M2M application holds. Today the server offers scopes for reading and creating organizations and for reading connections, directories, users and events. A command that needs anything else (for example `api-key`, `vault` or `audit-log`) is refused by the API, and the CLI says that the WIF token was refused. A job that has a stored profile key and no `WORKOS_WIF_TOKEN_URL` keeps using the stored key. The token is held in memory only and refreshed before it expires. A token exchange that hits a network error or a 5xx is retried up to three times in total, each with a fresh GitHub OIDC token, and an API call answered with 401 is re-sent once with a newly exchanged token. `verify-login` does not use WIF, because it can't confirm the environment isn't production, and `migrations` ignores WIF. See [`examples/wif-github-actions`](examples/wif-github-actions/) for a workflow and setup guide. #### organization @@ -694,7 +694,7 @@ workos install --api-key sk_test_xxx --client-id client_xxx 2>/dev/null | `WORKOS_API_KEY` | API key for `workos api`, the still-REST commands (connection, directory, audit-log, api-key, vault), and workflow/debug commands. Resource commands use the `workos auth login` session instead | | `WORKOS_CLIENT_ID` | In GitHub Actions with no API key: the M2M application's client ID, which turns on workload identity federation for the REST commands | | `WORKOS_WIF_TOKEN_URL` | Workload identity federation token endpoint (`https:///oauth2/token`). Required for WIF; no default until the server side ships | -| `WORKOS_WIF_AUDIENCE` | Audience requested for the GitHub OIDC token (default `https://api.workos.com`); must match the M2M application's trust rule | +| `WORKOS_WIF_AUDIENCE` | Audience requested for the GitHub OIDC token (default `https://api.workos.com`); must be the M2M application's audience | | `WORKOS_WIF_SCOPE` | Optional `scope` sent with the WIF token exchange | | `WORKOS_ENVIRONMENT_ID` | Optional. Sent as `x-url-environment-id` with WIF access tokens; when set it must be the environment the M2M application is bound to | | `WORKOS_API_URL` | Override the API base URL for all CLI commands (e.g. a local API) | diff --git a/examples/wif-github-actions/README.md b/examples/wif-github-actions/README.md index 38cf33fe..eb685a4f 100644 --- a/examples/wif-github-actions/README.md +++ b/examples/wif-github-actions/README.md @@ -9,7 +9,7 @@ This example calls the WorkOS API from a GitHub Actions workflow with **no `WORK - **`curl`**: plain bash and curl. It requests the OIDC token, does the exchange, runs `GET /organizations`, creates an organization with `POST /organizations` named `wif-test-`, and checks that the new organization is listed. - **`cli`**: the same through the `workos` CLI (`workos api ...`). The CLI does the exchange itself when it runs in GitHub Actions with `WORKOS_CLIENT_ID` set and no API key. It names its organization `wif-test--cli`. -Neither job prints a token. Both tokens are masked with `::add-mask::`, nothing uses `set -x`, and the curl job keeps the access token in shell memory instead of writing it to `GITHUB_ENV`. +Neither job prints a token. The curl job masks both tokens with `::add-mask::`, uses no `set -x`, and keeps the access token in shell memory instead of writing it to `GITHUB_ENV`. The CLI job never has the tokens in the shell: the CLI holds them in memory and redacts them from its own output. ## 1. Create a test repository @@ -43,10 +43,9 @@ The CLI also reads `WORKOS_WIF_AUDIENCE` (default `https://api.workos.com`) and In the WorkOS environment you're testing against: 1. Make sure the **`workos-api-workload-identity`** and **`management-api-oauth`** feature flags are on for the team. Without them the token endpoint rejects the grant with `unauthorized_client`. -2. Create an M2M application bound to the environment you want the workflow to act on. Its client ID is `WORKOS_CLIENT_ID`. Production environments are refused for now, so use a sandbox or staging environment. +2. Create an M2M application bound to the environment you want the workflow to act on, with the audience `https://api.workos.com`. Its client ID is `WORKOS_CLIENT_ID`, and its audience must be the `audience` the job requests (`WORKOS_WIF_AUDIENCE`). Production environments are refused for now, so use a sandbox or staging environment. 3. Add a GitHub trust rule to the application: - **Issuer:** `https://token.actions.githubusercontent.com` - - **Audience:** `https://api.workos.com`. It must match the `audience` the job requests (`WORKOS_WIF_AUDIENCE`). - **Claims:** `repository_id` set to your test repository's numeric ID, and `ref` set to the branch you'll run from, such as `refs/heads/main`. To find the repository ID, run `gh api repos// --jq .id`. Use `repository_id` rather than the repository name, because the name can be renamed or reused. @@ -80,19 +79,19 @@ The `curl` job does not retry. ## Common errors -| Symptom | Fix | -| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `No OIDC token available` / CLI `wif_id_token_unavailable` | Add `permissions: id-token: write` to the workflow or job. | -| CLI `wif_token_url_missing` | Set the `WORKOS_WIF_TOKEN_URL` variable. There is no default until the server side ships. | -| `invalid_grant` | No trust rule matched: check the issuer, the `repository_id` value, the audience, that the run's `ref` (branch) matches the rule, and that the rule is enabled. The GitHub token may also have expired or been used already; re-run the job. | -| `invalid_client` | `WORKOS_CLIENT_ID` isn't the M2M application with the trust rule, or `WORKOS_WIF_TOKEN_URL` belongs to a different WorkOS environment than that application. | -| `unauthorized_client` | The client can't use workload identity federation. Check that it is an M2M application with an enabled GitHub trust rule, that the feature flags from step 3 are on for the team, and that the application targets a non-production environment. | -| `invalid_target` | Resource or audience mismatch. The trust rule's audience must be `https://api.workos.com`, the same as `WORKOS_WIF_AUDIENCE`. | -| `invalid_scope` | `WORKOS_WIF_SCOPE` asks for a scope the application may not be granted. Set it to scopes the application has, or unset it to get the application's default scopes. | -| `invalid_request` | Malformed request, often a `WORKOS_WIF_TOKEN_URL` that isn't the `/oauth2/token` endpoint. | -| Token exchange fails with HTTP 404, or the response is not JSON | `WORKOS_WIF_TOKEN_URL` is wrong. It must be the `/oauth2/token` endpoint of your WorkOS environment. | -| CLI `wif_exchange_failed` ending in `Gave up after 3 attempts` | The token endpoint was unreachable or answered 5xx three times in a row. Re-run the job, and check `WORKOS_WIF_TOKEN_URL` if it keeps happening. | -| The API returns 401 after a successful exchange | The CLI already exchanged again and re-sent the request once. Check that `WORKOS_API_URL` points at the same deployment that issued the token, and that `WORKOS_ENVIRONMENT_ID`, if set, is the environment the M2M application is bound to (or unset it). | -| The API returns 403 after a successful exchange | The token doesn't carry the scope that endpoint needs. Grant the scope to the M2M application, and include it in `WORKOS_WIF_SCOPE` if you set that variable. | -| The CLI job uses an API key instead of WIF | `WORKOS_API_KEY` (or `--api-key`) always wins. Remove it from the job's environment. | -| CLI `wif_unsupported_command` | That command can't use WIF (for example `workos verify-login`, which won't create users when it can't confirm the environment isn't production). Use a sandbox `WORKOS_API_KEY` for that step. `workos migrations` ignores WIF entirely. | +| Symptom | Fix | +| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `No OIDC token available` / CLI `wif_id_token_unavailable` | Add `permissions: id-token: write` to the workflow or job. | +| CLI `wif_token_url_missing` | Set the `WORKOS_WIF_TOKEN_URL` variable. There is no default until the server side ships. | +| `invalid_grant` | No trust rule matched: check the `repository_id` value, that the run's `ref` (branch) matches the rule, that the rule has not expired, and that `WORKOS_WIF_AUDIENCE` is the application's audience. The GitHub token may also have expired or been used already; re-run the job. | +| `invalid_client` | `WORKOS_CLIENT_ID` isn't the M2M application with the trust rule, or `WORKOS_WIF_TOKEN_URL` belongs to a different WorkOS environment than that application. If the message asks for a client secret, the application's trust rules have all expired or been removed: add one. | +| `unauthorized_client` | The client can't use workload identity federation. Check that it is an M2M application with a GitHub trust rule that has not expired, that the feature flags from step 3 are on for the team, and that the application targets a non-production environment. | +| `invalid_target` | The resource is not one this token endpoint issues tokens for. Check that `WORKOS_WIF_TOKEN_URL` is the endpoint for the WorkOS API. | +| `invalid_scope` | `WORKOS_WIF_SCOPE` asks for a scope the application may not be granted. Set it to scopes the application has, or unset it to get the application's default scopes. | +| `invalid_request` | Malformed request, often a `WORKOS_WIF_TOKEN_URL` that isn't the `/oauth2/token` endpoint. | +| Token exchange fails with HTTP 404, or the response is not JSON | `WORKOS_WIF_TOKEN_URL` is wrong. It must be the `/oauth2/token` endpoint of your WorkOS environment. | +| CLI `wif_exchange_failed` ending in `Gave up after 3 attempts` | The token endpoint was unreachable or answered 5xx three times in a row. Re-run the job, and check `WORKOS_WIF_TOKEN_URL` if it keeps happening. | +| The API returns 401 after a successful exchange | The CLI already exchanged again and re-sent the request once. Check that `WORKOS_API_URL` points at the same deployment that issued the token, and that `WORKOS_ENVIRONMENT_ID`, if set, is the environment the M2M application is bound to (or unset it). | +| The API returns 403 after a successful exchange | The token doesn't carry the scope that endpoint needs. Grant the scope to the M2M application, and include it in `WORKOS_WIF_SCOPE` if you set that variable. | +| The CLI job uses an API key instead of WIF | `WORKOS_API_KEY` (or `--api-key`) always wins. Remove it from the job's environment. | +| CLI `wif_unsupported_command` | That command can't use WIF (for example `workos verify-login`, which won't create users when it can't confirm the environment isn't production). Use a sandbox `WORKOS_API_KEY` for that step. `workos migrations` ignores WIF entirely. | diff --git a/src/bin.ts b/src/bin.ts index bbc991b3..e559c568 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -304,7 +304,6 @@ const WIF_PRIMED_COMMANDS = new Set([ 'seed', 'setup-org', 'onboard-user', - 'verify-login', 'debug-sso', 'debug-sync', ]); diff --git a/src/commands/api/index.spec.ts b/src/commands/api/index.spec.ts index c117490e..4bcdf9f6 100644 --- a/src/commands/api/index.spec.ts +++ b/src/commands/api/index.spec.ts @@ -58,6 +58,9 @@ vi.mock('./request.js', () => ({ apiRequest: (...args: unknown[]) => mockApiRequest(...args), })); +let wifAccessToken: string | undefined; +vi.mock('../../lib/wif.js', () => ({ peekWifAccessToken: () => wifAccessToken })); + vi.mock('../../lib/api-key.js', () => ({ resolveApiKey: vi.fn(() => 'sk_test'), resolveApiBaseUrl: vi.fn(() => 'https://api.example.com'), @@ -107,6 +110,7 @@ describe('runApiInteractive', () => { beforeEach(() => { vi.clearAllMocks(); resetInteractionModeForTests(); + wifAccessToken = undefined; consoleOutput = []; stderrOutput = []; vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { @@ -272,6 +276,7 @@ describe('runApiRequest', () => { beforeEach(() => { vi.clearAllMocks(); resetInteractionModeForTests(); + wifAccessToken = undefined; consoleOutput = []; stderrOutput = []; vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { @@ -379,6 +384,40 @@ describe('runApiRequest', () => { await expectExit(runApiRequest('/users', { yes: true }), 1); }); + describe('a 401 or 403', () => { + const errorOf = () => + stderrOutput + .map((line) => { + try { + return (JSON.parse(line) as { error?: { message?: string; recovery?: unknown } }).error; + } catch { + return undefined; + } + }) + .find((error) => error !== undefined); + + it('with an API key suggests logging in again', async () => { + setOutputMode('json'); + mockApiRequest.mockResolvedValue(buildResponse({ status: 403, body: { message: 'Forbidden' } })); + + await expectExit(runApiRequest('/vault/v1/kv', { yes: true }), 1); + + expect(errorOf()?.message).toBe('API request failed with status 403'); + expect(errorOf()?.recovery).toBeDefined(); + }); + + it('with a WIF token says the token was refused and does not suggest logging in', async () => { + setOutputMode('json'); + wifAccessToken = 'wif-access-token'; + mockApiRequest.mockResolvedValue(buildResponse({ status: 403, body: { message: 'Forbidden' } })); + + await expectExit(runApiRequest('/vault/v1/kv', { yes: true }), 1); + + expect(errorOf()?.message).toContain('refused the workload identity federation (WIF) access token (HTTP 403)'); + expect(errorOf()?.recovery).toBeUndefined(); + }); + }); + it('passes --include through to printResponse', async () => { setOutputMode('human'); const headers = new Headers({ 'x-request-id': 'abc' }); diff --git a/src/commands/api/index.ts b/src/commands/api/index.ts index 5f124974..bf6fa6f8 100644 --- a/src/commands/api/index.ts +++ b/src/commands/api/index.ts @@ -2,6 +2,8 @@ import chalk from 'chalk'; import { loadCatalog, endpointsByTag } from './catalog.js'; import { apiRequest } from './request.js'; import { resolveApiBaseUrl } from '../../lib/api-key.js'; +import { wifRefusalMessage } from '../../lib/api-error-handler.js'; +import { peekWifAccessToken } from '../../lib/wif.js'; import { exitWithError, isJsonMode, outputJson } from '../../utils/output.js'; import { ExitCode, exitWithCode } from '../../utils/exit-codes.js'; import { isCiMode, isPromptAllowed, getInteractionMode } from '../../utils/interaction-mode.js'; @@ -160,10 +162,15 @@ export async function runApiRequest(endpoint: string, options: ApiCommandOptions printResponse(response, { includeStatus: options.include }); if (response.status >= 400) { + const isAuthFailure = response.status === 401 || response.status === 403; + // A refused WIF token is not fixed by logging in, so it gets its own + // message and no recovery step. + const refusedWifToken = isAuthFailure && peekWifAccessToken() !== undefined; // Give the caller a concrete next step keyed off the status: re-auth for // 401/403, discover endpoints for 404. - const recovery = - response.status === 401 || response.status === 403 + const recovery = refusedWifToken + ? undefined + : isAuthFailure ? authLoginRecovery({ mode: getInteractionMode().mode }) : response.status === 404 ? missingArgsRecovery( @@ -173,7 +180,9 @@ export async function runApiRequest(endpoint: string, options: ApiCommandOptions : undefined; exitWithError({ code: `http_${response.status}`, - message: `API request failed with status ${response.status}`, + message: refusedWifToken + ? wifRefusalMessage(response.status) + : `API request failed with status ${response.status}`, apiContext: { status: response.status }, ...(recovery && { recovery }), }); diff --git a/src/lib/api-error-handler.spec.ts b/src/lib/api-error-handler.spec.ts index c1744509..f20063ad 100644 --- a/src/lib/api-error-handler.spec.ts +++ b/src/lib/api-error-handler.spec.ts @@ -1,5 +1,8 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +let wifAccessToken: string | undefined; +vi.mock('./wif.js', () => ({ peekWifAccessToken: () => wifAccessToken })); + const { WorkOSApiError } = await import('./workos-api.js'); const { createApiErrorHandler } = await import('./api-error-handler.js'); const { setOutputMode } = await import('../utils/output.js'); @@ -10,6 +13,7 @@ describe('createApiErrorHandler', () => { beforeEach(() => { setOutputMode('json'); + wifAccessToken = undefined; stderrOutput = []; vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { stderrOutput.push(args.map(String).join(' ')); @@ -100,6 +104,25 @@ describe('createApiErrorHandler', () => { }); }); + describe('with a workload identity federation (WIF) token as the credential', () => { + it.each([401, 403])('a %i says the WIF token was refused, not that an API key is invalid', (status) => { + wifAccessToken = 'wif-access-token'; + const handler = createApiErrorHandler('Vault object'); + invoke(handler, new WorkOSApiError('Refused', status)); + const { message } = parseError().error; + expect(message).toContain(`refused the workload identity federation (WIF) access token (HTTP ${status})`); + expect(message).toContain('Set WORKOS_API_KEY for this step'); + expect(message).not.toContain('Invalid API key'); + }); + + it('a 404 keeps its usual message', () => { + wifAccessToken = 'wif-access-token'; + const handler = createApiErrorHandler('Organization'); + invoke(handler, new WorkOSApiError('Not found', 404)); + expect(parseError().error.message).toBe('Organization not found.'); + }); + }); + describe('SDK exceptions (@workos-inc/node)', () => { it('handles 401 (UnauthorizedException)', () => { const handler = createApiErrorHandler('Organization'); diff --git a/src/lib/api-error-handler.ts b/src/lib/api-error-handler.ts index 0c2d5c9a..6fdcdbea 100644 --- a/src/lib/api-error-handler.ts +++ b/src/lib/api-error-handler.ts @@ -1,6 +1,7 @@ import { WorkOSApiError } from './workos-api.js'; import { exitWithError } from '../utils/output.js'; import { CliExit } from '../utils/cli-exit.js'; +import { peekWifAccessToken } from './wif.js'; export function isSdkException( error: unknown, @@ -39,7 +40,17 @@ function normalizeApiError(error: unknown): NormalizedApiError | null { return null; } +/** What to say when the API refuses a workload identity federation (WIF) token. */ +export function wifRefusalMessage(status: number): string { + return ( + `WorkOS refused the workload identity federation (WIF) access token (HTTP ${status}). ` + + "This route may not accept WIF tokens yet, or the M2M application doesn't hold the scope it needs. " + + 'Set WORKOS_API_KEY for this step, or grant the application the scope.' + ); +} + function getApiErrorMessage(error: NormalizedApiError, label: string): string { + if ((error.status === 401 || error.status === 403) && peekWifAccessToken()) return wifRefusalMessage(error.status); if (error.status === 401) return 'Invalid API key. Check your environment configuration.'; if (error.status === 404) return `${label} not found.`; if (error.status === 422 && error.errors?.length) return error.errors.map((e) => e.message).join(', '); diff --git a/src/lib/api-key.spec.ts b/src/lib/api-key.spec.ts index 7ad7798e..48f56aae 100644 --- a/src/lib/api-key.spec.ts +++ b/src/lib/api-key.spec.ts @@ -137,9 +137,21 @@ describe('api-key', () => { expect(resolveApiKey()).toBe('sk_env_var'); }); + it('with a stored key and no WORKOS_WIF_TOKEN_URL, keeps using the stored key', () => { + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = 'https://token.example.com/idtoken?api-version=2.0'; + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'request-token'; + delete process.env.WORKOS_WIF_TOKEN_URL; + saveConfig({ + activeEnvironment: 'prod', + environments: { prod: { name: 'prod', type: 'production', apiKey: 'sk_stored' } }, + }); + expect(resolveApiKey()).toBe('sk_stored'); + }); + it('exits wif_unsupported_command when WIF applies but was not primed', () => { process.env.ACTIONS_ID_TOKEN_REQUEST_URL = 'https://token.example.com/idtoken?api-version=2.0'; process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'request-token'; + process.env.WORKOS_WIF_TOKEN_URL = 'https://auth.example.com/oauth2/token'; saveConfig({ activeEnvironment: 'prod', environments: { prod: { name: 'prod', type: 'production', apiKey: 'sk_stored' } }, diff --git a/src/lib/api-key.ts b/src/lib/api-key.ts index 6aafcd86..dc56bbaa 100644 --- a/src/lib/api-key.ts +++ b/src/lib/api-key.ts @@ -8,6 +8,10 @@ * 3. Workload identity federation in GitHub Actions (see wif.ts): a * short-lived WorkOS access token, primed by primeApiCredentials() * 4. Active environment's stored API key + * + * A job that has a stored key and no WORKOS_WIF_TOKEN_URL keeps using the + * stored key: WORKOS_CLIENT_ID and `id-token: write` are often set for other + * reasons, and without a token endpoint WIF could only fail. */ import { getActiveEnvironment } from './config-store.js'; @@ -38,11 +42,11 @@ export function resolveApiKey(options?: ApiKeyOptions): string { if (explicit) return explicit; const wifState = getWifState(); - if (wifState === 'ready') { + const stored = getActiveEnvironment()?.apiKey; + if (wifState === 'ready' && !(stored && wifIsUnconfigured())) { return peekWifAccessToken() ?? exitWithWifUnsupported(); } - const stored = getActiveEnvironment()?.apiKey; if (stored) return stored; if (wifState === 'missing_id_token_env') exitWithMissingIdTokenPermission(); @@ -60,7 +64,14 @@ export function resolveApiKey(options?: ApiKeyOptions): string { */ export async function primeApiCredentials(options?: ApiKeyOptions): Promise { if (resolveExplicitApiKey(options)) return; - if (getWifState() === 'ready') await getWifAccessToken(); + if (getWifState() !== 'ready') return; + if (wifIsUnconfigured() && getActiveEnvironment()?.apiKey) return; + await getWifAccessToken(); +} + +/** WIF has no token endpoint to exchange at. */ +function wifIsUnconfigured(): boolean { + return !process.env.WORKOS_WIF_TOKEN_URL; } /** resolveApiKey() for call sites that can await: primes WIF first. */ diff --git a/src/lib/wif.spec.ts b/src/lib/wif.spec.ts index c3c65f12..079a2f92 100644 --- a/src/lib/wif.spec.ts +++ b/src/lib/wif.spec.ts @@ -11,6 +11,7 @@ const { getWifState, isWifAccessToken, resetWifCacheForTests, + setWifRequestTimeoutForTests, setWifRetryBackoffForTests, WIF_GRANT_TYPE, ENVIRONMENT_ID_HEADER, @@ -102,6 +103,7 @@ describe('workload identity federation (wif)', () => { activeEnv = undefined; resetWifCacheForTests(); setWifRetryBackoffForTests(0); + setWifRequestTimeoutForTests(15_000); resetRegisteredSecretsForTests(); setOutputMode('human'); @@ -448,10 +450,18 @@ describe('workload identity federation (wif)', () => { expect(stderr.join('\n')).toContain('had no token (HTTP 200)'); }); - it('missing WORKOS_WIF_TOKEN_URL: says it is required, why, and its shape, with no fallback', async () => { + it('missing WORKOS_WIF_TOKEN_URL with a stored key: uses the stored key and makes no request', async () => { delete process.env.WORKOS_WIF_TOKEN_URL; activeEnv = { name: 'ci', type: 'sandbox', apiKey: 'sk_test_stored' }; + expect(await resolveApiKeyAsync()).toBe('sk_test_stored'); + expect(calls).toHaveLength(0); + expect(stderr).toEqual([]); + }); + + it('missing WORKOS_WIF_TOKEN_URL and no stored key: says it is required, why, and its shape', async () => { + delete process.env.WORKOS_WIF_TOKEN_URL; + const exit = await expectCliExit(resolveApiKeyAsync()); expect(exit.context?.errorCode).toBe('wif_token_url_missing'); expect(exit.exitCode).toBe(4); @@ -472,9 +482,13 @@ describe('workload identity federation (wif)', () => { it.each([ ['invalid_grant', 'trust rules'], - ['invalid_target', 'audience'], + ['invalid_target', 'WORKOS_WIF_TOKEN_URL is the endpoint for the WorkOS API'], ['invalid_client', 'Set WORKOS_CLIENT_ID to the client ID'], - ['unauthorized_client', 'Check that WORKOS_CLIENT_ID is an M2M application with an enabled GitHub trust rule'], + ['invalid_client', 'no secret is needed, add a trust rule'], + [ + 'unauthorized_client', + 'Check that WORKOS_CLIENT_ID is an M2M application with a GitHub trust rule that has not expired', + ], ['invalid_scope', 'Set WORKOS_WIF_SCOPE to scopes the application has, or unset it'], ['invalid_request', '/oauth2/token'], ])('%s: names the error, includes error_description and says what to fix', async (error, hint) => { @@ -492,15 +506,14 @@ describe('workload identity federation (wif)', () => { expect(tokenCalls()).toHaveLength(1); }); - it('invalid_grant and invalid_target say which settings to compare', async () => { + it('invalid_grant says which settings to compare, and names none the server does not have', async () => { tokenHandler = () => json({ error: 'invalid_grant' }, 400); await expectCliExit(resolveApiKeyAsync()); - expect(stderr.join('\n')).toContain("Check the trust rule's repository, ref and audience against this run"); - - stderr.length = 0; - tokenHandler = () => json({ error: 'invalid_target' }, 400); - await expectCliExit(resolveApiKeyAsync()); - expect(stderr.join('\n')).toContain("Set the trust rule's audience and WORKOS_WIF_AUDIENCE to the same value"); + const message = stderr.join('\n'); + expect(message).toContain("Check the trust rule's repository and ref against this run"); + expect(message).toContain('that the trust rule has not expired'); + expect(message).toContain("WORKOS_WIF_AUDIENCE is the application's audience"); + expect(message).not.toContain('enabled'); }); it('unauthorized_client exits 4 and names every condition to check', async () => { @@ -737,6 +750,36 @@ describe('workload identity federation (wif)', () => { expect(tokenCalls().map(assertionOf)).toEqual(['github-jwt-attempt-1', 'github-jwt-attempt-2']); }); + it('counts an exchange that does not answer in time as a failed attempt and retries', async () => { + setWifRequestTimeoutForTests(20); + let attempt = 0; + tokenHandler = (_url, init) => { + if (++attempt > 1) return json({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 300 }); + // Never answers: settles only when the request's own timeout aborts it. + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)); + }); + }; + + expect(await getWifAccessToken()).toBe(ACCESS_TOKEN); + + expect(tokenCalls()).toHaveLength(2); + }); + + it('exits when GitHub does not answer the OIDC token request in time', async () => { + setWifRequestTimeoutForTests(20); + githubHandler = (_url, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)); + }); + + const exit = await expectCliExit(resolveApiKeyAsync()); + + expect(exit.context?.errorCode).toBe('wif_id_token_request_failed'); + expect(stderr.join('\n')).toContain('Could not reach GitHub to request an OIDC token'); + expect(tokenCalls()).toHaveLength(0); + }); + it('retries when the connection drops while the response body is read', async () => { const jwts = ['github-jwt-attempt-1', 'github-jwt-attempt-2']; githubHandler = () => json({ value: jwts.shift() }); diff --git a/src/lib/wif.ts b/src/lib/wif.ts index b24bda7c..df6f97a2 100644 --- a/src/lib/wif.ts +++ b/src/lib/wif.ts @@ -46,6 +46,8 @@ const DEFAULT_LIFETIME_SECONDS = 300; const MAX_EXCHANGE_ATTEMPTS = 3; /** Wait before the second attempt; doubles for each one after. */ const DEFAULT_RETRY_BACKOFF_MS = 500; +/** How long the GitHub token request and each exchange attempt may take before they count as failed. */ +const DEFAULT_REQUEST_TIMEOUT_MS = 15_000; /** Cap on server-provided `error_description` text echoed into an error message. */ const MAX_DESCRIPTION_LENGTH = 500; @@ -65,14 +67,16 @@ const ID_TOKEN_PERMISSION_HINT = const OAUTH_ERROR_HINTS: Record = { invalid_grant: "None of the M2M application's trust rules matched this workflow run, or the GitHub OIDC token expired or was already used. " + - "Check the trust rule's repository, ref and audience against this run, and that the trust rule is enabled, then re-run the job.", - invalid_target: `The resource or audience is wrong. Set the trust rule's audience and WORKOS_WIF_AUDIENCE to the same value (default ${WIF_DEFAULT_AUDIENCE}).`, + "Check the trust rule's repository and ref against this run, that the trust rule has not expired, " + + "and that WORKOS_WIF_AUDIENCE is the application's audience, then re-run the job.", + invalid_target: `The resource is not one this token endpoint issues tokens for. Check that WORKOS_WIF_TOKEN_URL is the endpoint for the WorkOS API (the CLI asks for ${WIF_RESOURCE}).`, invalid_client: 'Set WORKOS_CLIENT_ID to the client ID of the M2M application that has the GitHub trust rule, ' + - 'and check that WORKOS_WIF_TOKEN_URL belongs to the same WorkOS environment as that application.', + 'and check that WORKOS_WIF_TOKEN_URL belongs to the same WorkOS environment as that application. ' + + "If the message asks for a client secret, the application's trust rules have all expired or been removed: no secret is needed, add a trust rule.", unauthorized_client: "This client isn't allowed to use workload identity federation. " + - 'Check that WORKOS_CLIENT_ID is an M2M application with an enabled GitHub trust rule, ' + + 'Check that WORKOS_CLIENT_ID is an M2M application with a GitHub trust rule that has not expired, ' + 'that workload identity federation is turned on for your WorkOS team, ' + 'and that the application targets a non-production environment.', invalid_scope: @@ -226,6 +230,7 @@ export function createWifFetch(credential: string): typeof fetch { } let retryBackoffMs = DEFAULT_RETRY_BACKOFF_MS; +let requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS; /** Test-only: forget cached and issued tokens. */ export function resetWifCacheForTests(): void { @@ -239,6 +244,11 @@ export function setWifRetryBackoffForTests(ms: number): void { retryBackoffMs = ms; } +/** Test-only: shorten how long a WIF request may take. */ +export function setWifRequestTimeoutForTests(ms: number): void { + requestTimeoutMs = ms; +} + function resolveTokenUrl(): string { const raw = process.env.WORKOS_WIF_TOKEN_URL; // No default yet: the WorkOS side of this grant (`workos-api-workload-identity`) is @@ -321,6 +331,7 @@ async function requestGitHubIdToken(audience: string): Promise { response = await fetch(url.toString(), { method: 'GET', headers: { Authorization: `Bearer ${requestToken}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(requestTimeoutMs), }); } catch (error) { exitWithError({ @@ -405,6 +416,7 @@ async function attemptExchange(tokenUrl: string, assertion: string): Promise