From ae5aa4552d0d7250a45afef051fa241c1b442d23 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 01:14:31 -0800 Subject: [PATCH 01/14] feat(workload-identity): add workload identity federation Authorize API requests with a short-lived access token, exchanged from the workload's own identity token, in place of an API key: new WorkOS({ credentials: new WorkloadIdentityCredentials({ ... }) }) - Credential seam: the HTTP client resolves credentials before every attempt and recovers once from a 401. An API key is the static implementation, and its requests are unchanged. - WIF core in the SDK: the jwt-bearer exchange, a per-instance token cache refreshed at min(60s, 20% of lifetime), one shared in-flight exchange, retries on network failures, 429 and 5xx, WorkloadIdentityError, tokenFile and tokenEnv. - Three provider packages under packages/: GitHub Actions, Google Cloud and AWS. None depends on @workos-inc/node. - Release: the repository becomes a release-please manifest monorepo with one entry, release PR and publish job per provider package. CI and scripts/ci cover each package. Built against a mock of the token endpoint. Nothing is published. Spec: docs/ideation/wif-backend-sdks/spec-phase-3.md Review: passed in cycle 2 of 3. --- .github/workflows/ci.yml | 56 + .github/workflows/release-please.yml | 36 +- .github/workflows/release.yml | 16 + .github/workflows/workos-node-dep-bump.yml | 10 + .release-please-manifest.json | 5 +- README.md | 86 ++ eslint.config.mjs | 3 +- package-lock.json | 383 +++++- package.json | 3 + packages/workload-identity-aws/CHANGELOG.md | 1 + packages/workload-identity-aws/LICENSE | 21 + packages/workload-identity-aws/README.md | 33 + .../workload-identity-aws/jest.config.cjs | 12 + packages/workload-identity-aws/package.json | 56 + .../workload-identity-aws/src/index.spec.ts | 154 +++ packages/workload-identity-aws/src/index.ts | 74 ++ packages/workload-identity-aws/tsconfig.json | 7 + .../workload-identity-aws/tsdown.config.ts | 13 + packages/workload-identity-gcp/CHANGELOG.md | 1 + packages/workload-identity-gcp/LICENSE | 21 + packages/workload-identity-gcp/README.md | 29 + .../workload-identity-gcp/jest.config.cjs | 12 + packages/workload-identity-gcp/package.json | 53 + .../workload-identity-gcp/src/index.spec.ts | 125 ++ packages/workload-identity-gcp/src/index.ts | 53 + packages/workload-identity-gcp/tsconfig.json | 7 + .../workload-identity-gcp/tsdown.config.ts | 13 + .../CHANGELOG.md | 1 + .../workload-identity-github-actions/LICENSE | 21 + .../README.md | 36 + .../jest.config.cjs | 12 + .../package.json | 52 + .../src/index.spec.ts | 151 +++ .../src/index.ts | 71 + .../tsconfig.json | 7 + .../tsdown.config.ts | 13 + release-please-config.json | 31 +- scripts/ci | 17 + .../interfaces/workos-options.interface.ts | 8 + src/common/net/credentials.ts | 60 + src/common/net/fetch-client.ts | 157 ++- src/index.ts | 11 +- src/index.worker.ts | 20 +- src/workload-identity/constants.ts | 25 + src/workload-identity/index.ts | 15 + src/workload-identity/token-env.ts | 26 + src/workload-identity/token-file.ts | 62 + .../workload-identity-credentials.ts | 638 +++++++++ .../workload-identity-error.ts | 86 ++ .../workload-identity.spec.ts | 1159 +++++++++++++++++ src/workos.ts | 66 +- 51 files changed, 3984 insertions(+), 44 deletions(-) create mode 100644 packages/workload-identity-aws/CHANGELOG.md create mode 100644 packages/workload-identity-aws/LICENSE create mode 100644 packages/workload-identity-aws/README.md create mode 100644 packages/workload-identity-aws/jest.config.cjs create mode 100644 packages/workload-identity-aws/package.json create mode 100644 packages/workload-identity-aws/src/index.spec.ts create mode 100644 packages/workload-identity-aws/src/index.ts create mode 100644 packages/workload-identity-aws/tsconfig.json create mode 100644 packages/workload-identity-aws/tsdown.config.ts create mode 100644 packages/workload-identity-gcp/CHANGELOG.md create mode 100644 packages/workload-identity-gcp/LICENSE create mode 100644 packages/workload-identity-gcp/README.md create mode 100644 packages/workload-identity-gcp/jest.config.cjs create mode 100644 packages/workload-identity-gcp/package.json create mode 100644 packages/workload-identity-gcp/src/index.spec.ts create mode 100644 packages/workload-identity-gcp/src/index.ts create mode 100644 packages/workload-identity-gcp/tsconfig.json create mode 100644 packages/workload-identity-gcp/tsdown.config.ts create mode 100644 packages/workload-identity-github-actions/CHANGELOG.md create mode 100644 packages/workload-identity-github-actions/LICENSE create mode 100644 packages/workload-identity-github-actions/README.md create mode 100644 packages/workload-identity-github-actions/jest.config.cjs create mode 100644 packages/workload-identity-github-actions/package.json create mode 100644 packages/workload-identity-github-actions/src/index.spec.ts create mode 100644 packages/workload-identity-github-actions/src/index.ts create mode 100644 packages/workload-identity-github-actions/tsconfig.json create mode 100644 packages/workload-identity-github-actions/tsdown.config.ts create mode 100644 src/common/net/credentials.ts create mode 100644 src/workload-identity/constants.ts create mode 100644 src/workload-identity/index.ts create mode 100644 src/workload-identity/token-env.ts create mode 100644 src/workload-identity/token-file.ts create mode 100644 src/workload-identity/workload-identity-credentials.ts create mode 100644 src/workload-identity/workload-identity-error.ts create mode 100644 src/workload-identity/workload-identity.spec.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d814ab80d..8f15aab74 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,3 +57,59 @@ jobs: - name: Test run: | npm run test + + # Each package under packages/ is released on its own, so each is built and + # tested on its own. + packages: + name: ${{ matrix.package }} (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + strategy: + matrix: + node: [22, 24] + package: + - workload-identity-github-actions + - workload-identity-gcp + - workload-identity-aws + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: ${{ matrix.node }} + + - name: Configure Socket Firewall + uses: workos/setup-socket-firewall@ca93dd8aa351f54f4729fe3377a9be23c631c25d + with: + token: ${{ secrets.PUBLIC_SOCKET_FIREWALL_TOKEN }} + allow-external-fork-fallback: true + + # At the repository root: it installs every workspace package. + - name: Install Dependencies + run: | + npm install + + - name: Prettier + working-directory: packages/${{ matrix.package }} + run: | + npm run prettier + + - name: Lint + working-directory: packages/${{ matrix.package }} + run: | + npm run lint + + - name: Typecheck + working-directory: packages/${{ matrix.package }} + run: | + npm run typecheck + + - name: Build + working-directory: packages/${{ matrix.package }} + run: | + npm run build + + - name: Test + working-directory: packages/${{ matrix.package }} + run: | + npm run test diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 0309476e2..2308393f2 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -14,8 +14,13 @@ jobs: release-please: runs-on: ubuntu-latest outputs: + # With more than one package, these two refer to the root package (the SDK) only. release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} + # One per provider package, keyed by its path in release-please-config.json. + github_actions_release_created: ${{ steps.release.outputs['packages/workload-identity-github-actions--release_created'] }} + gcp_release_created: ${{ steps.release.outputs['packages/workload-identity-gcp--release_created'] }} + aws_release_created: ${{ steps.release.outputs['packages/workload-identity-aws--release_created'] }} steps: - name: Generate token id: generate-token @@ -25,7 +30,7 @@ jobs: private-key: ${{ secrets.SDK_BOT_PRIVATE_KEY }} permission-contents: write permission-pull-requests: write - + - uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5 id: release with: @@ -37,3 +42,32 @@ jobs: uses: ./.github/workflows/release.yml secrets: PUBLIC_SOCKET_FIREWALL_TOKEN: ${{ secrets.PUBLIC_SOCKET_FIREWALL_TOKEN }} + + # The provider packages do not depend on the SDK, so their publish jobs need + # no ordering against `publish` or against each other. + publish-workload-identity-github-actions: + needs: release-please + if: ${{ needs.release-please.outputs.github_actions_release_created == 'true' }} + uses: ./.github/workflows/release.yml + with: + package-path: packages/workload-identity-github-actions + secrets: + PUBLIC_SOCKET_FIREWALL_TOKEN: ${{ secrets.PUBLIC_SOCKET_FIREWALL_TOKEN }} + + publish-workload-identity-gcp: + needs: release-please + if: ${{ needs.release-please.outputs.gcp_release_created == 'true' }} + uses: ./.github/workflows/release.yml + with: + package-path: packages/workload-identity-gcp + secrets: + PUBLIC_SOCKET_FIREWALL_TOKEN: ${{ secrets.PUBLIC_SOCKET_FIREWALL_TOKEN }} + + publish-workload-identity-aws: + needs: release-please + if: ${{ needs.release-please.outputs.aws_release_created == 'true' }} + uses: ./.github/workflows/release.yml + with: + package-path: packages/workload-identity-aws + secrets: + PUBLIC_SOCKET_FIREWALL_TOKEN: ${{ secrets.PUBLIC_SOCKET_FIREWALL_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 46d66236f..1eb2851ea 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,7 +2,19 @@ name: Release on: workflow_dispatch: + inputs: + package-path: + description: 'Package to publish: "." for the SDK, or a path under packages/' + required: false + default: '.' + type: string workflow_call: + inputs: + package-path: + description: 'Package to publish: "." for the SDK, or a path under packages/' + required: false + default: '.' + type: string secrets: PUBLIC_SOCKET_FIREWALL_TOKEN: required: true @@ -25,17 +37,21 @@ jobs: with: token: ${{ secrets.PUBLIC_SOCKET_FIREWALL_TOKEN }} + # Always at the repository root: it installs every workspace package. - name: Install Dependencies run: npm install - name: Build Project + working-directory: ${{ inputs.package-path }} run: npm run build - name: Run Tests + working-directory: ${{ inputs.package-path }} run: npm run test - name: Teardown Socket Firewall uses: workos/setup-socket-firewall/teardown@ca93dd8aa351f54f4729fe3377a9be23c631c25d - name: Publish + working-directory: ${{ inputs.package-path }} run: npm publish --tag latest --access public --provenance diff --git a/.github/workflows/workos-node-dep-bump.yml b/.github/workflows/workos-node-dep-bump.yml index 3898f6814..932689ec4 100644 --- a/.github/workflows/workos-node-dep-bump.yml +++ b/.github/workflows/workos-node-dep-bump.yml @@ -35,6 +35,16 @@ jobs: run: | if [ "$EVENT_NAME" = "release" ]; then TAG="$RELEASE_TAG" + + # The packages under packages/ release from this repository too, + # with tags like @workos-inc/workload-identity-gcp-v1.0.0. Only an + # SDK release (vX.Y.Z) bumps the dependency in other repos. + if ! [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+ ]]; then + echo "Not an SDK release ($TAG) — skipping." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + VERSION="${TAG#v}" MAJOR=$(echo "$VERSION" | cut -d. -f1) MINOR=$(echo "$VERSION" | cut -d. -f2) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ce79e2a70..a2e0da48a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,6 @@ { - ".": "12.2.0" + ".": "12.2.0", + "packages/workload-identity-github-actions": "0.0.0", + "packages/workload-identity-gcp": "0.0.0", + "packages/workload-identity-aws": "0.0.0" } diff --git a/README.md b/README.md index ec199965a..5724d531c 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,92 @@ if (!claims) { console.log(claims.sub, claims.org_id, claims.permissions); ``` +## Workload identity + +A workload running in GitHub Actions, Google Cloud or AWS can call the WorkOS API without an API key. It exchanges the identity token its platform issues for a short-lived WorkOS access token. The SDK makes the exchange, caches the token and replaces it shortly before it expires. + +Install the SDK and the provider package for your platform: + +``` +npm install @workos-inc/node @workos-inc/workload-identity-github-actions +``` + +Then pass `credentials` in place of an API key: + +```ts +import { WorkOS, WorkloadIdentityCredentials } from '@workos-inc/node'; +import { githubActions } from '@workos-inc/workload-identity-github-actions'; + +const workos = new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + clientId: 'client_...', // the M2M application that has the trust rule + tokenUrl: 'https:///oauth2/token', + environmentId: 'environment_...', + identityTokenProvider: githubActions('https://api.workos.com'), + }), +}); + +const organizations = await workos.organizations.listOrganizations(); +``` + +`clientId`, `tokenUrl`, `environmentId` and `scope` default to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL`, `WORKOS_ENVIRONMENT_ID` and `WORKOS_WIF_SCOPE` environment variables. Those variables only fill in fields you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. + +### Platform providers + +Each platform has its own package. The argument is the audience the identity token is requested for, which must match the audience of the trust rule. + +GitHub Actions. The job needs `permissions: id-token: write`: + +```ts +import { githubActions } from '@workos-inc/workload-identity-github-actions'; + +const identityTokenProvider = githubActions('https://api.workos.com'); +``` + +Google Cloud (Compute Engine, GKE, Cloud Run, Cloud Functions, App Engine): + +```ts +import { gcpMetadata } from '@workos-inc/workload-identity-gcp'; + +const identityTokenProvider = gcpMetadata('https://api.workos.com'); +``` + +AWS. The region is optional when the AWS SDK can resolve one: + +```ts +import { awsSts } from '@workos-inc/workload-identity-aws'; + +const identityTokenProvider = awsSts('https://api.workos.com', 'us-east-1'); +``` + +### Custom providers + +A provider is any function that returns the identity token. Use a callback for a platform without a package: + +```ts +const credentials = new WorkloadIdentityCredentials({ + identityTokenProvider: async () => { + const response = await fetch('https://identity.internal.example/token'); + return response.text(); + }, +}); +``` + +`tokenFile` reads the token from a file and `tokenEnv` from an environment variable, on every exchange, so a rotated token is picked up: + +```ts +import { tokenEnv, tokenFile } from '@workos-inc/node'; + +tokenFile('/var/run/secrets/tokens/workos'); +tokenEnv('MY_PLATFORM_JWT'); +``` + +`tokenFile` needs a file system, so it is not exported from `@workos-inc/node/worker`. + +### Errors + +A failed exchange throws a `WorkloadIdentityError`. Its `code` is the OAuth error code from the token endpoint (for example `invalid_grant`) or an SDK code (`exchange_failed`, `invalid_response`, `provider_failed`, `invalid_configuration`), `description` is the server's explanation, and `hint` says what to check. The exchange is retried on network failures, 429 and 5xx responses. An API request that gets a 401 is retried once with a new token. + ## Public Client Mode (Browser/Mobile/CLI) For apps that can't securely store secrets, initialize with just a client ID: diff --git a/eslint.config.mjs b/eslint.config.mjs index f71490fb1..51d0bdede 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -11,7 +11,8 @@ const ignores = [ 'node_modules', 'dist', 'build', - 'lib', + // Build output of the SDK and of every package under packages/. + '**/lib', ]; const tests = ['**/*.spec.{js,ts}']; diff --git a/package-lock.json b/package-lock.json index a45b10af6..cc7cacd71 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "@workos-inc/node", "version": "12.2.0", "license": "MIT", + "workspaces": [ + "packages/*" + ], "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", "@babel/plugin-transform-modules-commonjs": "^7.26.3", @@ -96,6 +99,263 @@ "node": ">=14.17" } }, + "node_modules/@aws-sdk/client-sts": { + "version": "3.1167.0", + "integrity": "sha512-0DrmFoeqDiudnFmpcJ4LEqeHnFX5ECQF8cb6ktza8/t8SJx/lCo643u9Wk03VPHsOp0YjidGUZWa3ISVFPhIdw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/credential-provider-node": "^3.972.97", + "@aws-sdk/signature-v4-multi-region": "^3.996.52", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/fetch-http-handler": "^5.8.1", + "@smithy/node-http-handler": "^4.14.2", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.981.0", + "integrity": "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.975.1", + "@aws-sdk/xml-builder": "^3.972.43", + "@aws/lambda-invoke-store": "^0.3.0", + "@smithy/core": "^3.40.0", + "@smithy/signature-v4": "^5.7.5", + "@smithy/types": "^4.20.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.972.84", + "integrity": "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.972.86", + "integrity": "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/fetch-http-handler": "^5.8.1", + "@smithy/node-http-handler": "^4.14.2", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.973.30", + "integrity": "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/credential-provider-env": "^3.972.84", + "@aws-sdk/credential-provider-http": "^3.972.86", + "@aws-sdk/credential-provider-login": "^3.972.92", + "@aws-sdk/credential-provider-process": "^3.972.84", + "@aws-sdk/credential-provider-sso": "^3.973.28", + "@aws-sdk/credential-provider-web-identity": "^3.972.90", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/credential-provider-imds": "^4.5.2", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-login": { + "version": "3.972.92", + "integrity": "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.972.97", + "integrity": "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.84", + "@aws-sdk/credential-provider-http": "^3.972.86", + "@aws-sdk/credential-provider-ini": "^3.973.30", + "@aws-sdk/credential-provider-process": "^3.972.84", + "@aws-sdk/credential-provider-sso": "^3.973.28", + "@aws-sdk/credential-provider-web-identity": "^3.972.90", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/credential-provider-imds": "^4.5.2", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.972.84", + "integrity": "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.973.28", + "integrity": "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/token-providers": "3.1166.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.972.90", + "integrity": "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.998.3", + "integrity": "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/signature-v4-multi-region": "^3.996.52", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/fetch-http-handler": "^5.8.1", + "@smithy/node-http-handler": "^4.14.2", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.996.52", + "integrity": "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.975.1", + "@smithy/signature-v4": "^5.7.5", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.1166.0", + "integrity": "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.975.1", + "integrity": "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.972.43", + "integrity": "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.3.0", + "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", @@ -4360,6 +4620,81 @@ "@sinonjs/commons": "^3.0.1" } }, + "node_modules/@smithy/core": { + "version": "3.40.0", + "integrity": "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.5.2", + "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.33.2", + "@smithy/types": "^4.17.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.8.1", + "integrity": "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.39.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.14.2", + "integrity": "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.39.0", + "@smithy/types": "^4.20.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.7.5", + "integrity": "sha512-WPjdr5oWOk1LArpI4pavu+fSo+/evi0Re1olxGvqwuZopd4gYR1UGCi+Soyn/IjmafqbWs+ZC+3AKxJS3ZpwUg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.38.0", + "@smithy/types": "^4.19.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.20.0", + "integrity": "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@speed-highlight/core": { "version": "1.2.15", "integrity": "sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==", @@ -5055,6 +5390,18 @@ "win32" ] }, + "node_modules/@workos-inc/workload-identity-aws": { + "resolved": "packages/workload-identity-aws", + "link": true + }, + "node_modules/@workos-inc/workload-identity-gcp": { + "resolved": "packages/workload-identity-gcp", + "link": true + }, + "node_modules/@workos-inc/workload-identity-github-actions": { + "resolved": "packages/workload-identity-github-actions", + "link": true + }, "node_modules/@yuku-core/binding-android-arm64": { "version": "0.19.0", "integrity": "sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw==", @@ -5517,6 +5864,11 @@ "node": ">=6.0.0" } }, + "node_modules/bowser": { + "version": "2.15.0", + "integrity": "sha512-xic6KSZglg/I4ymp45fdM4GWfYpBK79Fxd/TOvJktlaPgQqqDxvmGwOPZl2V0dyeS3Lj5c180bLhXF43iyAjZQ==", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "5.0.9", "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", @@ -9163,9 +9515,7 @@ "node_modules/tslib": { "version": "2.8.1", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true + "license": "0BSD" }, "node_modules/tsx": { "version": "4.23.15", @@ -9772,6 +10122,33 @@ "engines": { "node": ">=14.18.0" } + }, + "packages/workload-identity-aws": { + "name": "@workos-inc/workload-identity-aws", + "version": "0.0.0", + "license": "MIT", + "dependencies": { + "@aws-sdk/client-sts": "^3.935.0" + }, + "engines": { + "node": ">=22.11.0" + } + }, + "packages/workload-identity-gcp": { + "name": "@workos-inc/workload-identity-gcp", + "version": "0.0.0", + "license": "MIT", + "engines": { + "node": ">=22.11.0" + } + }, + "packages/workload-identity-github-actions": { + "name": "@workos-inc/workload-identity-github-actions", + "version": "0.0.0", + "license": "MIT", + "engines": { + "node": ">=22.11.0" + } } } } diff --git a/package.json b/package.json index 0ad08f290..435e41c38 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,9 @@ "lib/", "package.json" ], + "workspaces": [ + "packages/*" + ], "scripts": { "build": "tsdown", "build:watch": "tsdown --watch", diff --git a/packages/workload-identity-aws/CHANGELOG.md b/packages/workload-identity-aws/CHANGELOG.md new file mode 100644 index 000000000..825c32f0d --- /dev/null +++ b/packages/workload-identity-aws/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/workload-identity-aws/LICENSE b/packages/workload-identity-aws/LICENSE new file mode 100644 index 000000000..656ceca82 --- /dev/null +++ b/packages/workload-identity-aws/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 WorkOS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/workload-identity-aws/README.md b/packages/workload-identity-aws/README.md new file mode 100644 index 000000000..312620b89 --- /dev/null +++ b/packages/workload-identity-aws/README.md @@ -0,0 +1,33 @@ +# @workos-inc/workload-identity-aws + +An AWS identity token provider for [WorkOS workload identity](https://github.com/workos/workos-node#workload-identity). A workload with an IAM role authenticates to the WorkOS API with a token signed by AWS STS, so no API key is stored. + +## Installation + +``` +npm install @workos-inc/node @workos-inc/workload-identity-aws +``` + +## Usage + +```ts +import { WorkOS, WorkloadIdentityCredentials } from '@workos-inc/node'; +import { awsSts } from '@workos-inc/workload-identity-aws'; + +const workos = new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + clientId: 'client_...', + tokenUrl: 'https:///oauth2/token', + environmentId: 'environment_...', + identityTokenProvider: awsSts('https://api.workos.com', 'us-east-1'), + }), +}); +``` + +`awsSts(audience, region)` returns a function that calls `sts:GetWebIdentityToken` (signed with RS256) on every call. The audience must match the audience of the trust rule on the WorkOS application. + +- AWS credentials come from the AWS SDK's default chain. +- `region` is optional when the AWS SDK can resolve one, for example from `AWS_REGION`. The call uses that region's STS endpoint, never the global endpoint. +- The AWS account needs outbound identity federation enabled, and the role needs permission for `sts:GetWebIdentityToken`. + +The package depends on `@aws-sdk/client-sts` and does not depend on `@workos-inc/node`. diff --git a/packages/workload-identity-aws/jest.config.cjs b/packages/workload-identity-aws/jest.config.cjs new file mode 100644 index 000000000..70770125b --- /dev/null +++ b/packages/workload-identity-aws/jest.config.cjs @@ -0,0 +1,12 @@ +module.exports = { + clearMocks: true, + resetMocks: true, + restoreMocks: true, + verbose: true, + testEnvironment: 'node', + roots: ['/src'], + transform: { + // The repository's shared Babel transform. + '^.+\\.m?[jt]s$': '/../../jest-transform-esm.cjs', + }, +}; diff --git a/packages/workload-identity-aws/package.json b/packages/workload-identity-aws/package.json new file mode 100644 index 000000000..bf7c2719d --- /dev/null +++ b/packages/workload-identity-aws/package.json @@ -0,0 +1,56 @@ +{ + "name": "@workos-inc/workload-identity-aws", + "version": "0.0.0", + "description": "AWS identity token provider for WorkOS workload identity", + "keywords": [ + "workos", + "workload-identity", + "aws", + "sts", + "oidc" + ], + "homepage": "https://github.com/workos/workos-node/tree/main/packages/workload-identity-aws", + "bugs": { + "url": "https://github.com/workos/workos-node/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/workos/workos-node.git", + "directory": "packages/workload-identity-aws" + }, + "license": "MIT", + "author": "WorkOS", + "type": "module", + "files": [ + "lib/" + ], + "scripts": { + "build": "tsdown", + "clean": "rm -rf lib", + "format": "prettier \"src/**/*.ts\" --write", + "lint": "eslint", + "prepublishOnly": "npm run build", + "prettier": "prettier \"src/**/*.ts\" --check", + "test": "jest", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@aws-sdk/client-sts": "^3.935.0" + }, + "engines": { + "node": ">=22.11.0" + }, + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.cjs", + "module": "./lib/index.mjs", + "types": "./lib/index.d.cts", + "exports": { + ".": { + "import": "./lib/index.mjs", + "require": "./lib/index.cjs" + }, + "./package.json": "./package.json" + } +} diff --git a/packages/workload-identity-aws/src/index.spec.ts b/packages/workload-identity-aws/src/index.spec.ts new file mode 100644 index 000000000..f3ed8a22e --- /dev/null +++ b/packages/workload-identity-aws/src/index.spec.ts @@ -0,0 +1,154 @@ +// @oagen-ignore-file +import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'; +import { awsSts } from './index'; + +const AUDIENCE = 'https://api.workos.com'; + +interface StsCall { + client: STSClient; + command: GetWebIdentityTokenCommand; + region: string; + endpoint: string; +} + +describe('awsSts', () => { + const OLD_ENV = process.env; + + /** + * Stubs the one STS method the provider calls. The client itself is real, + * so its region and endpoint are what a live call would use. Nothing here + * reaches AWS. + */ + function stubSts(respond: () => unknown): StsCall[] { + const calls: StsCall[] = []; + + ( + jest.spyOn(STSClient.prototype, 'send') as unknown as jest.SpyInstance + ).mockImplementation(async function ( + this: STSClient, + command: GetWebIdentityTokenCommand, + ) { + const region = await this.config.region(); + const useGlobalEndpoint = this.config.useGlobalEndpoint; + const endpoint = this.config.endpointProvider({ + Region: region, + UseGlobalEndpoint: + typeof useGlobalEndpoint === 'function' + ? await useGlobalEndpoint() + : useGlobalEndpoint, + UseFIPS: false, + UseDualStack: false, + }); + + calls.push({ + client: this, + command, + region, + endpoint: endpoint.url.hostname, + }); + + return respond(); + }); + + return calls; + } + + beforeEach(() => { + // No region from the machine running the tests. + process.env = { + ...OLD_ENV, + AWS_CONFIG_FILE: '/nonexistent/aws/config', + AWS_SHARED_CREDENTIALS_FILE: '/nonexistent/aws/credentials', + }; + delete process.env.AWS_REGION; + delete process.env.AWS_DEFAULT_REGION; + delete process.env.AWS_PROFILE; + }); + + afterEach(() => { + process.env = OLD_ENV; + }); + + it('WIF-AWS-01: calls GetWebIdentityToken with the audience and RS256 on a regional endpoint and returns the token', async () => { + const calls = stubSts(() => ({ WebIdentityToken: 'aws-jwt' })); + + await expect(awsSts(AUDIENCE, 'us-east-1')()).resolves.toBe('aws-jwt'); + + expect(calls).toHaveLength(1); + expect(calls[0].command).toBeInstanceOf(GetWebIdentityTokenCommand); + // No DurationSeconds: STS applies its default. + expect(calls[0].command.input).toEqual({ + Audience: [AUDIENCE], + SigningAlgorithm: 'RS256', + }); + expect(calls[0].region).toBe('us-east-1'); + expect(calls[0].endpoint).toBe('sts.us-east-1.amazonaws.com'); + + // With no region available, the first call is an error and STS is never + // called. + await expect(awsSts(AUDIENCE)()).rejects.toThrow('no AWS region'); + expect(calls).toHaveLength(1); + }); + + it('WIF-AWS-02: an STS error surfaces as a provider error naming the call', async () => { + const denied = Object.assign( + new Error( + 'User: arn:aws:sts::123456789012:assumed-role/app/i-0abc is not authorized to perform: sts:GetWebIdentityToken', + ), + { name: 'AccessDenied' }, + ); + stubSts(() => { + throw denied; + }); + + const error = await awsSts(AUDIENCE, 'us-east-1')().catch((e) => e); + + expect(error).toBeInstanceOf(Error); + expect(error.message).toBe( + 'sts:GetWebIdentityToken failed with AccessDenied.', + ); + expect(error.cause).toBe(denied); + }); + + it('uses the region the AWS SDK resolves when none is passed', async () => { + process.env.AWS_REGION = 'eu-west-1'; + const calls = stubSts(() => ({ WebIdentityToken: 'aws-jwt' })); + + await expect(awsSts(AUDIENCE)()).resolves.toBe('aws-jwt'); + + expect(calls[0].region).toBe('eu-west-1'); + expect(calls[0].endpoint).toBe('sts.eu-west-1.amazonaws.com'); + }); + + it('refuses the global STS endpoint', async () => { + const calls = stubSts(() => ({ WebIdentityToken: 'aws-jwt' })); + + await expect(awsSts(AUDIENCE, 'aws-global')()).rejects.toThrow( + 'no AWS region', + ); + expect(calls).toHaveLength(0); + }); + + it('builds the STS client once', async () => { + const calls = stubSts(() => ({ WebIdentityToken: 'aws-jwt' })); + const provider = awsSts(AUDIENCE, 'us-east-1'); + + await provider(); + await provider(); + + expect(calls).toHaveLength(2); + expect(calls[1].client).toBe(calls[0].client); + }); + + it('fails when STS returns no token', async () => { + stubSts(() => ({})); + + await expect(awsSts(AUDIENCE, 'us-east-1')()).rejects.toThrow( + 'sts:GetWebIdentityToken returned no token.', + ); + }); + + it('requires an audience', () => { + expect(() => awsSts('')).toThrow('an audience is required'); + }); +}); diff --git a/packages/workload-identity-aws/src/index.ts b/packages/workload-identity-aws/src/index.ts new file mode 100644 index 000000000..bdb271eeb --- /dev/null +++ b/packages/workload-identity-aws/src/index.ts @@ -0,0 +1,74 @@ +// @oagen-ignore-file +import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'; + +/** + * An identity token provider for AWS. Each call asks STS for a signed token + * (`sts:GetWebIdentityToken`, RS256) that represents the calling role. + * + * AWS credentials come from the AWS SDK's default chain. The account needs + * outbound identity federation enabled, and the role needs permission for + * `sts:GetWebIdentityToken`. + * + * @param audience - The audience the token is requested for. It must match + * the audience of the trust rule, conventionally `https://api.workos.com`. + * @param region - The AWS region whose STS endpoint is called. Defaults to + * the region the AWS SDK resolves (`AWS_REGION`, then the shared config + * file). The call fails when there is none. + * + * @example + * new WorkloadIdentityCredentials({ + * identityTokenProvider: awsSts('https://api.workos.com', 'us-east-1'), + * }); + */ +export function awsSts( + audience: string, + region?: string, +): () => Promise { + if (!audience) { + throw new TypeError('awsSts: an audience is required.'); + } + + // Built once. STS does not serve this call from its global endpoint, so the + // client is held to the regional endpoint of its region. + const client = new STSClient({ + ...(region && { region }), + useGlobalEndpoint: false, + }); + + return async () => { + // The AWS SDK resolves the region on first use, so a missing region + // surfaces here and not when the provider is built. + const resolved = await client.config.region().catch(() => undefined); + + if (!resolved || resolved === 'aws-global') { + throw new Error( + 'awsSts: no AWS region. Pass a region or set AWS_REGION; sts:GetWebIdentityToken needs a regional STS endpoint.', + ); + } + + let token: string | undefined; + + try { + const response = await client.send( + new GetWebIdentityTokenCommand({ + Audience: [audience], + SigningAlgorithm: 'RS256', + }), + ); + token = response.WebIdentityToken; + } catch (error) { + // AWS service errors carry their code as the error name. + const code = error instanceof Error ? error.name : 'UnknownError'; + + throw new Error(`sts:GetWebIdentityToken failed with ${code}.`, { + cause: error, + }); + } + + if (!token) { + throw new Error('sts:GetWebIdentityToken returned no token.'); + } + + return token; + }; +} diff --git a/packages/workload-identity-aws/tsconfig.json b/packages/workload-identity-aws/tsconfig.json new file mode 100644 index 000000000..1b551f4e9 --- /dev/null +++ b/packages/workload-identity-aws/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "lib" + }, + "include": ["src"] +} diff --git a/packages/workload-identity-aws/tsdown.config.ts b/packages/workload-identity-aws/tsdown.config.ts new file mode 100644 index 000000000..12418f44d --- /dev/null +++ b/packages/workload-identity-aws/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/index.ts'], + dts: true, + format: ['esm', 'cjs'], + outDir: 'lib', + clean: true, + sourcemap: true, + exports: true, + publint: true, + attw: { profile: 'node16' }, +}); diff --git a/packages/workload-identity-gcp/CHANGELOG.md b/packages/workload-identity-gcp/CHANGELOG.md new file mode 100644 index 000000000..825c32f0d --- /dev/null +++ b/packages/workload-identity-gcp/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/workload-identity-gcp/LICENSE b/packages/workload-identity-gcp/LICENSE new file mode 100644 index 000000000..656ceca82 --- /dev/null +++ b/packages/workload-identity-gcp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 WorkOS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/workload-identity-gcp/README.md b/packages/workload-identity-gcp/README.md new file mode 100644 index 000000000..6576b63aa --- /dev/null +++ b/packages/workload-identity-gcp/README.md @@ -0,0 +1,29 @@ +# @workos-inc/workload-identity-gcp + +A Google Cloud identity token provider for [WorkOS workload identity](https://github.com/workos/workos-node#workload-identity). A workload on Compute Engine, GKE, Cloud Run, Cloud Functions or App Engine authenticates to the WorkOS API as its service account, so no API key is stored. + +## Installation + +``` +npm install @workos-inc/node @workos-inc/workload-identity-gcp +``` + +## Usage + +```ts +import { WorkOS, WorkloadIdentityCredentials } from '@workos-inc/node'; +import { gcpMetadata } from '@workos-inc/workload-identity-gcp'; + +const workos = new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + clientId: 'client_...', + tokenUrl: 'https:///oauth2/token', + environmentId: 'environment_...', + identityTokenProvider: gcpMetadata('https://api.workos.com'), + }), +}); +``` + +`gcpMetadata(audience)` returns a function that requests an identity token for the default service account from the metadata server on every call. The audience must match the audience of the trust rule on the WorkOS application. + +The package has no dependencies and does not depend on `@workos-inc/node`. diff --git a/packages/workload-identity-gcp/jest.config.cjs b/packages/workload-identity-gcp/jest.config.cjs new file mode 100644 index 000000000..70770125b --- /dev/null +++ b/packages/workload-identity-gcp/jest.config.cjs @@ -0,0 +1,12 @@ +module.exports = { + clearMocks: true, + resetMocks: true, + restoreMocks: true, + verbose: true, + testEnvironment: 'node', + roots: ['/src'], + transform: { + // The repository's shared Babel transform. + '^.+\\.m?[jt]s$': '/../../jest-transform-esm.cjs', + }, +}; diff --git a/packages/workload-identity-gcp/package.json b/packages/workload-identity-gcp/package.json new file mode 100644 index 000000000..8c48abc47 --- /dev/null +++ b/packages/workload-identity-gcp/package.json @@ -0,0 +1,53 @@ +{ + "name": "@workos-inc/workload-identity-gcp", + "version": "0.0.0", + "description": "Google Cloud identity token provider for WorkOS workload identity", + "keywords": [ + "workos", + "workload-identity", + "gcp", + "google-cloud", + "oidc" + ], + "homepage": "https://github.com/workos/workos-node/tree/main/packages/workload-identity-gcp", + "bugs": { + "url": "https://github.com/workos/workos-node/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/workos/workos-node.git", + "directory": "packages/workload-identity-gcp" + }, + "license": "MIT", + "author": "WorkOS", + "type": "module", + "files": [ + "lib/" + ], + "scripts": { + "build": "tsdown", + "clean": "rm -rf lib", + "format": "prettier \"src/**/*.ts\" --write", + "lint": "eslint", + "prepublishOnly": "npm run build", + "prettier": "prettier \"src/**/*.ts\" --check", + "test": "jest", + "typecheck": "tsc --noEmit" + }, + "engines": { + "node": ">=22.11.0" + }, + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.cjs", + "module": "./lib/index.mjs", + "types": "./lib/index.d.cts", + "exports": { + ".": { + "import": "./lib/index.mjs", + "require": "./lib/index.cjs" + }, + "./package.json": "./package.json" + } +} diff --git a/packages/workload-identity-gcp/src/index.spec.ts b/packages/workload-identity-gcp/src/index.spec.ts new file mode 100644 index 000000000..9755d60e0 --- /dev/null +++ b/packages/workload-identity-gcp/src/index.spec.ts @@ -0,0 +1,125 @@ +// @oagen-ignore-file +import http from 'node:http'; +import { AddressInfo } from 'node:net'; +import { gcpMetadata } from './index'; + +const AUDIENCE = 'https://api.workos.com'; +const METADATA_HOST = 'http://metadata.google.internal'; + +interface Received { + method: string; + url: string; + headers: http.IncomingHttpHeaders; +} + +describe('gcpMetadata', () => { + const servers: http.Server[] = []; + let requested: string[]; + + async function listen( + respond: (res: http.ServerResponse) => void, + ): Promise<{ baseUrl: string; received: Received[] }> { + const received: Received[] = []; + const server = http.createServer((req, res) => { + received.push({ + method: req.method ?? '', + url: req.url ?? '', + headers: req.headers, + }); + respond(res); + }); + servers.push(server); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + const { port } = server.address() as AddressInfo; + + return { baseUrl: `http://127.0.0.1:${port}`, received }; + } + + /** + * Points the metadata host at a local server. The provider has no setting + * for its base URL, so the test moves the host under it: the request the + * provider builds is sent unchanged apart from the origin, and anything + * that is not for the metadata host fails the test. + */ + async function metadataServer(respond: (res: http.ServerResponse) => void) { + const mock = await listen(respond); + const realFetch = globalThis.fetch; + + jest.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { + const url = String(input); + requested.push(url); + + if (!url.startsWith(`${METADATA_HOST}/`)) { + throw new Error(`Unexpected request to ${url}`); + } + + return realFetch(mock.baseUrl + url.slice(METADATA_HOST.length), init); + }); + + return mock; + } + + const text = (status: number, body: string) => (res: http.ServerResponse) => { + res.writeHead(status, { 'content-type': 'text/plain' }); + res.end(body); + }; + + beforeEach(() => { + requested = []; + }); + + afterEach(async () => { + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((done) => server.close(done)); + } + }); + + it('WIF-GCP-01: requests an identity token for the audience from the metadata server and returns the body', async () => { + const { received } = await metadataServer(text(200, 'gcp-jwt\n')); + + await expect(gcpMetadata(AUDIENCE)()).resolves.toBe('gcp-jwt'); + + expect(requested).toEqual([ + 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https%3A%2F%2Fapi.workos.com&format=full', + ]); + expect(received).toHaveLength(1); + expect(received[0].method).toBe('GET'); + expect(received[0].url).toBe( + '/computeMetadata/v1/instance/service-accounts/default/identity?audience=https%3A%2F%2Fapi.workos.com&format=full', + ); + expect(received[0].headers['metadata-flavor']).toBe('Google'); + }); + + it('WIF-GCP-02: a non-200 response or an empty body is an error, and no redirect is followed', async () => { + await metadataServer(text(404, 'not found')); + await expect(gcpMetadata(AUDIENCE)()).rejects.toThrow('status 404'); + + jest.restoreAllMocks(); + await metadataServer(text(200, ' \n')); + await expect(gcpMetadata(AUDIENCE)()).rejects.toThrow('empty token'); + + jest.restoreAllMocks(); + const target = await listen(text(200, 'redirected-jwt')); + const { received } = await metadataServer((res) => + res.writeHead(302, { location: `${target.baseUrl}/identity` }).end(), + ); + await expect(gcpMetadata(AUDIENCE)()).rejects.toThrow('status 302'); + expect(received).toHaveLength(1); + expect(target.received).toHaveLength(0); + }); + + it('percent-encodes the audience', async () => { + const { received } = await metadataServer(text(200, 'gcp-jwt')); + + await gcpMetadata('api://workos/a b&c')(); + + expect(received[0].url).toBe( + '/computeMetadata/v1/instance/service-accounts/default/identity?audience=api%3A%2F%2Fworkos%2Fa%20b%26c&format=full', + ); + }); + + it('requires an audience', () => { + expect(() => gcpMetadata('')).toThrow('an audience is required'); + }); +}); diff --git a/packages/workload-identity-gcp/src/index.ts b/packages/workload-identity-gcp/src/index.ts new file mode 100644 index 000000000..4ba525989 --- /dev/null +++ b/packages/workload-identity-gcp/src/index.ts @@ -0,0 +1,53 @@ +// @oagen-ignore-file +const REQUEST_TIMEOUT_MS = 10_000; + +const IDENTITY_URL = + 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity'; + +/** + * An identity token provider for Google Cloud. Each call asks the metadata + * server for an identity token of the default service account, with the + * given audience. + * + * Works wherever the metadata server is reachable: Compute Engine, GKE, + * Cloud Run, Cloud Functions and App Engine. + * + * @param audience - The audience the token is requested for. It must match + * the audience of the trust rule, conventionally `https://api.workos.com`. + * + * @example + * new WorkloadIdentityCredentials({ + * identityTokenProvider: gcpMetadata('https://api.workos.com'), + * }); + */ +export function gcpMetadata(audience: string): () => Promise { + if (!audience) { + throw new TypeError('gcpMetadata: an audience is required.'); + } + + return async () => { + const response = await fetch( + `${IDENTITY_URL}?audience=${encodeURIComponent(audience)}&format=full`, + { + headers: { 'Metadata-Flavor': 'Google' }, + redirect: 'manual', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }, + ); + + if (response.status !== 200) { + await response.body?.cancel().catch(() => undefined); + throw new Error( + `The GCP metadata server responded with status ${response.status}.`, + ); + } + + const token = (await response.text()).trim(); + + if (!token) { + throw new Error('The GCP metadata server returned an empty token.'); + } + + return token; + }; +} diff --git a/packages/workload-identity-gcp/tsconfig.json b/packages/workload-identity-gcp/tsconfig.json new file mode 100644 index 000000000..1b551f4e9 --- /dev/null +++ b/packages/workload-identity-gcp/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "lib" + }, + "include": ["src"] +} diff --git a/packages/workload-identity-gcp/tsdown.config.ts b/packages/workload-identity-gcp/tsdown.config.ts new file mode 100644 index 000000000..12418f44d --- /dev/null +++ b/packages/workload-identity-gcp/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/index.ts'], + dts: true, + format: ['esm', 'cjs'], + outDir: 'lib', + clean: true, + sourcemap: true, + exports: true, + publint: true, + attw: { profile: 'node16' }, +}); diff --git a/packages/workload-identity-github-actions/CHANGELOG.md b/packages/workload-identity-github-actions/CHANGELOG.md new file mode 100644 index 000000000..825c32f0d --- /dev/null +++ b/packages/workload-identity-github-actions/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/workload-identity-github-actions/LICENSE b/packages/workload-identity-github-actions/LICENSE new file mode 100644 index 000000000..656ceca82 --- /dev/null +++ b/packages/workload-identity-github-actions/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 WorkOS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/workload-identity-github-actions/README.md b/packages/workload-identity-github-actions/README.md new file mode 100644 index 000000000..e86651bd9 --- /dev/null +++ b/packages/workload-identity-github-actions/README.md @@ -0,0 +1,36 @@ +# @workos-inc/workload-identity-github-actions + +A GitHub Actions identity token provider for [WorkOS workload identity](https://github.com/workos/workos-node#workload-identity). A workflow authenticates to the WorkOS API with its own OIDC token, so no API key is stored in the repository's secrets. + +## Installation + +``` +npm install @workos-inc/node @workos-inc/workload-identity-github-actions +``` + +## Usage + +The job needs permission to request an OIDC token: + +```yaml +permissions: + id-token: write +``` + +```ts +import { WorkOS, WorkloadIdentityCredentials } from '@workos-inc/node'; +import { githubActions } from '@workos-inc/workload-identity-github-actions'; + +const workos = new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + clientId: 'client_...', + tokenUrl: 'https:///oauth2/token', + environmentId: 'environment_...', + identityTokenProvider: githubActions('https://api.workos.com'), + }), +}); +``` + +`githubActions(audience)` returns a function that requests a token from the runner on every call. The audience must match the audience of the trust rule on the WorkOS application. + +The package has no dependencies and does not depend on `@workos-inc/node`. diff --git a/packages/workload-identity-github-actions/jest.config.cjs b/packages/workload-identity-github-actions/jest.config.cjs new file mode 100644 index 000000000..70770125b --- /dev/null +++ b/packages/workload-identity-github-actions/jest.config.cjs @@ -0,0 +1,12 @@ +module.exports = { + clearMocks: true, + resetMocks: true, + restoreMocks: true, + verbose: true, + testEnvironment: 'node', + roots: ['/src'], + transform: { + // The repository's shared Babel transform. + '^.+\\.m?[jt]s$': '/../../jest-transform-esm.cjs', + }, +}; diff --git a/packages/workload-identity-github-actions/package.json b/packages/workload-identity-github-actions/package.json new file mode 100644 index 000000000..9594e984d --- /dev/null +++ b/packages/workload-identity-github-actions/package.json @@ -0,0 +1,52 @@ +{ + "name": "@workos-inc/workload-identity-github-actions", + "version": "0.0.0", + "description": "GitHub Actions identity token provider for WorkOS workload identity", + "keywords": [ + "workos", + "workload-identity", + "github-actions", + "oidc" + ], + "homepage": "https://github.com/workos/workos-node/tree/main/packages/workload-identity-github-actions", + "bugs": { + "url": "https://github.com/workos/workos-node/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/workos/workos-node.git", + "directory": "packages/workload-identity-github-actions" + }, + "license": "MIT", + "author": "WorkOS", + "type": "module", + "files": [ + "lib/" + ], + "scripts": { + "build": "tsdown", + "clean": "rm -rf lib", + "format": "prettier \"src/**/*.ts\" --write", + "lint": "eslint", + "prepublishOnly": "npm run build", + "prettier": "prettier \"src/**/*.ts\" --check", + "test": "jest", + "typecheck": "tsc --noEmit" + }, + "engines": { + "node": ">=22.11.0" + }, + "publishConfig": { + "access": "public" + }, + "main": "./lib/index.cjs", + "module": "./lib/index.mjs", + "types": "./lib/index.d.cts", + "exports": { + ".": { + "import": "./lib/index.mjs", + "require": "./lib/index.cjs" + }, + "./package.json": "./package.json" + } +} diff --git a/packages/workload-identity-github-actions/src/index.spec.ts b/packages/workload-identity-github-actions/src/index.spec.ts new file mode 100644 index 000000000..65a2a2150 --- /dev/null +++ b/packages/workload-identity-github-actions/src/index.spec.ts @@ -0,0 +1,151 @@ +// @oagen-ignore-file +import http from 'node:http'; +import { AddressInfo } from 'node:net'; +import { githubActions } from './index'; + +const AUDIENCE = 'https://api.workos.com'; + +interface Received { + method: string; + url: string; + headers: http.IncomingHttpHeaders; +} + +describe('githubActions', () => { + const OLD_ENV = process.env; + const servers: http.Server[] = []; + + /** A local stand-in for the runner's OIDC endpoint. */ + async function listen( + respond: (res: http.ServerResponse) => void, + ): Promise<{ baseUrl: string; received: Received[] }> { + const received: Received[] = []; + const server = http.createServer((req, res) => { + received.push({ + method: req.method ?? '', + url: req.url ?? '', + headers: req.headers, + }); + respond(res); + }); + servers.push(server); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + const { port } = server.address() as AddressInfo; + + return { baseUrl: `http://127.0.0.1:${port}`, received }; + } + + const json = + (status: number, body: unknown) => (res: http.ServerResponse) => { + res.writeHead(status, { 'content-type': 'application/json' }); + res.end(JSON.stringify(body)); + }; + + beforeEach(() => { + process.env = { ...OLD_ENV }; + delete process.env.ACTIONS_ID_TOKEN_REQUEST_URL; + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'gha-request-token'; + }); + + afterEach(async () => { + process.env = OLD_ENV; + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((done) => server.close(done)); + } + }); + + it('WIF-GHA-01: requests a token for the audience with the request token and returns its value', async () => { + const { baseUrl, received } = await listen(json(200, { value: 'gha-jwt' })); + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token?api-version=2.0`; + + await expect(githubActions(AUDIENCE)()).resolves.toBe('gha-jwt'); + + expect(received).toHaveLength(1); + expect(received[0].method).toBe('GET'); + expect(received[0].url).toBe( + '/token?api-version=2.0&audience=https%3A%2F%2Fapi.workos.com', + ); + expect(received[0].headers.authorization).toBe('Bearer gha-request-token'); + expect(received[0].headers.accept).toBe('application/json'); + }); + + it('WIF-GHA-02: missing environment variables fail with the permission hint', async () => { + const fetchSpy = jest.spyOn(globalThis, 'fetch'); + const { baseUrl, received } = await listen(json(200, { value: 'gha-jwt' })); + const provider = githubActions(AUDIENCE); + + // No request URL. + await expect(provider()).rejects.toThrow('permissions: id-token: write'); + + // No request token. + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token?api-version=2.0`; + delete process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + await expect(provider()).rejects.toThrow('permissions: id-token: write'); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(received).toHaveLength(0); + }); + + it('reads the environment on every call', async () => { + const { baseUrl } = await listen(json(200, { value: 'gha-jwt' })); + const provider = githubActions(AUDIENCE); + + await expect(provider()).rejects.toThrow('permissions: id-token: write'); + + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token`; + await expect(provider()).resolves.toBe('gha-jwt'); + }); + + it('adds a query string when the request URL has none', async () => { + const { baseUrl, received } = await listen(json(200, { value: 'gha-jwt' })); + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token`; + + await githubActions('api://workos/a b')(); + + expect(received[0].url).toBe('/token?audience=api%3A%2F%2Fworkos%2Fa%20b'); + }); + + it('fails on a status other than 200, naming the status', async () => { + const { baseUrl } = await listen(json(404, { message: 'not found' })); + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token`; + + await expect(githubActions(AUDIENCE)()).rejects.toThrow('status 404'); + }); + + it.each([ + ['no value', json(200, {})], + ['an empty value', json(200, { value: '' })], + [ + 'a body that is not JSON', + (res: http.ServerResponse) => res.writeHead(200).end('gha-jwt'), + ], + ])( + 'fails on a response with %s, without quoting it', + async (_name, respond) => { + const { baseUrl } = await listen(respond); + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token`; + + const error = await githubActions(AUDIENCE)().catch((e) => e); + + expect(error.message).toBe( + 'The GitHub Actions OIDC token response did not include a token.', + ); + }, + ); + + it('does not follow a redirect', async () => { + const target = await listen(json(200, { value: 'redirected-jwt' })); + const { baseUrl } = await listen((res) => + res.writeHead(302, { location: `${target.baseUrl}/token` }).end(), + ); + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = `${baseUrl}/token`; + + await expect(githubActions(AUDIENCE)()).rejects.toThrow('status 302'); + expect(target.received).toHaveLength(0); + }); + + it('requires an audience', () => { + expect(() => githubActions('')).toThrow('an audience is required'); + }); +}); diff --git a/packages/workload-identity-github-actions/src/index.ts b/packages/workload-identity-github-actions/src/index.ts new file mode 100644 index 000000000..e9375cebf --- /dev/null +++ b/packages/workload-identity-github-actions/src/index.ts @@ -0,0 +1,71 @@ +// @oagen-ignore-file +const REQUEST_TIMEOUT_MS = 10_000; + +/** + * An identity token provider for GitHub Actions. Each call asks the runner's + * OIDC endpoint for a token with the given audience. + * + * The job needs `permissions: id-token: write`. + * + * @param audience - The audience the token is requested for. It must match + * the audience of the trust rule, conventionally `https://api.workos.com`. + * + * @example + * new WorkloadIdentityCredentials({ + * identityTokenProvider: githubActions('https://api.workos.com'), + * }); + */ +export function githubActions(audience: string): () => Promise { + if (!audience) { + throw new TypeError('githubActions: an audience is required.'); + } + + return async () => { + // Read on every call. Both are set only for a job that may request a token. + const requestUrl = readEnv('ACTIONS_ID_TOKEN_REQUEST_URL'); + const requestToken = readEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN'); + + if (!requestUrl || !requestToken) { + throw new Error( + 'GitHub Actions did not provide an OIDC token endpoint. Add `permissions: id-token: write` to the workflow or job.', + ); + } + + // The URL already has a query string; add to it. + const separator = requestUrl.includes('?') ? '&' : '?'; + const response = await fetch( + `${requestUrl}${separator}audience=${encodeURIComponent(audience)}`, + { + headers: { + Authorization: `Bearer ${requestToken}`, + Accept: 'application/json', + }, + redirect: 'manual', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }, + ); + + if (response.status !== 200) { + await response.body?.cancel().catch(() => undefined); + throw new Error( + `The GitHub Actions OIDC token request failed with status ${response.status}.`, + ); + } + + // The body holds the token, so a body that cannot be read is never quoted. + const body: unknown = await response.json().catch(() => undefined); + const token = (body as { value?: unknown } | undefined)?.value; + + if (typeof token !== 'string' || !token) { + throw new Error( + 'The GitHub Actions OIDC token response did not include a token.', + ); + } + + return token; + }; +} + +function readEnv(name: string): string | undefined { + return typeof process === 'undefined' ? undefined : process.env?.[name]; +} diff --git a/packages/workload-identity-github-actions/tsconfig.json b/packages/workload-identity-github-actions/tsconfig.json new file mode 100644 index 000000000..1b551f4e9 --- /dev/null +++ b/packages/workload-identity-github-actions/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "lib" + }, + "include": ["src"] +} diff --git a/packages/workload-identity-github-actions/tsdown.config.ts b/packages/workload-identity-github-actions/tsdown.config.ts new file mode 100644 index 000000000..12418f44d --- /dev/null +++ b/packages/workload-identity-github-actions/tsdown.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/index.ts'], + dts: true, + format: ['esm', 'cjs'], + outDir: 'lib', + clean: true, + sourcemap: true, + exports: true, + publint: true, + attw: { profile: 'node16' }, +}); diff --git a/release-please-config.json b/release-please-config.json index 637e606c0..3116553dc 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,11 +1,40 @@ { "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", "include-component-in-tag": false, + "separate-pull-requests": true, + "plugins": [ + { + "type": "node-workspace", + "merge": false + } + ], "packages": { ".": { "release-type": "node", "changelog-path": "CHANGELOG.md", - "versioning": "default" + "versioning": "default", + "exclude-paths": ["packages"] + }, + "packages/workload-identity-github-actions": { + "release-type": "node", + "component": "@workos-inc/workload-identity-github-actions", + "package-name": "@workos-inc/workload-identity-github-actions", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" + }, + "packages/workload-identity-gcp": { + "release-type": "node", + "component": "@workos-inc/workload-identity-gcp", + "package-name": "@workos-inc/workload-identity-gcp", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" + }, + "packages/workload-identity-aws": { + "release-type": "node", + "component": "@workos-inc/workload-identity-aws", + "package-name": "@workos-inc/workload-identity-aws", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" } } } diff --git a/scripts/ci b/scripts/ci index 76e3defa5..40dcbe72d 100755 --- a/scripts/ci +++ b/scripts/ci @@ -15,3 +15,20 @@ npm run build echo "==> Test" npm run test + +# Every package under packages/ is released on its own, so each one is +# checked on its own. The steps above only cover the SDK. +echo "==> Packages: Prettier" +npm run prettier --workspaces --if-present + +echo "==> Packages: Lint" +npm run lint --workspaces --if-present + +echo "==> Packages: Typecheck" +npm run typecheck --workspaces --if-present + +echo "==> Packages: Build" +npm run build --workspaces --if-present + +echo "==> Packages: Test" +npm run test --workspaces --if-present diff --git a/src/common/interfaces/workos-options.interface.ts b/src/common/interfaces/workos-options.interface.ts index deaffc74b..51276dc5b 100644 --- a/src/common/interfaces/workos-options.interface.ts +++ b/src/common/interfaces/workos-options.interface.ts @@ -1,7 +1,15 @@ +import type { Credentials } from '../net/credentials'; import { AppInfo } from './app-info.interface'; export interface WorkOSOptions { apiKey?: string; + /** + * Authorizes API requests in place of an API key, for example + * `WorkloadIdentityCredentials`. Passing both `apiKey` and `credentials` + * is an error. When set, the `WORKOS_API_KEY` environment variable is + * ignored. + */ + credentials?: Credentials; apiHostname?: string; https?: boolean; port?: number; diff --git a/src/common/net/credentials.ts b/src/common/net/credentials.ts new file mode 100644 index 000000000..21f14c72d --- /dev/null +++ b/src/common/net/credentials.ts @@ -0,0 +1,60 @@ +// @oagen-ignore-file + +/** + * What a caller passes to {@link Credentials.resolve}. + */ +export interface CredentialContext { + /** + * Stops this caller from waiting. It never cancels work that other callers + * share, such as a token exchange already in progress. + */ + signal?: AbortSignal; +} + +/** + * The authorization headers for one HTTP attempt, and the credential they + * came from. + */ +export interface CredentialSnapshot { + /** Headers to set on the attempt. They replace any header of the same name. */ + readonly headers: Readonly>; + /** Opaque. Identifies the credential these headers came from. */ + readonly generation: number; + /** Whether a 401 on this snapshot is worth one more `resolve`. */ + readonly recoverable: boolean; +} + +/** + * How a client authorizes its API requests. The client resolves a snapshot + * before every HTTP attempt and, on a 401, invalidates the generation that + * attempt used. + */ +export interface Credentials { + resolve(context?: CredentialContext): Promise; + /** Never waits on the network. */ + invalidate(generation: number): void; +} + +/** + * A static API key: the same header on every attempt, and nothing to recover + * when the API rejects it. + */ +export class StaticKeyCredentials implements Credentials { + private readonly snapshot: CredentialSnapshot; + + constructor(key: string) { + this.snapshot = { + headers: { Authorization: `Bearer ${key}` }, + generation: 0, + recoverable: false, + }; + } + + resolve(): Promise { + return Promise.resolve(this.snapshot); + } + + invalidate(): void { + // A static key has no newer credential to fetch. + } +} diff --git a/src/common/net/fetch-client.ts b/src/common/net/fetch-client.ts index 1b76c4f41..96d63494b 100644 --- a/src/common/net/fetch-client.ts +++ b/src/common/net/fetch-client.ts @@ -13,20 +13,48 @@ import { HttpClientResponse, } from './http-client'; import { ParseError } from '../exceptions/parse-error'; +import type { Credentials, CredentialSnapshot } from './credentials'; type FetchHttpClientOptions = HttpClientOptions; +/** + * Settings the SDK sets itself. Kept apart from {@link HttpClientOptions}, + * which carries the caller's `config`, so nothing a caller passes there can + * change them. + */ +export interface FetchHttpClientSettings { + /** + * Resolved before every HTTP attempt. The snapshot's headers authorize that + * attempt. + */ + credentials?: Credentials; + /** Passed to `fetch`. Unset keeps the runtime's default. */ + redirect?: RequestRedirect; +} + +/** What one HTTP attempt reports back to the retry loop. */ +interface AttemptState { + /** The credential snapshot the attempt was sent with, when it had one. */ + snapshot?: CredentialSnapshot; +} + const DEFAULT_FETCH_TIMEOUT = 60_000; // 60 seconds export class FetchHttpClient extends HttpClient implements HttpClientInterface { private readonly _fetchFn; + private readonly credentials?: Credentials; + private readonly redirect?: RequestRedirect; constructor( readonly baseURL: string, readonly options?: FetchHttpClientOptions, fetchFn?: typeof fetch, + settings: FetchHttpClientSettings = {}, ) { super(baseURL, options); + this.credentials = settings.credentials; + this.redirect = settings.redirect; + // Default to global fetch if available if (!fetchFn) { if (!globalThis.fetch) { @@ -175,6 +203,7 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { method: string, body?: any, headers?: RequestHeaders, + attempt?: AttemptState, ): Promise { // For methods which expect payloads, we should always pass a body value // even when it is empty. Without this, some JS runtimes (eg. Deno) will @@ -208,17 +237,32 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { let res: Response | undefined; try { + // Resolved for every attempt, under the attempt's deadline, so a retry + // never sends a token that expired while the request was backing off. + const resolving = this.resolveCredentials( + headers, + abortController.signal, + ); + const snapshot = resolving ? await resolving : undefined; + if (attempt) { + attempt.snapshot = snapshot; + } + res = await this._fetchFn(url, { method, - headers: { - Accept: 'application/json, text/plain, */*', - 'Content-Type': 'application/json', - ...this.options?.headers, - ...headers, - 'User-Agent': (userAgent || 'workos-node').toString(), - }, + headers: FetchHttpClient.withCredentialHeaders( + { + Accept: 'application/json, text/plain, */*', + 'Content-Type': 'application/json', + ...this.options?.headers, + ...headers, + 'User-Agent': (userAgent || 'workos-node').toString(), + }, + snapshot, + ), body: requestBody, signal: abortController.signal, + ...(this.redirect && { redirect: this.redirect }), }); if (!res.ok) { @@ -313,16 +357,49 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { let response: HttpClientResponseInterface; let retryAttempts = 1; + // One 401 recovery per logical request. It is set once and never cleared, + // however many transport retries follow. + let recoveryUsed = false; const makeRequest = async (): Promise => { let requestError: any = null; + const attempt: AttemptState = {}; try { - response = await this.fetchRequest(url, method, body, requestHeaders); + response = await this.fetchRequest( + url, + method, + body, + requestHeaders, + attempt, + ); } catch (e) { requestError = e; } + // The API rejected a credential that can be replaced. Invalidate the + // generation this attempt used (never "the current one") and resend the + // same request once: no backoff, and it does not count as a retry. The + // resend resolves again, reusing a newer token or joining the one + // shared exchange. Whatever comes back is handled as usual below. + if ( + !recoveryUsed && + this.credentials && + attempt.snapshot?.recoverable && + FetchHttpClient.isUnauthorized(requestError) && + FetchHttpClient.isReplayable(body) + ) { + recoveryUsed = true; + this.credentials.invalidate(attempt.snapshot.generation); + requestError = null; + + try { + response = await this.fetchRequest(url, method, body, requestHeaders); + } catch (e) { + requestError = e; + } + } + if ( this.shouldRetryRequest(requestError, retryAttempts, maxRetryAttempts) ) { @@ -379,6 +456,70 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { return false; } + /** + * The snapshot that authorizes this attempt, or nothing when the client has + * no credentials or the request carries its own `Authorization` header. A + * per-request access token keeps its precedence over the client's + * credentials, and a 401 on it is not recovered. + */ + private resolveCredentials( + headers: RequestHeaders | undefined, + signal: AbortSignal, + ): Promise | undefined { + if ( + !this.credentials || + FetchHttpClient.hasHeader(headers, 'Authorization') + ) { + return undefined; + } + + return this.credentials.resolve({ signal }); + } + + /** + * Sets the snapshot's headers, replacing any header of the same name + * whatever its casing. + */ + private static withCredentialHeaders>( + headers: T, + snapshot: CredentialSnapshot | undefined, + ): T { + if (!snapshot) { + return headers; + } + + const merged: Record = headers; + + for (const [name, value] of Object.entries(snapshot.headers)) { + const target = name.toLowerCase(); + + for (const existing of Object.keys(merged)) { + if (existing.toLowerCase() === target) { + delete merged[existing]; + } + } + + merged[name] = value; + } + + return headers; + } + + private static isUnauthorized(requestError: unknown): boolean { + return ( + (requestError instanceof HttpClientError && + requestError.response.status === 401) || + (requestError instanceof ParseError && requestError.rawStatus === 401) + ); + } + + /** A stream can be read once, so a request with one cannot be sent again. */ + private static isReplayable(body: unknown): boolean { + return !( + typeof ReadableStream !== 'undefined' && body instanceof ReadableStream + ); + } + private static withIdempotencyKey( method: string, headers: RequestHeaders | undefined, diff --git a/src/index.ts b/src/index.ts index f00652919..8808f4df5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,6 +38,9 @@ export { CookieSession } from './user-management/session'; export * from './vault/interfaces'; export * from './webhooks/interfaces'; export * from './widgets/interfaces'; +export * from './workload-identity'; +// Reads the file system, so it is not part of the worker entry. +export { tokenFile } from './workload-identity/token-file'; export * from './pkce/pkce'; export { createWorkOS, @@ -66,10 +69,6 @@ class WorkOSNode extends WorkOS { headers['User-Agent'] = userAgent; - if (this.key) { - headers['Authorization'] = `Bearer ${this.key}`; - } - const opts = { ...options.config, timeout: options.timeout, @@ -77,7 +76,9 @@ class WorkOSNode extends WorkOS { headers, }; - return new FetchHttpClient(this.baseURL, opts, options.fetchFn); + return new FetchHttpClient(this.baseURL, opts, options.fetchFn, { + credentials: this.requestCredentials, + }); } /** @override */ diff --git a/src/index.worker.ts b/src/index.worker.ts index f1b0b4bbb..416de09fd 100644 --- a/src/index.worker.ts +++ b/src/index.worker.ts @@ -23,6 +23,7 @@ export * from './admin-portal/interfaces'; export * from './sso/interfaces'; export * from './user-management/interfaces'; export * from './roles/interfaces'; +export * from './workload-identity'; export * from './pkce/pkce'; export { createWorkOS, @@ -50,15 +51,16 @@ class WorkOSWorker extends WorkOS { Object.assign(headers, configHeaders); } - if (this.key) { - headers['Authorization'] = `Bearer ${this.key}`; - } - - return new FetchHttpClient(this.baseURL, { - ...options.config, - maxRetries: options.maxRetries, - headers, - }); + return new FetchHttpClient( + this.baseURL, + { + ...options.config, + maxRetries: options.maxRetries, + headers, + }, + undefined, + { credentials: this.requestCredentials }, + ); } /** @override */ diff --git a/src/workload-identity/constants.ts b/src/workload-identity/constants.ts new file mode 100644 index 000000000..d6fa8d5f9 --- /dev/null +++ b/src/workload-identity/constants.ts @@ -0,0 +1,25 @@ +// @oagen-ignore-file + +/** Sent with the environment ID on every workload identity API request. */ +export const ENVIRONMENT_ID_HEADER = 'x-url-environment-id'; + +export const JWT_BEARER_GRANT_TYPE = + 'urn:ietf:params:oauth:grant-type:jwt-bearer'; + +export const DEFAULT_RESOURCE = 'https://api.workos.com'; + +/** Used when the token response has no usable `expires_in`. */ +export const DEFAULT_TOKEN_LIFETIME_SECONDS = 300; + +/** + * A token is replaced once less than `min(60 seconds, 20% of its lifetime)` + * remains. + */ +export const REFRESH_THRESHOLD_MAX_MS = 60_000; +export const REFRESH_THRESHOLD_LIFETIME_FRACTION = 0.2; + +/** Bounds one whole exchange, including its retries and backoff. */ +export const EXCHANGE_DEADLINE_MS = 30_000; + +/** The server's `error_description` is cut to this many characters. */ +export const ERROR_DESCRIPTION_LIMIT = 500; diff --git a/src/workload-identity/index.ts b/src/workload-identity/index.ts new file mode 100644 index 000000000..086a519a7 --- /dev/null +++ b/src/workload-identity/index.ts @@ -0,0 +1,15 @@ +// @oagen-ignore-file +// Everything here is safe for edge runtimes. `tokenFile` needs a file system +// and is exported from the Node entry (`src/index.ts`) only. +export type { + CredentialContext, + Credentials, + CredentialSnapshot, +} from '../common/net/credentials'; +export { tokenEnv } from './token-env'; +export { + WorkloadIdentityCredentials, + type IdentityTokenProvider, + type WorkloadIdentityCredentialsOptions, +} from './workload-identity-credentials'; +export { WorkloadIdentityError } from './workload-identity-error'; diff --git a/src/workload-identity/token-env.ts b/src/workload-identity/token-env.ts new file mode 100644 index 000000000..aca705d32 --- /dev/null +++ b/src/workload-identity/token-env.ts @@ -0,0 +1,26 @@ +// @oagen-ignore-file +import { getEnv } from '../common/utils/env'; +import type { IdentityTokenProvider } from './workload-identity-credentials'; + +/** + * An identity token provider that reads the token from an environment + * variable on every call. + * + * @example + * new WorkloadIdentityCredentials({ + * identityTokenProvider: tokenEnv('MY_PLATFORM_JWT'), + * }); + */ +export function tokenEnv(name: string): IdentityTokenProvider { + return async () => { + const token = getEnv(name)?.trim(); + + if (!token) { + throw new Error( + `The environment variable ${name} is not set or is empty.`, + ); + } + + return token; + }; +} diff --git a/src/workload-identity/token-file.ts b/src/workload-identity/token-file.ts new file mode 100644 index 000000000..154d589d6 --- /dev/null +++ b/src/workload-identity/token-file.ts @@ -0,0 +1,62 @@ +// @oagen-ignore-file +import type { IdentityTokenProvider } from './workload-identity-credentials'; + +type FileSystem = typeof import('node:fs/promises'); + +/** + * The runtime's file system module, reached without an `import`. + * + * The Node entry is also what a browser bundler resolves for a public client, + * so a static `node:` import would break that build, and webpack cannot load + * a computed `import()`. `process.getBuiltinModule` is plain property access: + * no bundler traces or rewrites it. Node.js 22.3 and later, Deno and Bun all + * have it. + */ +function fileSystem(): FileSystem { + const fs = + typeof process !== 'undefined' && + typeof process.getBuiltinModule === 'function' + ? (process.getBuiltinModule('node:fs/promises') as FileSystem | undefined) + : undefined; + + if (!fs) { + throw new Error('This runtime has no file system.'); + } + + return fs; +} + +/** + * An identity token provider that reads the token from a file on every call, + * so a rotated token is picked up by the next exchange. Surrounding + * whitespace is trimmed. + * + * Needs a file system, so it is exported from the Node entry only and not + * from `@workos-inc/node/worker`. + * + * @example + * new WorkloadIdentityCredentials({ + * identityTokenProvider: tokenFile('/var/run/secrets/tokens/workos'), + * }); + */ +export function tokenFile(path: string): IdentityTokenProvider { + return async () => { + let contents: string; + + try { + contents = await fileSystem().readFile(path, 'utf8'); + } catch (error) { + throw new Error(`The identity token file ${path} could not be read.`, { + cause: error, + }); + } + + const token = contents.trim(); + + if (!token) { + throw new Error(`The identity token file ${path} is empty.`); + } + + return token; + }; +} diff --git a/src/workload-identity/workload-identity-credentials.ts b/src/workload-identity/workload-identity-credentials.ts new file mode 100644 index 000000000..e398920c3 --- /dev/null +++ b/src/workload-identity/workload-identity-credentials.ts @@ -0,0 +1,638 @@ +// @oagen-ignore-file +import { version as VERSION } from '../../package.json' with { type: 'json' }; +import { ParseError } from '../common/exceptions/parse-error'; +import type { HttpClientResponseInterface } from '../common/interfaces/http-client.interface'; +import type { + CredentialContext, + Credentials, + CredentialSnapshot, +} from '../common/net/credentials'; +import { FetchHttpClient } from '../common/net/fetch-client'; +import { + DEFAULT_MAX_RETRY_ATTEMPTS, + HttpClient, + HttpClientError, +} from '../common/net/http-client'; +import { getEnv } from '../common/utils/env'; +import { + DEFAULT_RESOURCE, + DEFAULT_TOKEN_LIFETIME_SECONDS, + ENVIRONMENT_ID_HEADER, + EXCHANGE_DEADLINE_MS, + JWT_BEARER_GRANT_TYPE, + REFRESH_THRESHOLD_LIFETIME_FRACTION, + REFRESH_THRESHOLD_MAX_MS, +} from './constants'; +import { WorkloadIdentityError } from './workload-identity-error'; + +/** + * Returns the workload's identity token, a JWT issued by the platform the + * workload runs on. It is called again for every exchange attempt, so it + * should hold no cache of its own and must never log the token. + */ +export type IdentityTokenProvider = () => Promise; + +export interface WorkloadIdentityCredentialsOptions { + /** The M2M application's client ID. Defaults to `WORKOS_CLIENT_ID`. */ + clientId?: string; + /** + * The token exchange endpoint. Defaults to `WORKOS_WIF_TOKEN_URL`. There is + * no built-in default. + */ + tokenUrl?: string; + /** + * The environment the workload acts on, sent with every API request. + * Defaults to `WORKOS_ENVIRONMENT_ID`. + */ + environmentId?: string; + /** The API the access token is for. Defaults to `https://api.workos.com`. */ + resource?: string; + /** The scope to request. Defaults to `WORKOS_WIF_SCOPE`, else no scope. */ + scope?: string; + /** Returns the workload's identity token. */ + identityTokenProvider: IdentityTokenProvider; +} + +/** + * Test seams. Not part of the public API. + * + * @internal + */ +export interface WorkloadIdentityInternals { + /** The clock the token cache reads, in milliseconds. */ + now?: () => number; + /** Waits before an exchange retry. Same contract as `HttpClient#sleep`. */ + sleep?: ( + retryAttempt: number, + retryAfterMs?: number | null, + ) => Promise; +} + +interface CachedToken { + token: string; + generation: number; + lifetimeMs: number; + expiresAt: number; +} + +interface IssuedToken { + token: string; + generation: number; +} + +interface TokenResponse { + accessToken: string; + expiresInSeconds: number; +} + +/** One exchange POST: either an HTTP response or no response at all. */ +type ExchangeAttempt = + | { + responded: true; + status: number; + body: unknown; + retryAfterMs: number | null; + } + | { responded: false; error: unknown }; + +/** + * Authorizes API requests with a short-lived WorkOS access token, obtained by + * exchanging the workload's identity token. No API key is stored or sent. + * + * The token is cached on this instance and replaced on demand shortly before + * it expires. Concurrent requests share one exchange. + * + * @example + * const workos = new WorkOS({ + * credentials: new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', + * environmentId: 'environment_123', + * identityTokenProvider: async () => fetchMyPlatformJwt(), + * }), + * }); + */ +export class WorkloadIdentityCredentials implements Credentials { + private readonly clientId: string; + private readonly tokenUrl: URL; + private readonly environmentId: string; + private readonly resource: string; + private readonly scope: string | undefined; + private readonly identityTokenProvider: IdentityTokenProvider; + private readonly now: () => number; + private readonly sleep: NonNullable; + + // Held by this instance only: two instances never share a token or an + // exchange, even with identical configuration. + private cache: CachedToken | undefined; + private inflight: Promise | undefined; + + /** + * @param options - Omitted fields default from the environment; an explicit + * value always wins. + * @param internals - Test seams. Not part of the public API. + * @throws {WorkloadIdentityError} `invalid_configuration` when a required + * setting is missing after the environment is consulted. + */ + constructor( + options: WorkloadIdentityCredentialsOptions, + /** @internal */ + internals: WorkloadIdentityInternals = {}, + ) { + const clientId = options?.clientId || getEnv('WORKOS_CLIENT_ID'); + const tokenUrl = options?.tokenUrl || getEnv('WORKOS_WIF_TOKEN_URL'); + const environmentId = + options?.environmentId || getEnv('WORKOS_ENVIRONMENT_ID'); + + if (!clientId) { + throw missingSetting('clientId', 'WORKOS_CLIENT_ID'); + } + if (!tokenUrl) { + throw missingSetting('tokenUrl', 'WORKOS_WIF_TOKEN_URL'); + } + if (!environmentId) { + throw missingSetting('environmentId', 'WORKOS_ENVIRONMENT_ID'); + } + if (typeof options?.identityTokenProvider !== 'function') { + throw new WorkloadIdentityError( + 'invalid_configuration', + 'identityTokenProvider is required', + ); + } + + try { + this.tokenUrl = new URL(tokenUrl); + } catch { + throw new WorkloadIdentityError( + 'invalid_configuration', + 'tokenUrl is not a valid URL', + ); + } + + if ( + this.tokenUrl.protocol !== 'https:' && + this.tokenUrl.protocol !== 'http:' + ) { + throw new WorkloadIdentityError( + 'invalid_configuration', + 'tokenUrl must be an http or https URL', + ); + } + + this.clientId = clientId; + this.environmentId = environmentId; + this.resource = options.resource || DEFAULT_RESOURCE; + this.scope = options.scope || getEnv('WORKOS_WIF_SCOPE') || undefined; + this.identityTokenProvider = options.identityTokenProvider; + this.now = internals.now ?? (() => Date.now()); + this.sleep = + internals.sleep ?? + // The SDK's own backoff, so the exchange waits exactly as API requests do. + ((retryAttempt, retryAfterMs) => + this.createExchangeClient(EXCHANGE_DEADLINE_MS).sleep( + retryAttempt, + retryAfterMs, + )); + } + + /** + * Returns the headers for one API attempt, exchanging for a new access + * token first when the cached one is missing or about to expire. + * + * @throws {WorkloadIdentityError} When the exchange fails. + */ + async resolve(context: CredentialContext = {}): Promise { + const { token, generation } = await this.currentToken(context.signal); + + return { + headers: { + Authorization: `Bearer ${token}`, + [ENVIRONMENT_ID_HEADER]: this.environmentId, + }, + generation, + recoverable: true, + }; + } + + /** + * Discards the cached token, but only if it is still the one `generation` + * names. A late 401 for an old token leaves a newer token in place. + */ + invalidate(generation: number): void { + if (this.cache?.generation === generation) { + this.cache.expiresAt = Number.NEGATIVE_INFINITY; + } + } + + private currentToken(signal?: AbortSignal): Promise { + const cache = this.cache; + + if (cache && this.isFresh(cache)) { + return Promise.resolve({ + token: cache.token, + generation: cache.generation, + }); + } + + this.inflight ??= this.startExchange(); + + // The caller holds its own reference to the exchange it joined. Giving up + // stops this caller from waiting and leaves the exchange running. + return settleUnlessAborted(this.inflight, signal, () => + abortReason(signal), + ); + } + + private isFresh(cache: CachedToken): boolean { + const threshold = Math.min( + REFRESH_THRESHOLD_MAX_MS, + REFRESH_THRESHOLD_LIFETIME_FRACTION * cache.lifetimeMs, + ); + + return cache.expiresAt - this.now() >= threshold; + } + + /** + * Starts the one shared exchange. It runs on its own deadline, tied to no + * caller. The in-flight reference is cleared before any waiter is woken, so + * a caller that gets an error and calls again starts a new exchange. + */ + private startExchange(): Promise { + const exchange = Promise.resolve() + .then(() => this.exchangeWithinDeadline()) + .then( + ({ accessToken, expiresInSeconds }) => { + const lifetimeMs = expiresInSeconds * 1000; + const generation = (this.cache?.generation ?? 0) + 1; + + this.cache = { + token: accessToken, + generation, + lifetimeMs, + expiresAt: this.now() + lifetimeMs, + }; + this.inflight = undefined; + + return { token: accessToken, generation }; + }, + (error) => { + // A failed exchange is not cached. + this.inflight = undefined; + throw error; + }, + ); + + // Every waiter may have given up by the time this settles. + exchange.catch(() => undefined); + + return exchange; + } + + private async exchangeWithinDeadline(): Promise { + const deadline = new AbortController(); + const timer = setTimeout(() => deadline.abort(), EXCHANGE_DEADLINE_MS); + + try { + return await this.exchange( + deadline.signal, + Date.now() + EXCHANGE_DEADLINE_MS, + ); + } finally { + clearTimeout(timer); + } + } + + /** + * The jwt-bearer exchange. Retries when the provider fails, when no + * response arrives, and on 429 and 5xx. The provider is called again and + * the form rebuilt on every attempt. Any other response is final. + */ + private async exchange( + deadline: AbortSignal, + deadlineAt: number, + ): Promise { + const pastDeadline = () => + new WorkloadIdentityError( + 'exchange_failed', + `The token exchange did not finish within ${EXCHANGE_DEADLINE_MS / 1000} seconds.`, + ); + + let failure = new WorkloadIdentityError('exchange_failed'); + let retryAfterMs: number | null = null; + + for (let attempt = 0; attempt <= DEFAULT_MAX_RETRY_ATTEMPTS; attempt++) { + if (attempt > 0) { + // Numbered as the SDK's request loop numbers its retries. A wait the + // server asked for never runs past the deadline. + await settleUnlessAborted( + this.sleep( + attempt + 1, + retryAfterMs === null + ? null + : Math.min(retryAfterMs, Math.max(0, deadlineAt - Date.now())), + ), + deadline, + pastDeadline, + ); + retryAfterMs = null; + } + + let assertion: string; + + try { + assertion = await settleUnlessAborted( + Promise.resolve().then(() => this.identityTokenProvider()), + deadline, + pastDeadline, + ); + } catch (error) { + if (deadline.aborted) { + throw pastDeadline(); + } + + failure = new WorkloadIdentityError( + 'provider_failed', + error instanceof Error ? error.message : '', + { cause: error }, + ); + continue; + } + + if (typeof assertion !== 'string' || assertion.trim() === '') { + failure = new WorkloadIdentityError( + 'provider_failed', + 'The identity token provider returned an empty token.', + ); + continue; + } + + const form = new URLSearchParams({ + grant_type: JWT_BEARER_GRANT_TYPE, + assertion, + client_id: this.clientId, + resource: this.resource, + }); + if (this.scope) { + form.set('scope', this.scope); + } + + const result = await settleUnlessAborted( + this.post(form, Math.max(1, deadlineAt - Date.now())), + deadline, + pastDeadline, + ); + + if (!result.responded) { + failure = new WorkloadIdentityError( + 'exchange_failed', + 'The token request did not get a response.', + { cause: result.error }, + ); + continue; + } + + const { status, body } = result; + const oauthError = readOAuthError(body); + + // The status is checked before the body: a 429 or 5xx is retried even + // when it carries an OAuth error. + if (status === 429 || (status >= 500 && status <= 599)) { + retryAfterMs = result.retryAfterMs; + failure = new WorkloadIdentityError( + oauthError?.code ?? 'exchange_failed', + oauthError?.description ?? + `The token endpoint responded with status ${status}.`, + ); + continue; + } + + if (oauthError) { + throw new WorkloadIdentityError( + oauthError.code, + oauthError.description, + ); + } + + // Status 0 is how a browser-like runtime reports an unfollowed redirect. + if (status === 0 || (status >= 300 && status <= 399)) { + throw new WorkloadIdentityError( + 'exchange_failed', + 'The token endpoint responded with a redirect. Redirects are not followed.', + ); + } + + if (status !== 200) { + throw new WorkloadIdentityError( + 'invalid_response', + `The token endpoint responded with status ${status}.`, + ); + } + + return readTokenResponse(body); + } + + throw failure; + } + + /** + * Sends one exchange POST and reports what came back. Never rejects, and + * never keeps a response body that could hold a token: only the status, the + * parsed JSON and `Retry-After` leave this method. + */ + private async post( + form: URLSearchParams, + timeout: number, + ): Promise { + try { + // The absolute URL, never a path joined to the origin: a path that + // starts with `//` would be read as another host. + const response = await this.createExchangeClient(timeout).post( + this.tokenUrl.href, + form, + { + headers: { + Accept: 'application/json', + 'Content-Type': 'application/x-www-form-urlencoded', + }, + }, + ); + + return { + responded: true, + status: response.getStatusCode(), + body: await readJson(response), + retryAfterMs: null, + }; + } catch (error) { + if (error instanceof HttpClientError) { + if (isRequestTimeout(error)) { + return { responded: false, error }; + } + + return { + responded: true, + status: error.response.status, + body: error.response.data, + retryAfterMs: HttpClient.parseRetryAfter( + error.response.headers?.get('Retry-After'), + ), + }; + } + + // An error response whose body is not JSON. + if (error instanceof ParseError) { + return { + responded: true, + status: error.rawStatus, + body: undefined, + retryAfterMs: HttpClient.parseRetryAfter( + error.rawHeaders?.get('Retry-After'), + ), + }; + } + + return { responded: false, error }; + } + } + + /** + * The SDK's HTTP client, set up for the exchange: one attempt per call (the + * exchange loop owns the retries), redirects never followed, and none of + * the API client's settings. It has no credentials, so the request carries + * no API key and no `Authorization` header. + */ + private createExchangeClient(timeout: number): FetchHttpClient { + return new FetchHttpClient( + this.tokenUrl.origin, + { + timeout, + maxRetries: 0, + headers: { 'User-Agent': `workos-node/${VERSION}` }, + }, + undefined, + { redirect: 'manual' }, + ); + } +} + +function missingSetting(field: string, variable: string) { + return new WorkloadIdentityError( + 'invalid_configuration', + `${field} is required (or set ${variable})`, + ); +} + +/** + * Settles with `work`, or rejects with `reason()` as soon as `signal` aborts. + * `work` is left running either way. + */ +function settleUnlessAborted( + work: Promise, + signal: AbortSignal | undefined, + reason: () => unknown, +): Promise { + if (!signal) { + return work; + } + + return new Promise((resolve, reject) => { + const onAbort = () => reject(reason()); + + if (signal.aborted) { + onAbort(); + } else { + signal.addEventListener('abort', onAbort, { once: true }); + } + + work.then( + (value) => { + signal.removeEventListener('abort', onAbort); + resolve(value); + }, + (error) => { + signal.removeEventListener('abort', onAbort); + reject(error); + }, + ); + }); +} + +function abortReason(signal: AbortSignal | undefined): unknown { + if (signal?.reason !== undefined) { + return signal.reason; + } + + const error = new Error('The operation was aborted.'); + error.name = 'AbortError'; + return error; +} + +/** + * True for the 408 the SDK's HTTP client raises itself when a request runs + * past its timeout (see `fetch-client.ts`), which is a transport failure. A + * 408 sent by the server is a response. + */ +function isRequestTimeout(error: HttpClientError): boolean { + const { status, data } = error.response; + + return status === 408 && isRecord(data) && data.error === 'Request timeout'; +} + +async function readJson( + response: HttpClientResponseInterface, +): Promise { + try { + return await response.toJSON(); + } catch (error) { + if (error instanceof ParseError) { + return undefined; + } + throw error; + } +} + +function readOAuthError( + body: unknown, +): { code: string; description: string } | undefined { + if (!isRecord(body) || typeof body.error !== 'string' || !body.error) { + return undefined; + } + + return { + code: body.error, + description: + typeof body.error_description === 'string' ? body.error_description : '', + }; +} + +function readTokenResponse(body: unknown): TokenResponse { + if (!isRecord(body)) { + throw new WorkloadIdentityError( + 'invalid_response', + 'The token response was not a JSON object.', + ); + } + + const { access_token: accessToken, expires_in: expiresIn } = body; + + if (typeof accessToken !== 'string' || !accessToken) { + throw new WorkloadIdentityError( + 'invalid_response', + 'The token response had no access token.', + ); + } + + return { + accessToken, + expiresInSeconds: + typeof expiresIn === 'number' && + Number.isFinite(expiresIn) && + expiresIn > 0 + ? expiresIn + : DEFAULT_TOKEN_LIFETIME_SECONDS, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/src/workload-identity/workload-identity-error.ts b/src/workload-identity/workload-identity-error.ts new file mode 100644 index 000000000..4077e928d --- /dev/null +++ b/src/workload-identity/workload-identity-error.ts @@ -0,0 +1,86 @@ +// @oagen-ignore-file +import { ERROR_DESCRIPTION_LIMIT } from './constants'; + +/** + * Every hint lives in this one table. The wording is pending the final + * server error contract, so a change is made here and nowhere else. + */ +const HINTS = new Map([ + // OAuth codes returned by the token endpoint. + [ + 'invalid_grant', + 'The identity token did not match a trust rule for this application, or the token has expired. Check the issuer, audience and subject claims against the trust rule.', + ], + [ + 'invalid_target', + "The resource or audience is wrong. The trust rule's audience must match the audience the identity token was requested with, and the resource must be registered for the environment.", + ], + [ + 'invalid_client', + 'Check that the client ID is the M2M application that has the trust rule.', + ], + [ + 'unauthorized_client', + 'This application is not allowed to use workload identity federation. Check that the feature is enabled for the environment and that the application has a trust rule.', + ], + [ + 'invalid_scope', + 'The requested scope is not allowed for this application. Fix the scope or leave it unset.', + ], + [ + 'invalid_request', + 'The token request was malformed. Check that the token URL points at the `/oauth2/token` endpoint.', + ], + // Codes the SDK assigns to failures that have no OAuth code. + [ + 'exchange_failed', + 'The token endpoint could not be reached or kept failing. Check the token URL and try again.', + ], + [ + 'invalid_response', + 'The token endpoint returned a response the SDK could not read. Check that the token URL points at the `/oauth2/token` endpoint.', + ], + [ + 'provider_failed', + 'The identity token provider failed, so there was no token to exchange.', + ], + [ + 'invalid_configuration', + 'Workload identity credentials are missing a required setting.', + ], +]); + +/** For an OAuth code the table does not list. */ +const UNKNOWN_CODE_HINT = 'The token endpoint rejected the exchange.'; + +/** + * A workload identity failure: a rejected or unreachable token exchange, a + * failing identity token provider, or incomplete configuration. + * + * The message is `: `, followed by the description when there is + * one. It never contains the identity token or the access token. + */ +export class WorkloadIdentityError extends Error { + readonly name = 'WorkloadIdentityError'; + /** The OAuth error code from the token endpoint, or an SDK code. */ + readonly code: string; + /** The server's `error_description`, or a detail from the SDK. May be empty. */ + readonly description: string; + /** One sentence on what to check. Never empty. */ + readonly hint: string; + + constructor( + code: string, + description?: string, + options?: { cause?: unknown }, + ) { + const hint = HINTS.get(code) ?? UNKNOWN_CODE_HINT; + const text = (description ?? '').slice(0, ERROR_DESCRIPTION_LIMIT); + + super(text ? `${code}: ${hint} ${text}` : `${code}: ${hint}`, options); + + this.code = code; + this.description = text; + this.hint = hint; + } +} diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts new file mode 100644 index 000000000..f5935317c --- /dev/null +++ b/src/workload-identity/workload-identity.spec.ts @@ -0,0 +1,1159 @@ +// @oagen-ignore-file +import fetch from 'jest-fetch-mock'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import http from 'node:http'; +import { AddressInfo } from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { inspect } from 'node:util'; +import { version } from '../../package.json'; +import { UnauthorizedException } from '../common/exceptions'; +import { + tokenEnv, + tokenFile, + WorkloadIdentityCredentials, + WorkloadIdentityCredentialsOptions, + WorkloadIdentityError, + WorkOS, +} from '../index'; +import { WorkOS as WorkOSWorker } from '../index.worker'; +import type { WorkloadIdentityInternals } from './workload-identity-credentials'; + +// The conformance cases in the WIF plan (WIF-01 to WIF-24). Each case ID is +// in the name of at least one test below. Shared `describe` names carry no +// ID, because the conformance check reads the full test name. + +const CLIENT_ID = 'client_wif_test'; +const ENVIRONMENT_ID = 'environment_wif_test'; +const TOKEN_URL = 'https://auth.workos.test/oauth2/token'; +const GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'; + +interface RecordedRequest { + url: string; + method: string; + headers: Headers; + body: string; +} + +interface Reply { + status?: number; + json?: unknown; + text?: string; + headers?: Record; +} + +/** Called with the 1-based count of requests the mock has received. */ +type Responder = ( + count: number, + request: RecordedRequest, +) => Reply | Promise; + +// The mock token endpoint and the mock WorkOS API. +let exchanges: RecordedRequest[]; +let apiRequests: RecordedRequest[]; +let issued: number; +let tokenEndpoint: Responder; +let api: Responder; + +/** The success response: `access-1`, then `access-2`, one per exchange. */ +const issueToken = (fields: Record = {}): Reply => ({ + json: { + access_token: `access-${++issued}`, + token_type: 'Bearer', + expires_in: 300, + ...fields, + }, +}); + +const oauthError = (code: string, description = `${code} description`) => ({ + status: 400, + json: { error: code, error_description: description }, +}); + +const unauthorized = (): Reply => ({ + status: 401, + json: { message: 'Unauthorized' }, +}); + +const form = (request: RecordedRequest) => + Object.fromEntries(new URLSearchParams(request.body)); + +const bearer = (request: RecordedRequest) => + request.headers.get('authorization'); + +const noSleep = () => Promise.resolve(); + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => (resolve = done)); + return { promise, resolve }; +} + +async function waitFor(condition: () => boolean) { + for (let turn = 0; turn < 1000 && !condition(); turn++) { + await new Promise((done) => setImmediate(done)); + } + expect(condition()).toBe(true); +} + +function setup( + options: Partial = {}, + internals: WorkloadIdentityInternals = {}, +) { + const provider = jest.fn(async () => 'assertion-1'); + const credentials = new WorkloadIdentityCredentials( + { + clientId: CLIENT_ID, + tokenUrl: TOKEN_URL, + environmentId: ENVIRONMENT_ID, + identityTokenProvider: provider, + ...options, + }, + { sleep: noSleep, ...internals }, + ); + const workos = new WorkOS({ credentials }); + + return { provider, credentials, workos }; +} + +describe('workload identity', () => { + const OLD_ENV = process.env; + + beforeEach(() => { + process.env = { ...OLD_ENV }; + for (const name of [ + 'WORKOS_API_KEY', + 'WORKOS_CLIENT_ID', + 'WORKOS_WIF_TOKEN_URL', + 'WORKOS_WIF_SCOPE', + 'WORKOS_ENVIRONMENT_ID', + ]) { + delete process.env[name]; + } + + exchanges = []; + apiRequests = []; + issued = 0; + tokenEndpoint = () => issueToken(); + api = () => ({ json: { ok: true } }); + + fetch.resetMocks(); + fetch.mockResponse(async (request) => { + const recorded: RecordedRequest = { + url: request.url, + method: request.method, + headers: request.headers, + body: await request.text(), + }; + const isExchange = request.url.endsWith('/oauth2/token'); + const received = isExchange ? exchanges : apiRequests; + received.push(recorded); + + const reply = await (isExchange ? tokenEndpoint : api)( + received.length, + recorded, + ); + + return { + status: reply.status ?? 200, + body: reply.text ?? JSON.stringify(reply.json ?? {}), + headers: { + 'content-type': + reply.text === undefined ? 'application/json' : 'text/plain', + ...reply.headers, + }, + }; + }); + }); + + afterEach(() => { + process.env = OLD_ENV; + }); + + describe('exchange', () => { + it('WIF-01: the first request sends one exchange POST with the jwt-bearer form', async () => { + const { workos } = setup(); + + await workos.get('/organizations'); + + expect(exchanges).toHaveLength(1); + expect(exchanges[0].url).toBe(TOKEN_URL); + expect(exchanges[0].method).toBe('POST'); + expect(exchanges[0].headers.get('content-type')).toBe( + 'application/x-www-form-urlencoded', + ); + expect(form(exchanges[0])).toEqual({ + grant_type: GRANT_TYPE, + assertion: 'assertion-1', + client_id: CLIENT_ID, + resource: 'https://api.workos.com', + }); + expect(exchanges[0].headers.has('authorization')).toBe(false); + + const scoped = setup({ scope: 'organizations:write' }); + + await scoped.workos.get('/organizations'); + + expect(exchanges).toHaveLength(2); + expect(form(exchanges[1])).toEqual({ + grant_type: GRANT_TYPE, + assertion: 'assertion-1', + client_id: CLIENT_ID, + resource: 'https://api.workos.com', + scope: 'organizations:write', + }); + expect(form(exchanges[1])).not.toHaveProperty('client_secret'); + expect(exchanges[1].headers.has('authorization')).toBe(false); + }); + + it('WIF-02: the API request carries the access token and the environment header', async () => { + const { workos } = setup(); + + await expect(workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(apiRequests).toHaveLength(1); + expect(apiRequests[0].url).toBe('https://api.workos.com/organizations'); + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + expect(apiRequests[0].headers.get('x-url-environment-id')).toBe( + ENVIRONMENT_ID, + ); + }); + + it('WIF-18: the exchange does not follow a redirect', async () => { + // Real HTTP: a mocked fetch never follows a redirect, so it could not + // tell whether the exchange would. + const nativeFetch = (globalThis as Record) + .__workosNativeFetch as typeof globalThis.fetch; + fetch.mockImplementation((input, init) => + nativeFetch(input as string, init), + ); + + const listen = async (handler: http.RequestListener) => { + const server = http.createServer(handler); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + const { port } = server.address() as AddressInfo; + return { server, url: `http://127.0.0.1:${port}/oauth2/token` }; + }; + + const targetRequests: string[] = []; + const target = await listen((req, res) => { + targetRequests.push(req.method ?? ''); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ access_token: 'access-redirected' })); + }); + + const tokenRequests: string[] = []; + const token = await listen((req, res) => { + tokenRequests.push(req.method ?? ''); + res.writeHead(307, { location: target.url }); + res.end(); + }); + + try { + const credentials = new WorkloadIdentityCredentials({ + clientId: CLIENT_ID, + tokenUrl: token.url, + environmentId: ENVIRONMENT_ID, + identityTokenProvider: async () => 'assertion-1', + }); + + const error = await credentials.resolve().catch((e) => e); + + expect(error).toBeInstanceOf(WorkloadIdentityError); + expect(error.code).toBe('exchange_failed'); + expect(tokenRequests).toEqual(['POST']); + expect(targetRequests).toEqual([]); + } finally { + for (const { server } of [token, target]) { + server.closeAllConnections(); + await new Promise((done) => server.close(done)); + } + } + }); + + it('WIF: a redirect reported by the runtime as status 0 or 3xx is an exchange failure', async () => { + tokenEndpoint = () => ({ status: 302, text: '' }); + const { credentials } = setup(); + + await expect(credentials.resolve()).rejects.toMatchObject({ + code: 'exchange_failed', + }); + expect(exchanges).toHaveLength(1); + expect(fetch.mock.calls[0][1]).toMatchObject({ redirect: 'manual' }); + }); + + it.each([ + ['a 200 that is not JSON', { text: 'not json' }], + ['a 200 with no access token', { json: { token_type: 'Bearer' } }], + ['a 404 with no OAuth error', { status: 404, json: {} }], + ])( + 'WIF: %s is an invalid response and is not retried', + async (_name, reply) => { + tokenEndpoint = () => reply; + const { workos } = setup(); + + await expect(workos.get('/organizations')).rejects.toMatchObject({ + name: 'WorkloadIdentityError', + code: 'invalid_response', + }); + expect(exchanges).toHaveLength(1); + expect(apiRequests).toHaveLength(0); + }, + ); + }); + + describe('cache and refresh', () => { + it('WIF-03: a second request within the token lifetime reuses the cached token', async () => { + const { workos } = setup(); + + await workos.get('/organizations'); + await workos.get('/organizations'); + + expect(exchanges).toHaveLength(1); + expect(apiRequests.map(bearer)).toEqual([ + 'Bearer access-1', + 'Bearer access-1', + ]); + }); + + it('WIF-04: with expires_in 300 the token is refreshed when less than 60 seconds remain', async () => { + let now = 0; + const { workos } = setup({}, { now: () => now }); + + await workos.get('/organizations'); + + now = 239_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(1); + + now = 241_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(2); + expect(bearer(apiRequests[2])).toBe('Bearer access-2'); + }); + + it('WIF-05: with expires_in 100 the refresh threshold is 20 seconds, not 60', async () => { + let now = 0; + tokenEndpoint = () => issueToken({ expires_in: 100 }); + const { workos } = setup({}, { now: () => now }); + + await workos.get('/organizations'); + + now = 79_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(1); + + now = 81_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(2); + }); + + it('WIF-06: a response with no expires_in is treated as 300 seconds', async () => { + let now = 0; + tokenEndpoint = () => issueToken({ expires_in: undefined }); + const { workos } = setup({}, { now: () => now }); + + await workos.get('/organizations'); + + now = 239_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(1); + + now = 241_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(2); + }); + + it('WIF-07: two credentials instances never share a cached token', async () => { + const first = setup(); + const second = setup(); + + await first.workos.get('/organizations'); + await second.workos.get('/organizations'); + + expect(exchanges).toHaveLength(2); + expect(apiRequests.map(bearer)).toEqual([ + 'Bearer access-1', + 'Bearer access-2', + ]); + }); + + it('WIF-11: a late 401 for an old generation does not discard a newer token', async () => { + const { credentials, workos } = setup(); + + const first = await credentials.resolve(); + expect(first.headers.Authorization).toBe('Bearer access-1'); + + credentials.invalidate(first.generation); + const second = await credentials.resolve(); + expect(second.headers.Authorization).toBe('Bearer access-2'); + expect(second.generation).not.toBe(first.generation); + + // The late 401 names the generation its request was sent with. + credentials.invalidate(first.generation); + + await workos.get('/organizations'); + + expect((await credentials.resolve()).generation).toBe(second.generation); + expect(exchanges).toHaveLength(2); + expect(bearer(apiRequests[0])).toBe('Bearer access-2'); + }); + }); + + describe('shared exchange', () => { + it('WIF-08: 20 concurrent first requests on one instance produce exactly one exchange', async () => { + const release = deferred(); + tokenEndpoint = async () => { + await release.promise; + return issueToken(); + }; + const { provider, workos } = setup(); + + const requests = Array.from({ length: 20 }, () => + workos.get('/organizations'), + ); + + // The endpoint holds its response until every caller is waiting on it. + await waitFor(() => exchanges.length === 1); + expect(apiRequests).toHaveLength(0); + release.resolve(); + + await Promise.all(requests); + + expect(exchanges).toHaveLength(1); + expect(provider).toHaveBeenCalledTimes(1); + expect(apiRequests).toHaveLength(20); + expect(new Set(apiRequests.map(bearer))).toEqual( + new Set(['Bearer access-1']), + ); + }); + + it('WIF-16: after a failed exchange the next request starts a fresh exchange', async () => { + tokenEndpoint = (count) => + count === 1 ? oauthError('invalid_grant') : issueToken(); + const { workos } = setup(); + + await expect(workos.get('/organizations')).rejects.toBeInstanceOf( + WorkloadIdentityError, + ); + await expect(workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(exchanges).toHaveLength(2); + expect(apiRequests.map(bearer)).toEqual(['Bearer access-1']); + }); + + it('WIF-23: aborting one waiting caller does not cancel the shared exchange', async () => { + const release = deferred(); + tokenEndpoint = async () => { + await release.promise; + return issueToken(); + }; + const { credentials } = setup(); + const abort = new AbortController(); + + const callerA = credentials.resolve({ signal: abort.signal }); + const callerB = credentials.resolve(); + await waitFor(() => exchanges.length === 1); + + abort.abort(); + await expect(callerA).rejects.toMatchObject({ name: 'AbortError' }); + + release.resolve(); + + await expect(callerB).resolves.toMatchObject({ + headers: { Authorization: 'Bearer access-1' }, + }); + expect(exchanges).toHaveLength(1); + }); + + it('WIF-23: a request that times out while waiting does not cancel the shared exchange', async () => { + const release = deferred(); + tokenEndpoint = async () => { + await release.promise; + return issueToken(); + }; + const { credentials } = setup(); + const impatient = new WorkOS({ credentials, timeout: 20, maxRetries: 0 }); + const patient = new WorkOS({ credentials }); + + // Caller A starts the exchange, then gives up on its own deadline. + const callerA = impatient.get('/organizations'); + await waitFor(() => exchanges.length === 1); + const callerB = patient.get('/organizations'); + + await expect(callerA).rejects.toMatchObject({ status: 408 }); + + release.resolve(); + + await expect(callerB).resolves.toEqual({ data: { ok: true } }); + expect(exchanges).toHaveLength(1); + expect(apiRequests.map(bearer)).toEqual(['Bearer access-1']); + }); + }); + + describe('401 recovery', () => { + it('WIF-09: a 401 invalidates that token generation, exchanges again and retries once', async () => { + api = (count) => (count === 1 ? unauthorized() : { json: { ok: true } }); + const { workos } = setup(); + + await expect(workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(exchanges).toHaveLength(2); + expect(apiRequests.map(bearer)).toEqual([ + 'Bearer access-1', + 'Bearer access-2', + ]); + }); + + it('WIF-10: a second 401 after recovery is returned to the caller', async () => { + api = () => unauthorized(); + const { workos } = setup(); + + await expect(workos.get('/organizations')).rejects.toBeInstanceOf( + UnauthorizedException, + ); + + expect(exchanges).toHaveLength(2); + expect(apiRequests).toHaveLength(2); + }); + + it('WIF-12: transport retries inside one request do not reset the single 401 recovery', async () => { + api = (count) => { + if (count === 2) { + return { + status: 503, + json: { message: 'Unavailable' }, + headers: { 'Retry-After': '0' }, + }; + } + return count <= 3 ? unauthorized() : { json: { ok: true } }; + }; + const { workos } = setup(); + + await expect(workos.get('/organizations')).rejects.toBeInstanceOf( + UnauthorizedException, + ); + + expect(exchanges).toHaveLength(2); + expect(apiRequests).toHaveLength(3); + }); + + it('WIF-13: the 401 retry sends the same body and the same idempotency key', async () => { + api = (count) => (count === 1 ? unauthorized() : { json: { ok: true } }); + const { workos } = setup(); + + await workos.post('/organizations', { + name: 'Acme', + domains: ['a.test'], + }); + + expect(apiRequests).toHaveLength(2); + const [first, second] = apiRequests; + expect(first.body).toBe('{"name":"Acme","domains":["a.test"]}'); + expect(second.body).toBe(first.body); + expect(first.headers.get('idempotency-key')).toBeTruthy(); + expect(second.headers.get('idempotency-key')).toBe( + first.headers.get('idempotency-key'), + ); + expect([bearer(first), bearer(second)]).toEqual([ + 'Bearer access-1', + 'Bearer access-2', + ]); + }); + + it('WIF: a per-request access token keeps its precedence and is not recovered', async () => { + api = () => unauthorized(); + const { workos } = setup(); + + await expect( + workos.get('/sso/profile', { accessToken: 'user_access_token' }), + ).rejects.toBeInstanceOf(UnauthorizedException); + + expect(exchanges).toHaveLength(0); + expect(apiRequests).toHaveLength(1); + expect(bearer(apiRequests[0])).toBe('Bearer user_access_token'); + expect(apiRequests[0].headers.has('x-url-environment-id')).toBe(false); + }); + }); + + describe('exchange retries', () => { + it('WIF-14: the exchange is retried on 5xx and 429, calling the provider again each attempt', async () => { + tokenEndpoint = (count) => { + if (count === 1) { + return { status: 503, text: 'unavailable' }; + } + if (count === 2) { + return { + status: 429, + json: { message: 'slow down' }, + headers: { 'Retry-After': '0' }, + }; + } + return issueToken(); + }; + const { provider, workos } = setup(); + + await expect(workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(exchanges).toHaveLength(3); + expect(provider).toHaveBeenCalledTimes(3); + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + }); + + it('WIF-14: the exchange is retried when the token endpoint cannot be reached', async () => { + tokenEndpoint = (count) => { + if (count === 1) { + throw new TypeError('fetch failed'); + } + return issueToken(); + }; + const { provider, workos } = setup(); + + await expect(workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(provider).toHaveBeenCalledTimes(2); + }); + + it('WIF-14: the exchange is retried when the provider fails', async () => { + const provider = jest + .fn, []>() + .mockRejectedValueOnce(new Error('metadata service unavailable')) + .mockResolvedValueOnce('assertion-2'); + const { workos } = setup({ identityTokenProvider: provider }); + + await expect(workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(provider).toHaveBeenCalledTimes(2); + expect(exchanges).toHaveLength(1); + expect(form(exchanges[0]).assertion).toBe('assertion-2'); + }); + + it('WIF-14: the exchange honors Retry-After', async () => { + tokenEndpoint = (count) => + count === 1 + ? { + status: 429, + json: { message: 'slow down' }, + headers: { 'Retry-After': '1' }, + } + : issueToken(); + const sleep = jest.fn< + Promise, + [retryAttempt: number, retryAfterMs?: number | null] + >(noSleep); + const { workos } = setup({}, { sleep }); + + await workos.get('/organizations'); + + expect(exchanges).toHaveLength(2); + expect(sleep).toHaveBeenCalledTimes(1); + expect(sleep.mock.calls[0][1]).toBeGreaterThanOrEqual(1000); + }); + + it('WIF: an exchange that keeps failing surfaces the last failure', async () => { + tokenEndpoint = () => ({ + status: 503, + json: { error: 'temporarily_unavailable', error_description: 'busy' }, + }); + const { provider, workos } = setup(); + + await expect(workos.get('/organizations')).rejects.toMatchObject({ + name: 'WorkloadIdentityError', + code: 'temporarily_unavailable', + description: 'busy', + }); + + // The SDK's default: one attempt and three retries. + expect(exchanges).toHaveLength(4); + expect(provider).toHaveBeenCalledTimes(4); + expect(apiRequests).toHaveLength(0); + }); + }); + + describe('errors', () => { + it.each([ + 'invalid_grant', + 'invalid_target', + 'invalid_client', + 'unauthorized_client', + 'invalid_scope', + 'invalid_request', + ])( + 'WIF-15: %s is not retried and surfaces as a typed error with the code', + async (code) => { + tokenEndpoint = () => oauthError(code, `the server said ${code}`); + const { workos } = setup(); + + const error = await workos.get('/organizations').catch((e) => e); + + expect(error).toBeInstanceOf(WorkloadIdentityError); + expect(error.code).toBe(code); + expect(error.description).toBe(`the server said ${code}`); + expect(error.hint).not.toBe(''); + expect(error.message).toBe( + `${code}: ${error.hint} the server said ${code}`, + ); + expect(exchanges).toHaveLength(1); + expect(apiRequests).toHaveLength(0); + }, + ); + + it('WIF-17: neither the assertion nor the access token appears in an error or a log line', async () => { + const ASSERTION = 'SECRET-ASSERTION-VALUE'; + const ACCESS_TOKEN = 'SECRET-ACCESS-VALUE'; + + const logged: unknown[][] = []; + for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) { + jest + .spyOn(console, method) + .mockImplementation((...args) => void logged.push(args)); + } + jest + .spyOn(process, 'emitWarning') + .mockImplementation((...args) => void logged.push(args)); + + const secretProvider = async () => ASSERTION; + const errors: unknown[] = []; + + // An OAuth error from the exchange. + tokenEndpoint = () => oauthError('invalid_grant'); + errors.push( + await setup({ identityTokenProvider: secretProvider }) + .workos.get('/organizations') + .catch((e) => e), + ); + + // A 500 from the token endpoint until the retries run out. + tokenEndpoint = () => ({ status: 500, json: { message: 'boom' } }); + errors.push( + await setup({ identityTokenProvider: secretProvider }) + .workos.get('/organizations') + .catch((e) => e), + ); + + // A provider that raises. + tokenEndpoint = () => issueToken(); + errors.push( + await setup({ + identityTokenProvider: async () => { + throw new Error('metadata service unavailable'); + }, + }) + .workos.get('/organizations') + .catch((e) => e), + ); + + // A second 401 from the API. + tokenEndpoint = () => issueToken({ access_token: ACCESS_TOKEN }); + api = () => unauthorized(); + errors.push( + await setup({ identityTokenProvider: secretProvider }) + .workos.get('/organizations') + .catch((e) => e), + ); + + expect(errors.map((error) => (error as Error).name)).toEqual([ + 'WorkloadIdentityError', + 'WorkloadIdentityError', + 'WorkloadIdentityError', + 'UnauthorizedException', + ]); + // Both secrets did reach the mocks, so their absence below means + // something. + expect(exchanges.some((e) => e.body.includes(ASSERTION))).toBe(true); + expect(apiRequests.map(bearer)).toContain(`Bearer ${ACCESS_TOKEN}`); + + const seen = [ + ...errors.flatMap((error) => [ + (error as Error).message, + String(error), + (error as Error).stack, + inspect(error, { depth: null, showHidden: true }), + JSON.stringify(error, Object.getOwnPropertyNames(error as object)), + ]), + inspect(logged, { depth: null }), + ].join('\n'); + + expect(seen).not.toContain(ASSERTION); + expect(seen).not.toContain(ACCESS_TOKEN); + }); + }); + + describe('authentication precedence', () => { + it('WIF-19: passing both an API key and credentials is a configuration error', async () => { + const { credentials } = setup(); + + expect( + () => new WorkOS({ apiKey: 'sk_test_explicit', credentials }), + ).toThrow('WorkOS accepts an API key or credentials, not both'); + expect(() => new WorkOS('sk_test_explicit', { credentials })).toThrow( + 'WorkOS accepts an API key or credentials, not both', + ); + expect( + () => new WorkOSWorker({ apiKey: 'sk_test_explicit', credentials }), + ).toThrow('WorkOS accepts an API key or credentials, not both'); + + expect(fetch).not.toHaveBeenCalled(); + }); + + it('WIF-20: explicit credentials win over WORKOS_API_KEY and a failing configuration never falls back to it', async () => { + process.env.WORKOS_API_KEY = 'sk_test_env'; + + // (a) Valid credentials. + const valid = setup(); + await valid.workos.get('/organizations'); + expect(valid.workos.key).toBeUndefined(); + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + + // (b) No token URL, explicitly or in the environment. + const construct = () => + new WorkloadIdentityCredentials({ + clientId: CLIENT_ID, + environmentId: ENVIRONMENT_ID, + identityTokenProvider: async () => 'assertion-1', + }); + expect(construct).toThrow(WorkloadIdentityError); + expect(construct).toThrow( + 'invalid_configuration: Workload identity credentials are missing a required setting. tokenUrl is required (or set WORKOS_WIF_TOKEN_URL)', + ); + + // (c) Valid credentials whose exchange fails. + tokenEndpoint = () => oauthError('invalid_client'); + await expect(setup().workos.get('/organizations')).rejects.toMatchObject({ + name: 'WorkloadIdentityError', + code: 'invalid_client', + }); + + expect(apiRequests).toHaveLength(1); + for (const request of [...exchanges, ...apiRequests]) { + expect(request.headers.get('authorization') ?? '').not.toContain( + 'sk_test_env', + ); + expect(request.body).not.toContain('sk_test_env'); + } + }); + + it('WIF-24: a static API-key client is unchanged', async () => { + const workos = new WorkOS('sk_test_static'); + + await workos.get('/organizations'); + + // The exact header set an API-key client sent before credentials + // existed. + expect(fetch.mock.calls[0][1]?.headers).toEqual({ + Accept: 'application/json, text/plain, */*', + Authorization: 'Bearer sk_test_static', + 'Content-Type': 'application/json', + 'User-Agent': `workos-node/${version}`, + }); + expect(apiRequests[0].headers.has('x-url-environment-id')).toBe(false); + + api = () => unauthorized(); + + await expect(workos.get('/organizations')).rejects.toBeInstanceOf( + UnauthorizedException, + ); + + // One attempt for the 401: a static key has nothing to recover. + expect(apiRequests).toHaveLength(2); + expect(apiRequests.map(bearer)).toEqual([ + 'Bearer sk_test_static', + 'Bearer sk_test_static', + ]); + expect(exchanges).toHaveLength(0); + }); + + it('WIF: the worker entry authorizes with credentials too', async () => { + const { credentials } = setup(); + const workos = new WorkOSWorker({ credentials }); + + await workos.get('/organizations'); + + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + expect(apiRequests[0].headers.get('x-url-environment-id')).toBe( + ENVIRONMENT_ID, + ); + }); + + it('WIF: the snapshot replaces an Authorization header from the client config, whatever its casing', async () => { + const { credentials } = setup(); + const workos = new WorkOS({ + credentials, + config: { headers: { authorization: 'Bearer from_config' } }, + }); + + await workos.get('/organizations'); + + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + }); + }); + + describe('providers and configuration', () => { + it('WIF-21: tokenFile re-reads the file on every exchange', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'workos-wif-')); + const file = path.join(directory, 'token'); + let now = 0; + + try { + await writeFile(file, 'assertion-1\n'); + const { workos } = setup( + { identityTokenProvider: tokenFile(file) }, + { now: () => now }, + ); + + await workos.get('/organizations'); + + await writeFile(file, ' assertion-2\n'); + now = 241_000; + await workos.get('/organizations'); + + expect(exchanges.map((exchange) => form(exchange).assertion)).toEqual([ + 'assertion-1', + 'assertion-2', + ]); + + // An empty or missing file is a provider error. + await writeFile(file, '\n'); + await expect(tokenFile(file)()).rejects.toThrow('is empty'); + await expect( + tokenFile(path.join(directory, 'missing'))(), + ).rejects.toThrow('could not be read'); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it('WIF-22: tokenEnv and callback providers supply the assertion, and omitted fields default from the environment', async () => { + // (a) tokenEnv reads the variable on every call. + process.env.MY_JWT = 'assertion-env'; + await setup({ + identityTokenProvider: tokenEnv('MY_JWT'), + }).workos.get('/organizations'); + expect(form(exchanges[0]).assertion).toBe('assertion-env'); + + delete process.env.MY_JWT; + await expect(tokenEnv('MY_JWT')()).rejects.toThrow( + 'The environment variable MY_JWT is not set or is empty.', + ); + + // (b) A callback is any function of the provider type. + await setup({ + identityTokenProvider: async () => 'assertion-cb', + }).workos.get('/organizations'); + expect(form(exchanges[1]).assertion).toBe('assertion-cb'); + + // (c) Only a provider: everything else comes from the environment. + const ENV_TOKEN_URL = 'https://env.workos.test/oauth2/token'; + process.env.WORKOS_CLIENT_ID = 'client_env'; + process.env.WORKOS_WIF_TOKEN_URL = ENV_TOKEN_URL; + process.env.WORKOS_WIF_SCOPE = 'scope_env'; + process.env.WORKOS_ENVIRONMENT_ID = 'environment_env'; + + await new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + identityTokenProvider: async () => 'assertion-1', + }), + }).get('/organizations'); + + expect(exchanges[2].url).toBe(ENV_TOKEN_URL); + expect(form(exchanges[2])).toMatchObject({ + client_id: 'client_env', + scope: 'scope_env', + }); + expect(apiRequests[2].headers.get('x-url-environment-id')).toBe( + 'environment_env', + ); + + // (d) Explicit values win over the environment. + await new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + clientId: CLIENT_ID, + scope: 'organizations:write', + environmentId: ENVIRONMENT_ID, + identityTokenProvider: async () => 'assertion-1', + }), + }).get('/organizations'); + + expect(exchanges[3].url).toBe(ENV_TOKEN_URL); + expect(form(exchanges[3])).toMatchObject({ + client_id: CLIENT_ID, + scope: 'organizations:write', + }); + expect(apiRequests[3].headers.get('x-url-environment-id')).toBe( + ENVIRONMENT_ID, + ); + }); + + it.each([ + [ + 'clientId', + { clientId: undefined }, + 'clientId is required (or set WORKOS_CLIENT_ID)', + ], + [ + 'environmentId', + { environmentId: undefined }, + 'environmentId is required (or set WORKOS_ENVIRONMENT_ID)', + ], + [ + 'identityTokenProvider', + { identityTokenProvider: undefined }, + 'identityTokenProvider is required', + ], + [ + 'a valid tokenUrl', + { tokenUrl: 'not a url' }, + 'tokenUrl is not a valid URL', + ], + ])( + 'WIF: credentials without %s fail at construction', + (_name, overrides, description) => { + const construct = () => + setup(overrides as Partial); + + expect(construct).toThrow(WorkloadIdentityError); + expect(construct).toThrow(description); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + }); + + describe('edges', () => { + it('WIF: the exchange goes to the token URL host even when its path starts with two slashes', async () => { + const tokenUrl = 'https://auth.workos.test//oauth2/token'; + const { workos } = setup({ tokenUrl }); + + await workos.get('/organizations'); + + expect(exchanges.map((exchange) => exchange.url)).toEqual([tokenUrl]); + }); + + it('WIF: a token URL that is not http or https fails at construction', () => { + expect(() => setup({ tokenUrl: 'file:///oauth2/token' })).toThrow( + 'tokenUrl must be an http or https URL', + ); + }); + + it('WIF: tokenFile fails as a provider error in a runtime with no file system', async () => { + jest + .spyOn(process, 'getBuiltinModule') + .mockReturnValue(undefined as never); + + const error = await tokenFile('/var/run/token')().catch((e) => e); + + expect(error.message).toBe( + 'The identity token file /var/run/token could not be read.', + ); + expect(error.cause.message).toBe('This runtime has no file system.'); + }); + + it('WIF: an exchange that outlives its 30-second deadline fails, and the next request starts a new one', async () => { + // The first provider call never answers. + const provider = jest + .fn, []>() + .mockReturnValueOnce(new Promise(() => undefined)) + .mockResolvedValue('assertion-1'); + const { credentials } = setup({ identityTokenProvider: provider }); + + jest.useFakeTimers({ + doNotFake: ['nextTick', 'setImmediate', 'queueMicrotask'], + }); + + try { + const first = credentials.resolve().catch((e) => e); + const joined = credentials.resolve().catch((e) => e); + + await jest.advanceTimersByTimeAsync(29_999); + expect(provider).toHaveBeenCalledTimes(1); + await jest.advanceTimersByTimeAsync(1); + + for (const error of [await first, await joined]) { + expect(error).toBeInstanceOf(WorkloadIdentityError); + expect(error.code).toBe('exchange_failed'); + expect(error.description).toBe( + 'The token exchange did not finish within 30 seconds.', + ); + } + expect(jest.getTimerCount()).toBe(0); + } finally { + jest.useRealTimers(); + } + + // The in-flight exchange was cleared, so this starts a new one. + await expect(credentials.resolve()).resolves.toMatchObject({ + headers: { Authorization: 'Bearer access-1' }, + }); + expect(provider).toHaveBeenCalledTimes(2); + expect(exchanges).toHaveLength(1); + }); + + it('WIF: a Retry-After longer than the time left is cut to the exchange deadline', async () => { + tokenEndpoint = (count) => + count === 1 + ? { + status: 429, + json: { message: 'slow down' }, + headers: { 'Retry-After': '60' }, + } + : issueToken(); + const sleep = jest.fn< + Promise, + [retryAttempt: number, retryAfterMs?: number | null] + >(noSleep); + const { workos } = setup({}, { sleep }); + + await workos.get('/organizations'); + + expect(sleep).toHaveBeenCalledTimes(1); + expect(sleep.mock.calls[0][1]).toBeLessThanOrEqual(30_000); + expect(sleep.mock.calls[0][1]).toBeGreaterThan(25_000); + }); + + it('WIF: the server description is cut to 500 characters and an unknown code gets the general hint', async () => { + tokenEndpoint = () => oauthError('server_made_this_up', 'x'.repeat(600)); + const { workos } = setup(); + + const error = await workos.get('/organizations').catch((e) => e); + + expect(error).toBeInstanceOf(WorkloadIdentityError); + expect(error.code).toBe('server_made_this_up'); + expect(error.description).toBe('x'.repeat(500)); + expect(error.hint).toBe('The token endpoint rejected the exchange.'); + }); + + it.each([ + ['a string', 'soon'], + ['zero', 0], + ['a negative number', -5], + ])( + 'WIF: an expires_in that is %s is treated as 300 seconds', + async (_name, expiresIn) => { + let now = 0; + tokenEndpoint = () => issueToken({ expires_in: expiresIn }); + const { workos } = setup({}, { now: () => now }); + + await workos.get('/organizations'); + + now = 239_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(1); + + now = 241_000; + await workos.get('/organizations'); + expect(exchanges).toHaveLength(2); + }, + ); + }); +}); diff --git a/src/workos.ts b/src/workos.ts index 780e51f43..abb772fee 100644 --- a/src/workos.ts +++ b/src/workos.ts @@ -43,6 +43,8 @@ import { Groups } from './groups/groups'; import { HttpClient, HttpClientError } from './common/net/http-client'; import { SubtleCryptoProvider } from './common/crypto/subtle-crypto-provider'; import { FetchHttpClient } from './common/net/fetch-client'; +import { Credentials, StaticKeyCredentials } from './common/net/credentials'; +import { WorkloadIdentityError } from './workload-identity/workload-identity-error'; import { Widgets } from './widgets/widgets'; import { Actions } from './actions/actions'; import { Authorization } from './authorization/authorization'; @@ -69,6 +71,13 @@ export class WorkOS { private readonly hasApiKey: boolean; + /** + * What authorizes API requests: the `credentials` option when one is given, + * otherwise the API key wrapped as static credentials. Undefined for a + * public client, which has neither. + */ + protected readonly requestCredentials?: Credentials; + readonly actions: Actions; readonly agents = new Agents(this); readonly apiKeys = new ApiKeys(this); @@ -109,6 +118,12 @@ export class WorkOS { * @example * // PKCE/public client (no API key) * const workos = new WorkOS({ clientId: 'client_...' }); + * + * @example + * // Workload identity (no API key) + * const workos = new WorkOS({ + * credentials: new WorkloadIdentityCredentials({ ... }), + * }); */ constructor( keyOrOptions?: string | WorkOSOptions, @@ -122,11 +137,25 @@ export class WorkOS { this.options = maybeOptions ?? {}; } - if (!this.key) { + const { credentials } = this.options; + + if (credentials && this.key) { + throw new Error( + 'WorkOS accepts an API key or credentials, not both. ' + + 'Pass `apiKey` or `credentials`.', + ); + } + + // Explicit credentials win over the environment. A client built with + // them never reads or sends WORKOS_API_KEY. + if (!this.key && !credentials) { this.key = getEnv('WORKOS_API_KEY'); } this.hasApiKey = !!this.key; + this.requestCredentials = + credentials ?? + (this.key ? new StaticKeyCredentials(this.key) : undefined); if (this.options.https === undefined) { this.options.https = true; @@ -137,7 +166,7 @@ export class WorkOS { this.clientId = getEnv('WORKOS_CLIENT_ID'); } - if (!this.hasApiKey && !this.clientId) { + if (!this.requestCredentials && !this.clientId) { throw new Error( 'WorkOS requires either an API key or a clientId. ' + 'For server-side: new WorkOS("sk_...") or new WorkOS({ apiKey: "sk_..." }). ' + @@ -198,16 +227,17 @@ export class WorkOS { Object.assign(headers, configHeaders); } - if (this.key) { - headers['Authorization'] = `Bearer ${this.key}`; - } - - return new FetchHttpClient(this.baseURL, { - ...options.config, - timeout: options.timeout, - maxRetries: options.maxRetries, - headers, - }) as HttpClient; + return new FetchHttpClient( + this.baseURL, + { + ...options.config, + timeout: options.timeout, + maxRetries: options.maxRetries, + headers, + }, + undefined, + { credentials: this.requestCredentials }, + ) as HttpClient; } get version() { @@ -215,12 +245,13 @@ export class WorkOS { } /** - * Require API key for methods that need it. + * Require API key for methods that need it. Credentials passed to the + * constructor authorize the same methods an API key does. * @param methodName - Name of the method requiring API key (for error message) - * @throws ApiKeyRequiredException if no API key was provided + * @throws ApiKeyRequiredException if neither an API key nor credentials were provided */ requireApiKey(methodName: string): void { - if (!this.hasApiKey) { + if (!this.hasApiKey && !this.options.credentials) { throw new ApiKeyRequiredException(methodName); } } @@ -420,6 +451,11 @@ export class WorkOS { /** @internal */ handleHttpError({ path, error }: { path: string; error: unknown }) { + // The request never got its credentials. Surface the typed error as is. + if (error instanceof WorkloadIdentityError) { + throw error; + } + if (!(error instanceof HttpClientError)) { throw new Error(`Unexpected error: ${error}`, { cause: error }); } From ef4afb1a01645b3acef885c4ef3a1ede1ed9f311 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 08:05:15 -0800 Subject: [PATCH 02/14] ci(release): start the provider packages at 0.1.0 A manifest entry of 0.0.0 does not make the first release 0.1.0 for the node release type. release-please treats 0.0.0 as "never released", and the node strategy then uses the default first version, 1.0.0. Set initial-version on the three provider entries so the first release PR of each is 0.1.0. The key is read only when a package has no earlier release. It does not change which commits count for a package. Spec: docs/ideation/wif-backend-sdks/spec-phase-3.md --- release-please-config.json | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/release-please-config.json b/release-please-config.json index 3116553dc..a99053fd3 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -20,21 +20,24 @@ "component": "@workos-inc/workload-identity-github-actions", "package-name": "@workos-inc/workload-identity-github-actions", "include-component-in-tag": true, - "changelog-path": "CHANGELOG.md" + "changelog-path": "CHANGELOG.md", + "initial-version": "0.1.0" }, "packages/workload-identity-gcp": { "release-type": "node", "component": "@workos-inc/workload-identity-gcp", "package-name": "@workos-inc/workload-identity-gcp", "include-component-in-tag": true, - "changelog-path": "CHANGELOG.md" + "changelog-path": "CHANGELOG.md", + "initial-version": "0.1.0" }, "packages/workload-identity-aws": { "release-type": "node", "component": "@workos-inc/workload-identity-aws", "package-name": "@workos-inc/workload-identity-aws", "include-component-in-tag": true, - "changelog-path": "CHANGELOG.md" + "changelog-path": "CHANGELOG.md", + "initial-version": "0.1.0" } } } From 5206140d50495555c8b225eaa272cb2d8a5ef227 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 08:08:23 -0800 Subject: [PATCH 03/14] docs: add the release rule for provider packages release-please counts a commit for the SDK unless every file it touches is under packages/, and pull requests are squash-merged. Write down the rule that keeps a provider change out of the SDK release: - a provider feat or fix touches only packages//; - a provider dependency change goes in its own chore(deps) pull request, with the package.json and the root package-lock.json together, merged before the feat or fix that needs it. Spec: docs/ideation/wif-backend-sdks/spec-phase-3.md --- AGENTS.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 9c0f37d46..2a4df7cd0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,3 +8,26 @@ Write American English in hand-maintained code, comments, docs and test names Never respell a name or value that already ships: exported types, methods, options, API fields and enum values, fixture payloads, generated files, and third-party identifiers keep their spelling. + +## Releases + +release-please releases four packages from this repository: the SDK at the +root, and a provider package in each directory under `packages/`. A change to +a provider package must not release the SDK. + +release-please counts a commit for the SDK unless every file it touches is +under `packages/`. Pull requests are squash-merged, so one pull request is one +commit. Only `feat`, `fix`, `perf` and `revert` commits, and breaking changes, +cause a release. + +- A `feat` or `fix` pull request for a provider package touches only + `packages//`. +- A change to a provider package's dependencies goes in its own `chore(deps)` + pull request, with `packages//package.json` and the root + `package-lock.json` together. Merge it before the `feat` or `fix` pull + request that needs it. +- A `chore(deps)` pull request releases nothing. When a dependency change must + ship with no other change, follow it with a `fix` pull request that touches + only `packages//`. +- A pull request that changes the SDK and a provider package on purpose + releases both. From 1db64400556ad039d4b5d349f373c76f690e6711 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 11:42:55 -0800 Subject: [PATCH 04/14] fix(workload-identity): send the GCP metadata request without a proxy The Google Cloud provider used fetch. Started with NODE_USE_ENV_PROXY=1, Node sends fetch requests through the proxy named by HTTP_PROXY, and fetch has no per-request way out of that. The request for an identity token then went to the proxy. The metadata server exists only inside the workload's own VM or container, so a proxy cannot reach it: the request failed, or the provider returned whatever the proxy answered as the token. The provider now makes the request with node:http and an agent of its own, which the setting does not reach. The URL, the header, the 10-second timeout and the status and empty-token errors are unchanged, and a redirect is still not followed. A connection failure now rejects with the socket error itself instead of "fetch failed". A test gives the default agent a proxy and checks that the proxy receives nothing. Spec: docs/ideation/wif-backend-sdks/spec-phase-3.md --- packages/workload-identity-gcp/README.md | 2 + .../workload-identity-gcp/src/index.spec.ts | 54 +++++++++--- packages/workload-identity-gcp/src/index.ts | 87 +++++++++++++------ 3 files changed, 105 insertions(+), 38 deletions(-) diff --git a/packages/workload-identity-gcp/README.md b/packages/workload-identity-gcp/README.md index 6576b63aa..ed006da1c 100644 --- a/packages/workload-identity-gcp/README.md +++ b/packages/workload-identity-gcp/README.md @@ -26,4 +26,6 @@ const workos = new WorkOS({ `gcpMetadata(audience)` returns a function that requests an identity token for the default service account from the metadata server on every call. The audience must match the audience of the trust rule on the WorkOS application. +The request to the metadata server never goes through a proxy, even when Node is started with `NODE_USE_ENV_PROXY=1`. That server exists only inside the workload's own VM or container, so a proxy cannot reach it. + The package has no dependencies and does not depend on `@workos-inc/node`. diff --git a/packages/workload-identity-gcp/src/index.spec.ts b/packages/workload-identity-gcp/src/index.spec.ts index 9755d60e0..535eea65a 100644 --- a/packages/workload-identity-gcp/src/index.spec.ts +++ b/packages/workload-identity-gcp/src/index.spec.ts @@ -4,7 +4,7 @@ import { AddressInfo } from 'node:net'; import { gcpMetadata } from './index'; const AUDIENCE = 'https://api.workos.com'; -const METADATA_HOST = 'http://metadata.google.internal'; +const METADATA_HOST = 'metadata.google.internal'; interface Received { method: string; @@ -18,7 +18,7 @@ describe('gcpMetadata', () => { async function listen( respond: (res: http.ServerResponse) => void, - ): Promise<{ baseUrl: string; received: Received[] }> { + ): Promise<{ baseUrl: string; port: number; received: Received[] }> { const received: Received[] = []; const server = http.createServer((req, res) => { received.push({ @@ -32,29 +32,34 @@ describe('gcpMetadata', () => { await new Promise((done) => server.listen(0, '127.0.0.1', done)); const { port } = server.address() as AddressInfo; - return { baseUrl: `http://127.0.0.1:${port}`, received }; + return { baseUrl: `http://127.0.0.1:${port}`, port, received }; } /** * Points the metadata host at a local server. The provider has no setting * for its base URL, so the test moves the host under it: the request the - * provider builds is sent unchanged apart from the origin, and anything - * that is not for the metadata host fails the test. + * provider builds is sent unchanged apart from the host and port, and + * anything that is not for the metadata host fails the test. */ async function metadataServer(respond: (res: http.ServerResponse) => void) { const mock = await listen(respond); - const realFetch = globalThis.fetch; + const realRequest = http.request; - jest.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { - const url = String(input); - requested.push(url); + jest.spyOn(http, 'request').mockImplementation((( + options: http.RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ) => { + requested.push(`http://${options.host}${options.path}`); - if (!url.startsWith(`${METADATA_HOST}/`)) { - throw new Error(`Unexpected request to ${url}`); + if (options.host !== METADATA_HOST) { + throw new Error(`Unexpected request to ${options.host}`); } - return realFetch(mock.baseUrl + url.slice(METADATA_HOST.length), init); - }); + return realRequest( + { ...options, host: '127.0.0.1', port: mock.port }, + callback, + ); + }) as typeof http.request); return mock; } @@ -119,6 +124,29 @@ describe('gcpMetadata', () => { ); }); + it('never sends the request through a proxy', async () => { + // Started with NODE_USE_ENV_PROXY=1, Node sends every request that uses + // the default agent through the proxy named by HTTP_PROXY. Give the + // default agent a proxy the same way: the provider must not use it. A + // Node version without the `proxyEnv` option ignores it, and there this + // test cannot fail. + const proxy = await listen(text(200, 'token-from-the-proxy')); + const { received } = await metadataServer(text(200, 'gcp-jwt')); + const defaultAgent = http.globalAgent; + http.globalAgent = new http.Agent({ + proxyEnv: { HTTP_PROXY: proxy.baseUrl, http_proxy: proxy.baseUrl }, + } as http.AgentOptions); + + try { + await expect(gcpMetadata(AUDIENCE)()).resolves.toBe('gcp-jwt'); + } finally { + http.globalAgent = defaultAgent; + } + + expect(received).toHaveLength(1); + expect(proxy.received).toHaveLength(0); + }); + it('requires an audience', () => { expect(() => gcpMetadata('')).toThrow('an audience is required'); }); diff --git a/packages/workload-identity-gcp/src/index.ts b/packages/workload-identity-gcp/src/index.ts index 4ba525989..b6f96801f 100644 --- a/packages/workload-identity-gcp/src/index.ts +++ b/packages/workload-identity-gcp/src/index.ts @@ -1,8 +1,23 @@ // @oagen-ignore-file +import http from 'node:http'; + const REQUEST_TIMEOUT_MS = 10_000; +const METADATA_HOST = 'metadata.google.internal'; +const IDENTITY_PATH = + '/computeMetadata/v1/instance/service-accounts/default/identity'; -const IDENTITY_URL = - 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity'; +/** + * The metadata server is an address inside the workload's own VM or + * container. A proxy is another machine: it cannot reach that server, and it + * could answer with its own identity. So the request never goes through one. + * + * Started with `NODE_USE_ENV_PROXY=1`, Node sends `fetch` requests, and + * `node:http` requests that use the default agent, through the proxy named + * by `HTTP_PROXY`. `fetch` has no per-request way out of that, so the + * request is made with `node:http` and this agent of its own, which the + * setting does not reach. + */ +const agent = new http.Agent(); /** * An identity token provider for Google Cloud. Each call asks the metadata @@ -10,7 +25,8 @@ const IDENTITY_URL = * given audience. * * Works wherever the metadata server is reachable: Compute Engine, GKE, - * Cloud Run, Cloud Functions and App Engine. + * Cloud Run, Cloud Functions and App Engine. The request never goes through + * a proxy. * * @param audience - The audience the token is requested for. It must match * the audience of the trust rule, conventionally `https://api.workos.com`. @@ -25,29 +41,50 @@ export function gcpMetadata(audience: string): () => Promise { throw new TypeError('gcpMetadata: an audience is required.'); } - return async () => { - const response = await fetch( - `${IDENTITY_URL}?audience=${encodeURIComponent(audience)}&format=full`, - { - headers: { 'Metadata-Flavor': 'Google' }, - redirect: 'manual', - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), - }, - ); - - if (response.status !== 200) { - await response.body?.cancel().catch(() => undefined); - throw new Error( - `The GCP metadata server responded with status ${response.status}.`, - ); - } + const path = `${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`; + + return () => + new Promise((resolve, reject) => { + // `node:http` follows no redirect: a 3xx comes back as the response. + const request = http.request( + { + host: METADATA_HOST, + path, + method: 'GET', + headers: { 'Metadata-Flavor': 'Google' }, + agent, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }, + (response) => { + response.on('error', reject); - const token = (await response.text()).trim(); + if (response.statusCode !== 200) { + // The body is dropped unread: an error never needs it. + response.destroy(); + reject( + new Error( + `The GCP metadata server responded with status ${response.statusCode}.`, + ), + ); + return; + } - if (!token) { - throw new Error('The GCP metadata server returned an empty token.'); - } + const chunks: Buffer[] = []; + response.on('data', (chunk: Buffer) => chunks.push(chunk)); + response.on('end', () => { + const token = Buffer.concat(chunks).toString('utf8').trim(); + if (token) { + resolve(token); + } else { + reject( + new Error('The GCP metadata server returned an empty token.'), + ); + } + }); + }, + ); - return token; - }; + request.on('error', reject); + request.end(); + }); } From 762c7a06db8a583b29796d2edfc3e1ef492b66ad Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 12:42:20 -0800 Subject: [PATCH 05/14] test(workload-identity): name the GCP proxy test for WIF-GCP-03 The rule that the GCP metadata request never goes through a proxy is now conformance case WIF-GCP-03. The conformance check reads case IDs from test names, so the existing test for the rule now carries the ID. No behavior changes. Spec: docs/ideation/wif-backend-sdks/spec-phase-3.md --- packages/workload-identity-gcp/src/index.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/workload-identity-gcp/src/index.spec.ts b/packages/workload-identity-gcp/src/index.spec.ts index 535eea65a..172992926 100644 --- a/packages/workload-identity-gcp/src/index.spec.ts +++ b/packages/workload-identity-gcp/src/index.spec.ts @@ -124,7 +124,7 @@ describe('gcpMetadata', () => { ); }); - it('never sends the request through a proxy', async () => { + it('WIF-GCP-03: never sends the request through a proxy', async () => { // Started with NODE_USE_ENV_PROXY=1, Node sends every request that uses // the default agent through the proxy named by HTTP_PROXY. Give the // default agent a proxy the same way: the provider must not use it. A From a2e7872fe131cb8b33aa5018187bf3d5dd0df0a8 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Fri, 13 Nov 2026 13:49:54 -0800 Subject: [PATCH 06/14] fix(workload-identity): make environment ID optional and align error hints with the server A reading of the server code on 2026-11-13 showed three things the SDK had slightly wrong. The server binds a workload identity client to exactly one environment and takes the environment from that binding, so the x-url-environment-id header selects nothing. environmentId is now optional: a missing value is no longer a configuration error, and the header is sent only when a value is set. An empty string counts as not set. WORKOS_ENVIRONMENT_ID still fills the field when it is omitted, and an explicit value still wins. Setting it is a safety check: a value that names a different environment gets 403 environment_mismatch. Four hints said the wrong thing for their code. An audience that no trust rule names is invalid_grant, not invalid_target; invalid_target is only about the resource. An application with no enabled trust rule is invalid_client, not unauthorized_client. invalid_grant also covers an identity token that was already exchanged. The four hints now carry the shared wording. The scope in the tests is orgs:write, the real scope name on the server. The README says that environmentId is optional and why, and that the server accepts an identity token for one exchange, which matters for tokenFile and tokenEnv. WIF-02 now has two parts: (a) with an environment ID, (b) without one. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 6 to 8) --- README.md | 6 ++- src/workload-identity/constants.ts | 5 +- .../workload-identity-credentials.ts | 33 +++++++----- .../workload-identity-error.ts | 8 +-- .../workload-identity.spec.ts | 50 +++++++++++++++---- 5 files changed, 73 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 5724d531c..602447b34 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ const workos = new WorkOS({ credentials: new WorkloadIdentityCredentials({ clientId: 'client_...', // the M2M application that has the trust rule tokenUrl: 'https:///oauth2/token', - environmentId: 'environment_...', + environmentId: 'environment_...', // optional identityTokenProvider: githubActions('https://api.workos.com'), }), }); @@ -131,6 +131,8 @@ const organizations = await workos.organizations.listOrganizations(); `clientId`, `tokenUrl`, `environmentId` and `scope` default to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL`, `WORKOS_ENVIRONMENT_ID` and `WORKOS_WIF_SCOPE` environment variables. Those variables only fill in fields you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. +`environmentId` is optional. WorkOS binds a workload identity client to exactly one environment, so the value selects nothing. Setting it is a safety check: the SDK sends it as the `x-url-environment-id` header on every API request, and a value that names a different environment gets `403 environment_mismatch`. When it is not set, the header is not sent. + ### Platform providers Each platform has its own package. The argument is the audience the identity token is requested for, which must match the audience of the trust rule. @@ -181,6 +183,8 @@ tokenFile('/var/run/secrets/tokens/workos'); tokenEnv('MY_PLATFORM_JWT'); ``` +WorkOS accepts an identity token for one exchange. The SDK makes a new exchange about every four minutes. If the file or variable still holds the same token then, that exchange fails with `invalid_grant`. So use `tokenFile` and `tokenEnv` for a source that something rewrites before each exchange, or for a job shorter than five minutes. The platform providers (GitHub Actions, Google Cloud, AWS) fetch a new token every time. + `tokenFile` needs a file system, so it is not exported from `@workos-inc/node/worker`. ### Errors diff --git a/src/workload-identity/constants.ts b/src/workload-identity/constants.ts index d6fa8d5f9..87ebac686 100644 --- a/src/workload-identity/constants.ts +++ b/src/workload-identity/constants.ts @@ -1,6 +1,9 @@ // @oagen-ignore-file -/** Sent with the environment ID on every workload identity API request. */ +/** + * Sent with the environment ID on every workload identity API request, when + * an environment ID is set. + */ export const ENVIRONMENT_ID_HEADER = 'x-url-environment-id'; export const JWT_BEARER_GRANT_TYPE = diff --git a/src/workload-identity/workload-identity-credentials.ts b/src/workload-identity/workload-identity-credentials.ts index e398920c3..bf5f03135 100644 --- a/src/workload-identity/workload-identity-credentials.ts +++ b/src/workload-identity/workload-identity-credentials.ts @@ -41,8 +41,13 @@ export interface WorkloadIdentityCredentialsOptions { */ tokenUrl?: string; /** - * The environment the workload acts on, sent with every API request. - * Defaults to `WORKOS_ENVIRONMENT_ID`. + * Optional. Defaults to `WORKOS_ENVIRONMENT_ID`, else not set. + * + * The server binds a workload identity client to exactly one environment, + * so this selects nothing. Setting it is a safety check: it is sent as the + * `x-url-environment-id` header on every API request, and a value that + * names a different environment gets `403 environment_mismatch`. When it is + * not set, the header is not sent. An empty string counts as not set. */ environmentId?: string; /** The API the access token is for. Defaults to `https://api.workos.com`. */ @@ -115,7 +120,7 @@ type ExchangeAttempt = export class WorkloadIdentityCredentials implements Credentials { private readonly clientId: string; private readonly tokenUrl: URL; - private readonly environmentId: string; + private readonly environmentId: string | undefined; private readonly resource: string; private readonly scope: string | undefined; private readonly identityTokenProvider: IdentityTokenProvider; @@ -141,8 +146,6 @@ export class WorkloadIdentityCredentials implements Credentials { ) { const clientId = options?.clientId || getEnv('WORKOS_CLIENT_ID'); const tokenUrl = options?.tokenUrl || getEnv('WORKOS_WIF_TOKEN_URL'); - const environmentId = - options?.environmentId || getEnv('WORKOS_ENVIRONMENT_ID'); if (!clientId) { throw missingSetting('clientId', 'WORKOS_CLIENT_ID'); @@ -150,9 +153,6 @@ export class WorkloadIdentityCredentials implements Credentials { if (!tokenUrl) { throw missingSetting('tokenUrl', 'WORKOS_WIF_TOKEN_URL'); } - if (!environmentId) { - throw missingSetting('environmentId', 'WORKOS_ENVIRONMENT_ID'); - } if (typeof options?.identityTokenProvider !== 'function') { throw new WorkloadIdentityError( 'invalid_configuration', @@ -180,7 +180,9 @@ export class WorkloadIdentityCredentials implements Credentials { } this.clientId = clientId; - this.environmentId = environmentId; + // Optional: an empty string counts as not set. + this.environmentId = + options.environmentId || getEnv('WORKOS_ENVIRONMENT_ID') || undefined; this.resource = options.resource || DEFAULT_RESOURCE; this.scope = options.scope || getEnv('WORKOS_WIF_SCOPE') || undefined; this.identityTokenProvider = options.identityTokenProvider; @@ -204,11 +206,16 @@ export class WorkloadIdentityCredentials implements Credentials { async resolve(context: CredentialContext = {}): Promise { const { token, generation } = await this.currentToken(context.signal); + const headers: Record = { + Authorization: `Bearer ${token}`, + }; + + if (this.environmentId) { + headers[ENVIRONMENT_ID_HEADER] = this.environmentId; + } + return { - headers: { - Authorization: `Bearer ${token}`, - [ENVIRONMENT_ID_HEADER]: this.environmentId, - }, + headers, generation, recoverable: true, }; diff --git a/src/workload-identity/workload-identity-error.ts b/src/workload-identity/workload-identity-error.ts index 4077e928d..e345f0157 100644 --- a/src/workload-identity/workload-identity-error.ts +++ b/src/workload-identity/workload-identity-error.ts @@ -9,19 +9,19 @@ const HINTS = new Map([ // OAuth codes returned by the token endpoint. [ 'invalid_grant', - 'The identity token did not match a trust rule for this application, or the token has expired. Check the issuer, audience and subject claims against the trust rule.', + 'The identity token was not accepted. Check its issuer, audience and subject claims against the trust rule, and that it has not expired. A token that was already exchanged is also refused: each exchange needs a new identity token.', ], [ 'invalid_target', - "The resource or audience is wrong. The trust rule's audience must match the audience the identity token was requested with, and the resource must be registered for the environment.", + 'The resource is not one the token endpoint accepts. Leave the resource unset to use the default, https://api.workos.com.', ], [ 'invalid_client', - 'Check that the client ID is the M2M application that has the trust rule.', + 'The client ID is unknown, or the application has no enabled trust rule. Check that the client ID is the M2M application that has the trust rule.', ], [ 'unauthorized_client', - 'This application is not allowed to use workload identity federation. Check that the feature is enabled for the environment and that the application has a trust rule.', + 'This application cannot use workload identity federation. Check that the feature is enabled for your team and that the application is bound to a non-production environment.', ], [ 'invalid_scope', diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts index f5935317c..d4bdd9179 100644 --- a/src/workload-identity/workload-identity.spec.ts +++ b/src/workload-identity/workload-identity.spec.ts @@ -190,7 +190,7 @@ describe('workload identity', () => { }); expect(exchanges[0].headers.has('authorization')).toBe(false); - const scoped = setup({ scope: 'organizations:write' }); + const scoped = setup({ scope: 'orgs:write' }); await scoped.workos.get('/organizations'); @@ -200,13 +200,13 @@ describe('workload identity', () => { assertion: 'assertion-1', client_id: CLIENT_ID, resource: 'https://api.workos.com', - scope: 'organizations:write', + scope: 'orgs:write', }); expect(form(exchanges[1])).not.toHaveProperty('client_secret'); expect(exchanges[1].headers.has('authorization')).toBe(false); }); - it('WIF-02: the API request carries the access token and the environment header', async () => { + it('WIF-02: (a) with an environment ID the API request carries the access token and the environment header', async () => { const { workos } = setup(); await expect(workos.get('/organizations')).resolves.toEqual({ @@ -221,6 +221,41 @@ describe('workload identity', () => { ); }); + it('WIF-02: (b) with no environment ID the API request carries the access token and no environment header', async () => { + // `afterEach` restores the variable. + delete process.env.WORKOS_ENVIRONMENT_ID; + + let built!: ReturnType; + expect(() => { + built = setup({ environmentId: undefined }); + }).not.toThrow(); + + await expect(built.workos.get('/organizations')).resolves.toEqual({ + data: { ok: true }, + }); + + expect(apiRequests).toHaveLength(1); + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + expect(apiRequests[0].headers.has('x-url-environment-id')).toBe(false); + }); + + it.each([ + ['an empty environmentId', { environmentId: '' }, undefined], + ['an empty WORKOS_ENVIRONMENT_ID', { environmentId: undefined }, ''], + ])( + 'WIF: %s counts as not set and sends no environment header', + async (_name, overrides, variable) => { + if (variable !== undefined) { + process.env.WORKOS_ENVIRONMENT_ID = variable; + } + + await setup(overrides).workos.get('/organizations'); + + expect(bearer(apiRequests[0])).toBe('Bearer access-1'); + expect(apiRequests[0].headers.has('x-url-environment-id')).toBe(false); + }, + ); + it('WIF-18: the exchange does not follow a redirect', async () => { // Real HTTP: a mocked fetch never follows a redirect, so it could not // tell whether the exchange would. @@ -980,7 +1015,7 @@ describe('workload identity', () => { await new WorkOS({ credentials: new WorkloadIdentityCredentials({ clientId: CLIENT_ID, - scope: 'organizations:write', + scope: 'orgs:write', environmentId: ENVIRONMENT_ID, identityTokenProvider: async () => 'assertion-1', }), @@ -989,7 +1024,7 @@ describe('workload identity', () => { expect(exchanges[3].url).toBe(ENV_TOKEN_URL); expect(form(exchanges[3])).toMatchObject({ client_id: CLIENT_ID, - scope: 'organizations:write', + scope: 'orgs:write', }); expect(apiRequests[3].headers.get('x-url-environment-id')).toBe( ENVIRONMENT_ID, @@ -1002,11 +1037,6 @@ describe('workload identity', () => { { clientId: undefined }, 'clientId is required (or set WORKOS_CLIENT_ID)', ], - [ - 'environmentId', - { environmentId: undefined }, - 'environmentId is required (or set WORKOS_ENVIRONMENT_ID)', - ], [ 'identityTokenProvider', { identityTokenProvider: undefined }, From a802a9824a188b94c6a4b90346f0c8f5ab79b609 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sat, 14 Nov 2026 11:21:47 -0800 Subject: [PATCH 07/14] fix(workload-identity): stop reading WORKOS_ENVIRONMENT_ID and correct the README examples environmentId now comes only from the caller's code. The variable was new in this work and exists nowhere else: not on main, not in the server, the CLI or the docs. The header it filled is an optional safety check, and a variable left in the environment could turn that check into a 403 environment_mismatch with no line of code to point at. Left out, undefined, null or an empty string all mean "not set": no x-url-environment-id header and no error. WORKOS_CLIENT_ID, WORKOS_WIF_TOKEN_URL and WORKOS_WIF_SCOPE are unchanged. WIF-02 (b) now sets the variable and checks that no header is sent. WIF-22 (c) and (d) no longer involve the environment ID. The README and doc comments are corrected in three places: - The tokenFile example was the path of a Kubernetes service account token, which the server refuses. It is now a file that another process writes, such as a sidecar or an earlier CI step. - tokenFile and tokenEnv suit a job shorter than four minutes, not five: the SDK exchanges again when the 300-second token has 60 seconds left. - environmentId is described as optional and set in code, and no variable is named for it. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 9 and 10) --- README.md | 10 +++--- src/workload-identity/token-file.ts | 4 ++- .../workload-identity-credentials.ts | 12 +++---- .../workload-identity.spec.ts | 31 +++++++------------ 4 files changed, 26 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 602447b34..11464dc07 100644 --- a/README.md +++ b/README.md @@ -129,9 +129,9 @@ const workos = new WorkOS({ const organizations = await workos.organizations.listOrganizations(); ``` -`clientId`, `tokenUrl`, `environmentId` and `scope` default to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL`, `WORKOS_ENVIRONMENT_ID` and `WORKOS_WIF_SCOPE` environment variables. Those variables only fill in fields you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. +`clientId`, `tokenUrl` and `scope` default to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` environment variables. Those variables only fill in fields you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. -`environmentId` is optional. WorkOS binds a workload identity client to exactly one environment, so the value selects nothing. Setting it is a safety check: the SDK sends it as the `x-url-environment-id` header on every API request, and a value that names a different environment gets `403 environment_mismatch`. When it is not set, the header is not sent. +`environmentId` is optional and is set only in code: no environment variable fills it. WorkOS binds a workload identity client to exactly one environment, so the value selects nothing. Setting it is a safety check: the SDK sends it as the `x-url-environment-id` header on every API request, and a value that names a different environment gets `403 environment_mismatch`. When it is not set, the header is not sent. ### Platform providers @@ -179,11 +179,13 @@ const credentials = new WorkloadIdentityCredentials({ ```ts import { tokenEnv, tokenFile } from '@workos-inc/node'; -tokenFile('/var/run/secrets/tokens/workos'); +// A file that another process writes, such as a sidecar or an earlier CI +// step that fetches a new token. +tokenFile('/run/workos/identity-token'); tokenEnv('MY_PLATFORM_JWT'); ``` -WorkOS accepts an identity token for one exchange. The SDK makes a new exchange about every four minutes. If the file or variable still holds the same token then, that exchange fails with `invalid_grant`. So use `tokenFile` and `tokenEnv` for a source that something rewrites before each exchange, or for a job shorter than five minutes. The platform providers (GitHub Actions, Google Cloud, AWS) fetch a new token every time. +WorkOS accepts an identity token for one exchange. The SDK makes a new exchange about every four minutes. If the file or variable still holds the same token then, that exchange fails with `invalid_grant`. So use `tokenFile` and `tokenEnv` for a source that something rewrites before each exchange, or for a job shorter than four minutes. The platform providers (GitHub Actions, Google Cloud, AWS) fetch a new token every time. `tokenFile` needs a file system, so it is not exported from `@workos-inc/node/worker`. diff --git a/src/workload-identity/token-file.ts b/src/workload-identity/token-file.ts index 154d589d6..1655b6300 100644 --- a/src/workload-identity/token-file.ts +++ b/src/workload-identity/token-file.ts @@ -36,7 +36,9 @@ function fileSystem(): FileSystem { * * @example * new WorkloadIdentityCredentials({ - * identityTokenProvider: tokenFile('/var/run/secrets/tokens/workos'), + * // A file that another process writes, such as a sidecar or an earlier CI + * // step that fetches a new token. + * identityTokenProvider: tokenFile('/run/workos/identity-token'), * }); */ export function tokenFile(path: string): IdentityTokenProvider { diff --git a/src/workload-identity/workload-identity-credentials.ts b/src/workload-identity/workload-identity-credentials.ts index bf5f03135..2a1140f19 100644 --- a/src/workload-identity/workload-identity-credentials.ts +++ b/src/workload-identity/workload-identity-credentials.ts @@ -41,7 +41,7 @@ export interface WorkloadIdentityCredentialsOptions { */ tokenUrl?: string; /** - * Optional. Defaults to `WORKOS_ENVIRONMENT_ID`, else not set. + * Optional, and set only here: no environment variable fills it. * * The server binds a workload identity client to exactly one environment, * so this selects nothing. Setting it is a safety check: it is sent as the @@ -133,8 +133,8 @@ export class WorkloadIdentityCredentials implements Credentials { private inflight: Promise | undefined; /** - * @param options - Omitted fields default from the environment; an explicit - * value always wins. + * @param options - An omitted `clientId`, `tokenUrl` or `scope` defaults + * from the environment; an explicit value always wins. * @param internals - Test seams. Not part of the public API. * @throws {WorkloadIdentityError} `invalid_configuration` when a required * setting is missing after the environment is consulted. @@ -180,9 +180,9 @@ export class WorkloadIdentityCredentials implements Credentials { } this.clientId = clientId; - // Optional: an empty string counts as not set. - this.environmentId = - options.environmentId || getEnv('WORKOS_ENVIRONMENT_ID') || undefined; + // Optional, and never read from the environment. An empty string counts + // as not set. + this.environmentId = options.environmentId || undefined; this.resource = options.resource || DEFAULT_RESOURCE; this.scope = options.scope || getEnv('WORKOS_WIF_SCOPE') || undefined; this.identityTokenProvider = options.identityTokenProvider; diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts index d4bdd9179..75369109d 100644 --- a/src/workload-identity/workload-identity.spec.ts +++ b/src/workload-identity/workload-identity.spec.ts @@ -126,7 +126,6 @@ describe('workload identity', () => { 'WORKOS_CLIENT_ID', 'WORKOS_WIF_TOKEN_URL', 'WORKOS_WIF_SCOPE', - 'WORKOS_ENVIRONMENT_ID', ]) { delete process.env[name]; } @@ -222,8 +221,8 @@ describe('workload identity', () => { }); it('WIF-02: (b) with no environment ID the API request carries the access token and no environment header', async () => { - // `afterEach` restores the variable. - delete process.env.WORKOS_ENVIRONMENT_ID; + // The SDK does not read this variable. `afterEach` restores it. + process.env.WORKOS_ENVIRONMENT_ID = 'environment_env'; let built!: ReturnType; expect(() => { @@ -240,16 +239,16 @@ describe('workload identity', () => { }); it.each([ - ['an empty environmentId', { environmentId: '' }, undefined], - ['an empty WORKOS_ENVIRONMENT_ID', { environmentId: undefined }, ''], + ['an empty', ''], + ['a null', null], ])( - 'WIF: %s counts as not set and sends no environment header', - async (_name, overrides, variable) => { - if (variable !== undefined) { - process.env.WORKOS_ENVIRONMENT_ID = variable; - } - - await setup(overrides).workos.get('/organizations'); + 'WIF: %s environmentId counts as not set and sends no environment header', + async (_name, environmentId) => { + await setup({ + environmentId, + } as Partial).workos.get( + '/organizations', + ); expect(bearer(apiRequests[0])).toBe('Bearer access-1'); expect(apiRequests[0].headers.has('x-url-environment-id')).toBe(false); @@ -994,7 +993,6 @@ describe('workload identity', () => { process.env.WORKOS_CLIENT_ID = 'client_env'; process.env.WORKOS_WIF_TOKEN_URL = ENV_TOKEN_URL; process.env.WORKOS_WIF_SCOPE = 'scope_env'; - process.env.WORKOS_ENVIRONMENT_ID = 'environment_env'; await new WorkOS({ credentials: new WorkloadIdentityCredentials({ @@ -1007,16 +1005,12 @@ describe('workload identity', () => { client_id: 'client_env', scope: 'scope_env', }); - expect(apiRequests[2].headers.get('x-url-environment-id')).toBe( - 'environment_env', - ); // (d) Explicit values win over the environment. await new WorkOS({ credentials: new WorkloadIdentityCredentials({ clientId: CLIENT_ID, scope: 'orgs:write', - environmentId: ENVIRONMENT_ID, identityTokenProvider: async () => 'assertion-1', }), }).get('/organizations'); @@ -1026,9 +1020,6 @@ describe('workload identity', () => { client_id: CLIENT_ID, scope: 'orgs:write', }); - expect(apiRequests[3].headers.get('x-url-environment-id')).toBe( - ENVIRONMENT_ID, - ); }); it.each([ From e306a19261e06725649fb69d471399e8f9ecaec8 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sat, 14 Nov 2026 11:29:17 -0800 Subject: [PATCH 08/14] fix(workload-identity): stop reading WORKOS_WIF_TOKEN_URL and WORKOS_WIF_SCOPE tokenUrl and scope now come only from the caller's code. WORKOS_CLIENT_ID is the only variable the credentials read. Both names came from the CLI spike, where variables are the only way to configure a command; an SDK takes code. With no scope the token carries every scope the application holds, so a variable left in the environment would change permissions with no line of code to point at. Adding a variable later breaks no one, and removing one after a release does. - tokenUrl is required. Missing or empty is an invalid_configuration error at construction: "tokenUrl is required". Its type is now `tokenUrl: string`, so TypeScript reports a missing one too. - scope is optional. Not set or empty means no scope field in the form. - clientId is unchanged: it still defaults from WORKOS_CLIENT_ID, and its error still names that variable. WIF-22 now sets both variables and checks that they are ignored: the POST goes to the token URL passed in code, the form has no scope, and credentials built with no token URL fail at construction. The README says WORKOS_CLIENT_ID is the only variable read. Every example, in the README and in the doc comments of the SDK and the three provider packages, passes the client ID and the token URL in code. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decision 11) --- README.md | 4 +- packages/workload-identity-aws/src/index.ts | 2 + packages/workload-identity-gcp/src/index.ts | 2 + .../src/index.ts | 2 + src/workload-identity/token-env.ts | 2 + src/workload-identity/token-file.ts | 2 + .../workload-identity-credentials.ts | 28 +++++---- .../workload-identity.spec.ts | 58 +++++++++++-------- 8 files changed, 63 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 11464dc07..351e2ff67 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ const workos = new WorkOS({ const organizations = await workos.organizations.listOrganizations(); ``` -`clientId`, `tokenUrl` and `scope` default to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` environment variables. Those variables only fill in fields you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. +`clientId` defaults to the `WORKOS_CLIENT_ID` environment variable, which is the only variable the credentials read. `tokenUrl` is required and `scope` is optional, and both are set only in code. The variable only fills in a `clientId` you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. `environmentId` is optional and is set only in code: no environment variable fills it. WorkOS binds a workload identity client to exactly one environment, so the value selects nothing. Setting it is a safety check: the SDK sends it as the `x-url-environment-id` header on every API request, and a value that names a different environment gets `403 environment_mismatch`. When it is not set, the header is not sent. @@ -167,6 +167,8 @@ A provider is any function that returns the identity token. Use a callback for a ```ts const credentials = new WorkloadIdentityCredentials({ + clientId: 'client_...', + tokenUrl: 'https:///oauth2/token', identityTokenProvider: async () => { const response = await fetch('https://identity.internal.example/token'); return response.text(); diff --git a/packages/workload-identity-aws/src/index.ts b/packages/workload-identity-aws/src/index.ts index bdb271eeb..ed6d705e0 100644 --- a/packages/workload-identity-aws/src/index.ts +++ b/packages/workload-identity-aws/src/index.ts @@ -17,6 +17,8 @@ import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'; * * @example * new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', * identityTokenProvider: awsSts('https://api.workos.com', 'us-east-1'), * }); */ diff --git a/packages/workload-identity-gcp/src/index.ts b/packages/workload-identity-gcp/src/index.ts index b6f96801f..204b612d6 100644 --- a/packages/workload-identity-gcp/src/index.ts +++ b/packages/workload-identity-gcp/src/index.ts @@ -33,6 +33,8 @@ const agent = new http.Agent(); * * @example * new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', * identityTokenProvider: gcpMetadata('https://api.workos.com'), * }); */ diff --git a/packages/workload-identity-github-actions/src/index.ts b/packages/workload-identity-github-actions/src/index.ts index e9375cebf..c2585810f 100644 --- a/packages/workload-identity-github-actions/src/index.ts +++ b/packages/workload-identity-github-actions/src/index.ts @@ -12,6 +12,8 @@ const REQUEST_TIMEOUT_MS = 10_000; * * @example * new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', * identityTokenProvider: githubActions('https://api.workos.com'), * }); */ diff --git a/src/workload-identity/token-env.ts b/src/workload-identity/token-env.ts index aca705d32..ed7523b8f 100644 --- a/src/workload-identity/token-env.ts +++ b/src/workload-identity/token-env.ts @@ -8,6 +8,8 @@ import type { IdentityTokenProvider } from './workload-identity-credentials'; * * @example * new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', * identityTokenProvider: tokenEnv('MY_PLATFORM_JWT'), * }); */ diff --git a/src/workload-identity/token-file.ts b/src/workload-identity/token-file.ts index 1655b6300..16c79187d 100644 --- a/src/workload-identity/token-file.ts +++ b/src/workload-identity/token-file.ts @@ -36,6 +36,8 @@ function fileSystem(): FileSystem { * * @example * new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', * // A file that another process writes, such as a sidecar or an earlier CI * // step that fetches a new token. * identityTokenProvider: tokenFile('/run/workos/identity-token'), diff --git a/src/workload-identity/workload-identity-credentials.ts b/src/workload-identity/workload-identity-credentials.ts index 2a1140f19..f0c779a8d 100644 --- a/src/workload-identity/workload-identity-credentials.ts +++ b/src/workload-identity/workload-identity-credentials.ts @@ -36,10 +36,10 @@ export interface WorkloadIdentityCredentialsOptions { /** The M2M application's client ID. Defaults to `WORKOS_CLIENT_ID`. */ clientId?: string; /** - * The token exchange endpoint. Defaults to `WORKOS_WIF_TOKEN_URL`. There is - * no built-in default. + * The token exchange endpoint. Required, and set only here: no environment + * variable fills it and there is no built-in default. */ - tokenUrl?: string; + tokenUrl: string; /** * Optional, and set only here: no environment variable fills it. * @@ -52,7 +52,10 @@ export interface WorkloadIdentityCredentialsOptions { environmentId?: string; /** The API the access token is for. Defaults to `https://api.workos.com`. */ resource?: string; - /** The scope to request. Defaults to `WORKOS_WIF_SCOPE`, else no scope. */ + /** + * The scope to request. Optional, and set only here: no environment + * variable fills it. Not set or empty means no scope is requested. + */ scope?: string; /** Returns the workload's identity token. */ identityTokenProvider: IdentityTokenProvider; @@ -133,8 +136,8 @@ export class WorkloadIdentityCredentials implements Credentials { private inflight: Promise | undefined; /** - * @param options - An omitted `clientId`, `tokenUrl` or `scope` defaults - * from the environment; an explicit value always wins. + * @param options - An omitted `clientId` defaults from the environment; an + * explicit value always wins. No other field is read from the environment. * @param internals - Test seams. Not part of the public API. * @throws {WorkloadIdentityError} `invalid_configuration` when a required * setting is missing after the environment is consulted. @@ -145,13 +148,16 @@ export class WorkloadIdentityCredentials implements Credentials { internals: WorkloadIdentityInternals = {}, ) { const clientId = options?.clientId || getEnv('WORKOS_CLIENT_ID'); - const tokenUrl = options?.tokenUrl || getEnv('WORKOS_WIF_TOKEN_URL'); + const tokenUrl = options?.tokenUrl; if (!clientId) { throw missingSetting('clientId', 'WORKOS_CLIENT_ID'); } if (!tokenUrl) { - throw missingSetting('tokenUrl', 'WORKOS_WIF_TOKEN_URL'); + throw new WorkloadIdentityError( + 'invalid_configuration', + 'tokenUrl is required', + ); } if (typeof options?.identityTokenProvider !== 'function') { throw new WorkloadIdentityError( @@ -180,11 +186,11 @@ export class WorkloadIdentityCredentials implements Credentials { } this.clientId = clientId; - // Optional, and never read from the environment. An empty string counts - // as not set. + // `environmentId` and `scope` are optional and never read from the + // environment. An empty string counts as not set. this.environmentId = options.environmentId || undefined; this.resource = options.resource || DEFAULT_RESOURCE; - this.scope = options.scope || getEnv('WORKOS_WIF_SCOPE') || undefined; + this.scope = options.scope || undefined; this.identityTokenProvider = options.identityTokenProvider; this.now = internals.now ?? (() => Date.now()); this.sleep = diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts index 75369109d..05191f85b 100644 --- a/src/workload-identity/workload-identity.spec.ts +++ b/src/workload-identity/workload-identity.spec.ts @@ -121,12 +121,7 @@ describe('workload identity', () => { beforeEach(() => { process.env = { ...OLD_ENV }; - for (const name of [ - 'WORKOS_API_KEY', - 'WORKOS_CLIENT_ID', - 'WORKOS_WIF_TOKEN_URL', - 'WORKOS_WIF_SCOPE', - ]) { + for (const name of ['WORKOS_API_KEY', 'WORKOS_CLIENT_ID']) { delete process.env[name]; } @@ -851,16 +846,16 @@ describe('workload identity', () => { expect(valid.workos.key).toBeUndefined(); expect(bearer(apiRequests[0])).toBe('Bearer access-1'); - // (b) No token URL, explicitly or in the environment. + // (b) No token URL. const construct = () => new WorkloadIdentityCredentials({ clientId: CLIENT_ID, environmentId: ENVIRONMENT_ID, identityTokenProvider: async () => 'assertion-1', - }); + } as WorkloadIdentityCredentialsOptions); expect(construct).toThrow(WorkloadIdentityError); expect(construct).toThrow( - 'invalid_configuration: Workload identity credentials are missing a required setting. tokenUrl is required (or set WORKOS_WIF_TOKEN_URL)', + /^invalid_configuration: Workload identity credentials are missing a required setting\. tokenUrl is required$/, ); // (c) Valid credentials whose exchange fails. @@ -969,7 +964,7 @@ describe('workload identity', () => { } }); - it('WIF-22: tokenEnv and callback providers supply the assertion, and omitted fields default from the environment', async () => { + it('WIF-22: tokenEnv and callback providers supply the assertion, and only clientId defaults from the environment', async () => { // (a) tokenEnv reads the variable on every call. process.env.MY_JWT = 'assertion-env'; await setup({ @@ -988,38 +983,50 @@ describe('workload identity', () => { }).workos.get('/organizations'); expect(form(exchanges[1]).assertion).toBe('assertion-cb'); - // (c) Only a provider: everything else comes from the environment. - const ENV_TOKEN_URL = 'https://env.workos.test/oauth2/token'; + // (c) A provider and the token URL: the client ID comes from the + // environment. The SDK reads neither of the other two variables. process.env.WORKOS_CLIENT_ID = 'client_env'; - process.env.WORKOS_WIF_TOKEN_URL = ENV_TOKEN_URL; + process.env.WORKOS_WIF_TOKEN_URL = + 'https://ignored.example.test/oauth2/token'; process.env.WORKOS_WIF_SCOPE = 'scope_env'; await new WorkOS({ credentials: new WorkloadIdentityCredentials({ + tokenUrl: TOKEN_URL, identityTokenProvider: async () => 'assertion-1', }), }).get('/organizations'); - expect(exchanges[2].url).toBe(ENV_TOKEN_URL); - expect(form(exchanges[2])).toMatchObject({ - client_id: 'client_env', - scope: 'scope_env', - }); + expect(exchanges[2].url).toBe(TOKEN_URL); + expect(form(exchanges[2]).client_id).toBe('client_env'); + expect(form(exchanges[2])).not.toHaveProperty('scope'); - // (d) Explicit values win over the environment. + // (d) An explicit client ID wins over the variable. await new WorkOS({ credentials: new WorkloadIdentityCredentials({ clientId: CLIENT_ID, - scope: 'orgs:write', + tokenUrl: TOKEN_URL, identityTokenProvider: async () => 'assertion-1', }), }).get('/organizations'); - expect(exchanges[3].url).toBe(ENV_TOKEN_URL); - expect(form(exchanges[3])).toMatchObject({ - client_id: CLIENT_ID, - scope: 'orgs:write', - }); + expect(exchanges[3].url).toBe(TOKEN_URL); + expect(form(exchanges[3]).client_id).toBe(CLIENT_ID); + + // (e) No token URL: the variable does not fill it. + let error: WorkloadIdentityError | undefined; + try { + new WorkloadIdentityCredentials({ + identityTokenProvider: async () => 'assertion-1', + } as WorkloadIdentityCredentialsOptions); + } catch (e) { + error = e as WorkloadIdentityError; + } + + expect(error).toBeInstanceOf(WorkloadIdentityError); + expect(error?.code).toBe('invalid_configuration'); + expect(error?.description).toBe('tokenUrl is required'); + expect(exchanges).toHaveLength(4); }); it.each([ @@ -1028,6 +1035,7 @@ describe('workload identity', () => { { clientId: undefined }, 'clientId is required (or set WORKOS_CLIENT_ID)', ], + ['tokenUrl', { tokenUrl: '' }, 'tokenUrl is required'], [ 'identityTokenProvider', { identityTokenProvider: undefined }, From 1312cced39a5a6e6edc58e099e2d33d4a6220040 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 16 Nov 2026 15:09:38 -0500 Subject: [PATCH 09/14] fix(workload-identity): require an https token URL WorkloadIdentityCredentials now rejects any tokenUrl that is not an absolute https URL. The POST to the token URL carries the workload's identity token and the response carries the access token, so neither may travel over plain HTTP. workos-php already has this rule, and every SDK now follows it. - The check runs at construction. A rejected URL is an invalid_configuration error: "tokenUrl must be an absolute https URL". The same text replaces "tokenUrl is not a valid URL" and "tokenUrl must be an http or https URL". - Rejected: http:// on any host, localhost and loopback addresses included, a URL with no scheme, a URL with no host and any other scheme. The scheme is matched without regard to case, so HTTPS:// is accepted. - The scheme and the two slashes are checked in the text before the URL is parsed. The parser repairs https:/path and https:///path into a URL whose host is the first path segment, which would let a URL with no host through. - No option, environment variable or test seam relaxes the rule. WIF-18 is the one test that talks to a real plain-HTTP server. It now passes an https token URL and moves the endpoint under the credentials: its stand-in for fetch sends the request the SDK built, unchanged apart from the address, to the local server. The GCP provider's test moves the metadata host the same way. The SDK gains no setting for it. The README and the TSDoc on tokenUrl say the URL must be https. --- README.md | 2 + .../workload-identity-credentials.ts | 62 +++++++++++----- .../workload-identity.spec.ts | 73 ++++++++++++++++--- 3 files changed, 108 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 351e2ff67..ec0ea07ae 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,8 @@ const organizations = await workos.organizations.listOrganizations(); `clientId` defaults to the `WORKOS_CLIENT_ID` environment variable, which is the only variable the credentials read. `tokenUrl` is required and `scope` is optional, and both are set only in code. The variable only fills in a `clientId` you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. +`tokenUrl` must be an absolute `https` URL. The request to it carries the workload's identity token and the response carries the access token, so any other URL is rejected when the credentials are constructed, with a `WorkloadIdentityError` whose code is `invalid_configuration`. That includes `http://localhost` and other loopback addresses. + `environmentId` is optional and is set only in code: no environment variable fills it. WorkOS binds a workload identity client to exactly one environment, so the value selects nothing. Setting it is a safety check: the SDK sends it as the `x-url-environment-id` header on every API request, and a value that names a different environment gets `403 environment_mismatch`. When it is not set, the header is not sent. ### Platform providers diff --git a/src/workload-identity/workload-identity-credentials.ts b/src/workload-identity/workload-identity-credentials.ts index f0c779a8d..943a00fc2 100644 --- a/src/workload-identity/workload-identity-credentials.ts +++ b/src/workload-identity/workload-identity-credentials.ts @@ -38,6 +38,11 @@ export interface WorkloadIdentityCredentialsOptions { /** * The token exchange endpoint. Required, and set only here: no environment * variable fills it and there is no built-in default. + * + * It must be an absolute `https` URL. The request to it carries the + * workload's identity token and the response carries the access token, so + * any other URL is rejected when the credentials are constructed. That + * includes `http://localhost` and other loopback addresses. */ tokenUrl: string; /** @@ -140,7 +145,8 @@ export class WorkloadIdentityCredentials implements Credentials { * explicit value always wins. No other field is read from the environment. * @param internals - Test seams. Not part of the public API. * @throws {WorkloadIdentityError} `invalid_configuration` when a required - * setting is missing after the environment is consulted. + * setting is missing after the environment is consulted, or when `tokenUrl` + * is not an absolute `https` URL. */ constructor( options: WorkloadIdentityCredentialsOptions, @@ -166,25 +172,7 @@ export class WorkloadIdentityCredentials implements Credentials { ); } - try { - this.tokenUrl = new URL(tokenUrl); - } catch { - throw new WorkloadIdentityError( - 'invalid_configuration', - 'tokenUrl is not a valid URL', - ); - } - - if ( - this.tokenUrl.protocol !== 'https:' && - this.tokenUrl.protocol !== 'http:' - ) { - throw new WorkloadIdentityError( - 'invalid_configuration', - 'tokenUrl must be an http or https URL', - ); - } - + this.tokenUrl = httpsUrl(tokenUrl); this.clientId = clientId; // `environmentId` and `scope` are optional and never read from the // environment. An empty string counts as not set. @@ -535,6 +523,40 @@ function missingSetting(field: string, variable: string) { ); } +/** + * Parses the token URL, which must be an absolute `https` URL with a host. + * The exchange POST carries the workload's identity token and the response + * carries the access token, so no other scheme is accepted, on any host. + */ +function httpsUrl(tokenUrl: string): URL { + const invalid = () => + new WorkloadIdentityError( + 'invalid_configuration', + 'tokenUrl must be an absolute https URL', + ); + + // Checked in the text first: the URL parser repairs `https:/path` and + // `https:///path` into a URL whose host is the first path segment. + if (!/^https:\/\/[^\s/\\?#]/i.test(tokenUrl)) { + throw invalid(); + } + + let url: URL; + + try { + url = new URL(tokenUrl); + } catch { + throw invalid(); + } + + // The parsed URL is the one the request is sent to. + if (url.protocol !== 'https:' || !url.hostname) { + throw invalid(); + } + + return url; +} + /** * Settles with `work`, or rejects with `reason()` as soon as `signal` aborts. * `work` is left running either way. diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts index 05191f85b..e2851d938 100644 --- a/src/workload-identity/workload-identity.spec.ts +++ b/src/workload-identity/workload-identity.spec.ts @@ -255,9 +255,6 @@ describe('workload identity', () => { // tell whether the exchange would. const nativeFetch = (globalThis as Record) .__workosNativeFetch as typeof globalThis.fetch; - fetch.mockImplementation((input, init) => - nativeFetch(input as string, init), - ); const listen = async (handler: http.RequestListener) => { const server = http.createServer(handler); @@ -280,10 +277,26 @@ describe('workload identity', () => { res.end(); }); + // The local servers speak plain HTTP and the credentials take only an + // https token URL, with no setting that relaxes it. So the test moves + // the token endpoint under them: the request the SDK builds is sent + // unchanged apart from the address, and a request for anything other + // than the token URL fails the test. + const requested: string[] = []; + fetch.mockImplementation(async (input, init) => { + requested.push(String(input)); + + if (input !== TOKEN_URL) { + throw new Error(`Unexpected request to ${String(input)}`); + } + + return nativeFetch(token.url, init); + }); + try { const credentials = new WorkloadIdentityCredentials({ clientId: CLIENT_ID, - tokenUrl: token.url, + tokenUrl: TOKEN_URL, environmentId: ENVIRONMENT_ID, identityTokenProvider: async () => 'assertion-1', }); @@ -292,6 +305,7 @@ describe('workload identity', () => { expect(error).toBeInstanceOf(WorkloadIdentityError); expect(error.code).toBe('exchange_failed'); + expect(requested).toEqual([TOKEN_URL]); expect(tokenRequests).toEqual(['POST']); expect(targetRequests).toEqual([]); } finally { @@ -1044,7 +1058,7 @@ describe('workload identity', () => { [ 'a valid tokenUrl', { tokenUrl: 'not a url' }, - 'tokenUrl is not a valid URL', + 'tokenUrl must be an absolute https URL', ], ])( 'WIF: credentials without %s fail at construction', @@ -1069,10 +1083,51 @@ describe('workload identity', () => { expect(exchanges.map((exchange) => exchange.url)).toEqual([tokenUrl]); }); - it('WIF: a token URL that is not http or https fails at construction', () => { - expect(() => setup({ tokenUrl: 'file:///oauth2/token' })).toThrow( - 'tokenUrl must be an http or https URL', - ); + it.each([ + ['an http URL', 'http://example.com/oauth2/token'], + ['an http URL on localhost', 'http://localhost:8080/oauth2/token'], + ['an http URL on a loopback address', 'http://127.0.0.1/oauth2/token'], + ['an http URL in upper case', 'HTTP://example.com/oauth2/token'], + ['a URL with no scheme', 'auth.workos.test/oauth2/token'], + [ + 'a URL with no scheme and two slashes', + '//auth.workos.test/oauth2/token', + ], + ['a path', '/oauth2/token'], + ['an https URL with no host', 'https:///oauth2/token'], + ['an https URL with one slash and no host', 'https:/oauth2/token'], + ['an https URL with no slashes and no host', 'https:oauth2/token'], + ['an https URL with nothing after the scheme', 'https://'], + ['a URL with another scheme', 'file:///oauth2/token'], + ['a WebSocket URL', 'wss://auth.workos.test/oauth2/token'], + ['an https URL after a space', ' https://auth.workos.test/oauth2/token'], + ])( + 'WIF: a token URL that is %s fails at construction', + (_name, tokenUrl) => { + let error: WorkloadIdentityError | undefined; + try { + setup({ tokenUrl }); + } catch (e) { + error = e as WorkloadIdentityError; + } + + expect(error).toBeInstanceOf(WorkloadIdentityError); + expect(error?.code).toBe('invalid_configuration'); + expect(error?.description).toBe( + 'tokenUrl must be an absolute https URL', + ); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + + it('WIF: a token URL with the https scheme in upper case is accepted', async () => { + const { workos } = setup({ + tokenUrl: 'HTTPS://auth.workos.test/oauth2/token', + }); + + await workos.get('/organizations'); + + expect(exchanges.map((exchange) => exchange.url)).toEqual([TOKEN_URL]); }); it('WIF: tokenFile fails as a provider error in a runtime with no file system', async () => { From 700dcd9ddf7136a111dad71738ae729dc8abbece Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 11:22:05 -0500 Subject: [PATCH 10/14] fix(workload-identity): Send API-key requests in the turn they are made The client resolves its credentials before every attempt, and for an API key that put a promise between making a request and sending it. A caller that aborted right after making the request then found nothing in flight: two of main's new tests for the signal option wait on a fetch that was never called. An API key has nothing to wait for, so its snapshot is now read without a promise, and the request is sent in the same turn, as on main. Other credentials are still awaited. --- src/common/net/credentials.ts | 10 ++++++++++ src/common/net/fetch-client.ts | 12 ++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/common/net/credentials.ts b/src/common/net/credentials.ts index 21f14c72d..9826ff5d9 100644 --- a/src/common/net/credentials.ts +++ b/src/common/net/credentials.ts @@ -54,6 +54,16 @@ export class StaticKeyCredentials implements Credentials { return Promise.resolve(this.snapshot); } + /** + * The same snapshot without a promise. The HTTP client uses it so that a + * request made with an API key is sent in the turn it was made, as it was + * before credentials existed: a caller that aborts right after making the + * request still finds it in flight. + */ + resolveNow(): CredentialSnapshot { + return this.snapshot; + } + invalidate(): void { // A static key has no newer credential to fetch. } diff --git a/src/common/net/fetch-client.ts b/src/common/net/fetch-client.ts index 9c15949dd..09e3d8773 100644 --- a/src/common/net/fetch-client.ts +++ b/src/common/net/fetch-client.ts @@ -13,6 +13,7 @@ import { HttpClientResponse, } from './http-client'; import { ParseError } from '../exceptions/parse-error'; +import { StaticKeyCredentials } from './credentials'; import type { Credentials, CredentialSnapshot } from './credentials'; type FetchHttpClientOptions = HttpClientOptions; @@ -255,11 +256,14 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { try { // Resolved for every attempt, under the attempt's deadline, so a retry // never sends a token that expired while the request was backing off. + // Awaited only when there is something to wait for: with an API key, or + // with no credentials, the request is sent in the turn it was made. const resolving = this.resolveCredentials( headers, abortController.signal, ); - const snapshot = resolving ? await resolving : undefined; + const snapshot = + resolving && 'then' in resolving ? await resolving : resolving; if (attempt) { attempt.snapshot = snapshot; } @@ -532,7 +536,7 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { private resolveCredentials( headers: RequestHeaders | undefined, signal: AbortSignal, - ): Promise | undefined { + ): CredentialSnapshot | Promise | undefined { if ( !this.credentials || FetchHttpClient.hasHeader(headers, 'Authorization') @@ -540,6 +544,10 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { return undefined; } + if (this.credentials instanceof StaticKeyCredentials) { + return this.credentials.resolveNow(); + } + return this.credentials.resolve({ signal }); } From 49754dbe79046ef0d49b37e98b10fdc372debbe7 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 13:22:14 -0500 Subject: [PATCH 11/14] fix(workload-identity): Refuse client-secret methods on a credentials client Some methods send the API key in the request body as `client_secret`: the user management `authenticateWith...` calls that reach `/user_management/authenticate`, and `sso.getProfileAndToken`. A client built with `credentials` has no API key, but it passed the API-key check, so these requests went out with no client secret and with the workload's access token as the bearer. That token is not a client secret. The methods that also serve public clients (`authenticateWithCode`, `authenticateWithRefreshToken` and `sso.getProfileAndToken`) switched to their public-client form without saying so. These methods now throw `ApiKeyRequiredException` on such a client before any request or token exchange is made. The message names the method and says to use a client built with an API key. Refreshing a sealed session goes through `authenticateWithRefreshToken`, so it throws too. The check is on the credentials, not on the missing key. A public client, which has neither, keeps its PKCE and refresh token flows, and a client with an API key is unchanged. `authenticateWithCodeAndVerifier` never sends a client secret and is not checked. --- README.md | 2 + .../exceptions/api-key-required.exception.ts | 14 +- src/sso/sso.ts | 6 + src/user-management/user-management.ts | 40 ++ .../workload-identity.spec.ts | 347 +++++++++++++++++- src/workos.ts | 28 +- 6 files changed, 431 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f59ea968b..5e96816e1 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,8 @@ const organizations = await workos.organizations.listOrganizations(); `clientId` defaults to the `WORKOS_CLIENT_ID` environment variable, which is the only variable the credentials read. `tokenUrl` is required and `scope` is optional, and both are set only in code. The variable only fills in a `clientId` you leave out: workload identity is used only when you pass `credentials`. A client built with `credentials` ignores `WORKOS_API_KEY`, and passing both `credentials` and an API key is an error. +Calls that send the API key as the client secret throw an `ApiKeyRequiredException` on a client built with `credentials`, before any request is sent, so make them with a client built with an API key: `sso.getProfileAndToken`, a sealed session's `refresh`, and in `userManagement` the methods `authenticateWithCode`, `authenticateWithPassword`, `authenticateWithMagicAuth`, `authenticateWithRefreshToken`, `authenticateWithTotp`, `authenticateWithEmailVerification`, `authenticateWithOrganizationSelection`, `authenticateWithRadarSmsChallenge` and `authenticateWithRadarEmailChallenge`. + `tokenUrl` must be an absolute `https` URL. The request to it carries the workload's identity token and the response carries the access token, so any other URL is rejected when the credentials are constructed, with a `WorkloadIdentityError` whose code is `invalid_configuration`. That includes `http://localhost` and other loopback addresses. `environmentId` is optional and is set only in code: no environment variable fills it. WorkOS binds a workload identity client to exactly one environment, so the value selects nothing. Setting it is a safety check: the SDK sends it as the `x-url-environment-id` header on every API request, and a value that names a different environment gets `403 environment_mismatch`. When it is not set, the header is not sent. diff --git a/src/common/exceptions/api-key-required.exception.ts b/src/common/exceptions/api-key-required.exception.ts index b2b6a7f1a..184ed380d 100644 --- a/src/common/exceptions/api-key-required.exception.ts +++ b/src/common/exceptions/api-key-required.exception.ts @@ -3,11 +3,17 @@ export class ApiKeyRequiredException extends Error { readonly name = 'ApiKeyRequiredException'; readonly path: string; - constructor(path: string) { + /** + * @param path - The API path that needs an API key. + * @param message - Replaces the default message, for a caller that can say + * more exactly why the API key is needed. + */ + constructor(path: string, message?: string) { super( - `API key required for "${path}". ` + - `For server-side apps, initialize with: new WorkOS("sk_..."). ` + - `For browser/mobile/CLI apps, use authenticateWithCodeAndVerifier() and authenticateWithRefreshToken() which work without an API key.`, + message ?? + `API key required for "${path}". ` + + `For server-side apps, initialize with: new WorkOS("sk_..."). ` + + `For browser/mobile/CLI apps, use authenticateWithCodeAndVerifier() and authenticateWithRefreshToken() which work without an API key.`, ); this.path = path; } diff --git a/src/sso/sso.ts b/src/sso/sso.ts index 721dd038b..cac9d9986 100644 --- a/src/sso/sso.ts +++ b/src/sso/sso.ts @@ -230,7 +230,11 @@ export class SSO { * Using PKCE with confidential clients is recommended by OAuth 2.1 for defense * in depth and provides additional CSRF protection on the authorization flow. * + * A client built with credentials has no API key and is not a public client, + * so this method throws on it whether or not a codeVerifier is given. + * * @throws Error if neither codeVerifier nor API key is available + * @throws ApiKeyRequiredException if the client was built with credentials */ async getProfileAndToken< CustomAttributesType extends UnknownRecord = UnknownRecord, @@ -241,6 +245,8 @@ export class SSO { }: GetProfileAndTokenOptions): Promise< ProfileAndToken > { + this.workos.requireApiKeyAsClientSecret('getProfileAndToken', '/sso/token'); + // Validate codeVerifier is not an empty string (common mistake) if (codeVerifier !== undefined && codeVerifier.trim() === '') { throw new TypeError( diff --git a/src/user-management/user-management.ts b/src/user-management/user-management.ts index 87d9fd778..50c8209b0 100644 --- a/src/user-management/user-management.ts +++ b/src/user-management/user-management.ts @@ -229,6 +229,19 @@ export class UserManagement { } return resolved; } + + /** + * Called first by every method that sends the API key as the client secret. + * A client built with credentials has no API key to send, so the method + * throws before any request is made. + * @throws ApiKeyRequiredException when the client was built with credentials + */ + private requireApiKeyAsClientSecret(methodName: string): void { + this.workos.requireApiKeyAsClientSecret( + methodName, + '/user_management/authenticate', + ); + } // @oagen-ignore-end // @oagen-ignore-start @@ -360,6 +373,8 @@ export class UserManagement { async authenticateWithMagicAuth( payload: AuthenticateWithMagicAuthOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithMagicAuth'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -385,6 +400,8 @@ export class UserManagement { async authenticateWithPassword( payload: AuthenticateWithPasswordOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithPassword'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -417,11 +434,17 @@ export class UserManagement { * Using PKCE with confidential clients is recommended by OAuth 2.1 for defense * in depth and provides additional CSRF protection on the authorization flow. * + * A client built with credentials has no API key and is not a public client, + * so this method throws on it whether or not a codeVerifier is given. + * * @throws Error if neither codeVerifier nor API key is available + * @throws ApiKeyRequiredException if the client was built with credentials */ async authenticateWithCode( payload: AuthenticateWithCodeOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithCode'); + const { session, clientId, codeVerifier, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -502,10 +525,17 @@ export class UserManagement { * Refresh an access token using a refresh token. * Automatically detects public client mode - if no API key is configured, * omits client_secret from the request. + * + * A client built with credentials has no API key and is not a public client, + * so this method throws on it. + * + * @throws ApiKeyRequiredException if the client was built with credentials */ async authenticateWithRefreshToken( payload: AuthenticateWithRefreshTokenOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithRefreshToken'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); const isPublicClient = !this.workos.key; @@ -539,6 +569,8 @@ export class UserManagement { async authenticateWithTotp( payload: AuthenticateWithTotpOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithTotp'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -564,6 +596,8 @@ export class UserManagement { async authenticateWithEmailVerification( payload: AuthenticateWithEmailVerificationOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithEmailVerification'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -589,6 +623,8 @@ export class UserManagement { async authenticateWithOrganizationSelection( payload: AuthenticateWithOrganizationSelectionOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithOrganizationSelection'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -633,6 +669,8 @@ export class UserManagement { async authenticateWithRadarSmsChallenge( payload: AuthenticateWithRadarSmsChallengeOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithRadarSmsChallenge'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); @@ -658,6 +696,8 @@ export class UserManagement { async authenticateWithRadarEmailChallenge( payload: AuthenticateWithRadarEmailChallengeOptions, ): Promise { + this.requireApiKeyAsClientSecret('authenticateWithRadarEmailChallenge'); + const { session, clientId, ...remainingPayload } = payload; const resolvedClientId = this.resolveClientId(clientId); diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts index e2851d938..c24cd5442 100644 --- a/src/workload-identity/workload-identity.spec.ts +++ b/src/workload-identity/workload-identity.spec.ts @@ -7,7 +7,12 @@ import os from 'node:os'; import path from 'node:path'; import { inspect } from 'node:util'; import { version } from '../../package.json'; -import { UnauthorizedException } from '../common/exceptions'; +import { sealData } from '../common/crypto/seal'; +import { + ApiKeyRequiredException, + UnauthorizedException, +} from '../common/exceptions'; +import userFixture from '../user-management/fixtures/user.json'; import { tokenEnv, tokenFile, @@ -943,6 +948,346 @@ describe('workload identity', () => { }); }); + describe('methods that send the API key as the client secret', () => { + // The application users sign in to. It is not the workload identity + // client. + const APP_CLIENT_ID = 'client_app'; + const pending = { + clientId: APP_CLIENT_ID, + pendingAuthenticationToken: 'pending_token', + }; + + const needsApiKey = (method: string) => + `${method} needs an API key: this request sends it as the client secret. ` + + 'A client that authenticates with workload identity has no API key, ' + + 'so use a client built with one for this call.'; + + // Every user management method that sends `client_secret`. + // `authenticateWithCode` is here with and without a code verifier. + const userManagementCalls: Array< + [string, string, (workos: WorkOS) => Promise] + > = [ + [ + 'authenticateWithPassword', + 'authenticateWithPassword', + (workos) => + workos.userManagement.authenticateWithPassword({ + clientId: APP_CLIENT_ID, + email: 'user@example.com', + password: 'password', + }), + ], + [ + 'authenticateWithMagicAuth', + 'authenticateWithMagicAuth', + (workos) => + workos.userManagement.authenticateWithMagicAuth({ + clientId: APP_CLIENT_ID, + email: 'user@example.com', + code: '123456', + }), + ], + [ + 'authenticateWithCode', + 'authenticateWithCode', + (workos) => + workos.userManagement.authenticateWithCode({ + clientId: APP_CLIENT_ID, + code: 'authorization_code', + }), + ], + [ + 'authenticateWithCode with a code verifier', + 'authenticateWithCode', + (workos) => + workos.userManagement.authenticateWithCode({ + clientId: APP_CLIENT_ID, + code: 'authorization_code', + codeVerifier: 'code_verifier', + }), + ], + [ + 'authenticateWithRefreshToken', + 'authenticateWithRefreshToken', + (workos) => + workos.userManagement.authenticateWithRefreshToken({ + clientId: APP_CLIENT_ID, + refreshToken: 'refresh_token', + }), + ], + [ + 'authenticateWithTotp', + 'authenticateWithTotp', + (workos) => + workos.userManagement.authenticateWithTotp({ + ...pending, + code: '123456', + authenticationChallengeId: 'auth_challenge_123', + }), + ], + [ + 'authenticateWithEmailVerification', + 'authenticateWithEmailVerification', + (workos) => + workos.userManagement.authenticateWithEmailVerification({ + ...pending, + code: '123456', + }), + ], + [ + 'authenticateWithOrganizationSelection', + 'authenticateWithOrganizationSelection', + (workos) => + workos.userManagement.authenticateWithOrganizationSelection({ + ...pending, + organizationId: 'org_123', + }), + ], + [ + 'authenticateWithRadarSmsChallenge', + 'authenticateWithRadarSmsChallenge', + (workos) => + workos.userManagement.authenticateWithRadarSmsChallenge({ + ...pending, + code: '123456', + verificationId: 'verification_123', + phoneNumber: '+15555550123', + }), + ], + [ + 'authenticateWithRadarEmailChallenge', + 'authenticateWithRadarEmailChallenge', + (workos) => + workos.userManagement.authenticateWithRadarEmailChallenge({ + ...pending, + code: '123456', + radarChallengeId: 'radar_challenge_123', + }), + ], + ]; + + const authenticationResponse = (): Reply => ({ + json: { + user: userFixture, + access_token: 'user_access_token', + refresh_token: 'user_refresh_token', + }, + }); + + const profileAndToken = (): Reply => ({ + json: { + access_token: 'sso_access_token', + profile: { + object: 'profile', + id: 'prof_123', + idp_id: '123', + organization_id: 'org_123', + connection_id: 'conn_123', + connection_type: 'OktaSAML', + email: 'user@example.com', + raw_attributes: {}, + }, + }, + }); + + it.each(userManagementCalls)( + 'WIF: userManagement.%s throws before any request on a client built with credentials', + async (_name, method, call) => { + const { workos, provider } = setup(); + + const error = await call(workos).catch((thrown: unknown) => thrown); + + expect(error).toBeInstanceOf(ApiKeyRequiredException); + expect(error).toMatchObject({ + message: needsApiKey(method), + path: '/user_management/authenticate', + }); + // No exchange and no API request. + expect(fetch).not.toHaveBeenCalled(); + expect(provider).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['with no code verifier', undefined], + ['with a code verifier', 'code_verifier'], + ])( + 'WIF: sso.getProfileAndToken %s throws before any request on a client built with credentials', + async (_name, codeVerifier) => { + const { workos, provider } = setup(); + + const error = await workos.sso + .getProfileAndToken({ + clientId: APP_CLIENT_ID, + code: 'authorization_code', + codeVerifier, + }) + .catch((thrown: unknown) => thrown); + + expect(error).toBeInstanceOf(ApiKeyRequiredException); + expect(error).toMatchObject({ + message: needsApiKey('getProfileAndToken'), + path: '/sso/token', + }); + expect(fetch).not.toHaveBeenCalled(); + expect(provider).not.toHaveBeenCalled(); + }, + ); + + it('WIF: refreshing a sealed session throws before any request on a client built with credentials', async () => { + const { credentials, provider } = setup(); + const workos = new WorkOS({ clientId: APP_CLIENT_ID, credentials }); + const cookiePassword = 'a cookie password of at least 32 characters'; + const encode = (value: object) => + Buffer.from(JSON.stringify(value)).toString('base64url'); + const session = workos.userManagement.loadSealedSession({ + sessionData: await sealData( + { + // Decoded, never verified, before the refresh request. + accessToken: `${encode({ alg: 'none' })}.${encode({ sid: 'session_123' })}.`, + refreshToken: 'refresh_token', + user: userFixture, + }, + { password: cookiePassword }, + ), + cookiePassword, + }); + + // Thrown, not reported as a failed refresh: the session is not over. + const error = await session.refresh().catch((thrown: unknown) => thrown); + + expect(error).toBeInstanceOf(ApiKeyRequiredException); + expect(error).toMatchObject({ + message: needsApiKey('authenticateWithRefreshToken'), + }); + expect(fetch).not.toHaveBeenCalled(); + expect(provider).not.toHaveBeenCalled(); + }); + + it('WIF: a public client still exchanges a code with a verifier and refreshes with no client secret', async () => { + // Neither an API key nor credentials. + const workos = new WorkOS({ clientId: APP_CLIENT_ID }); + + api = (_count, request) => + request.url.endsWith('/sso/token') + ? profileAndToken() + : authenticationResponse(); + + await expect( + workos.userManagement.authenticateWithCode({ + code: 'authorization_code', + codeVerifier: 'code_verifier', + }), + ).resolves.toMatchObject({ accessToken: 'user_access_token' }); + await expect( + workos.userManagement.authenticateWithCodeAndVerifier({ + clientId: APP_CLIENT_ID, + code: 'authorization_code', + codeVerifier: 'code_verifier', + }), + ).resolves.toMatchObject({ accessToken: 'user_access_token' }); + await expect( + workos.userManagement.authenticateWithRefreshToken({ + refreshToken: 'refresh_token', + }), + ).resolves.toMatchObject({ refreshToken: 'user_refresh_token' }); + await expect( + workos.sso.getProfileAndToken({ + clientId: APP_CLIENT_ID, + code: 'authorization_code', + codeVerifier: 'code_verifier', + }), + ).resolves.toMatchObject({ accessToken: 'sso_access_token' }); + + expect( + apiRequests.map((request) => new URL(request.url).pathname), + ).toEqual([ + '/user_management/authenticate', + '/user_management/authenticate', + '/user_management/authenticate', + '/sso/token', + ]); + expect(JSON.parse(apiRequests[0].body)).toEqual({ + grant_type: 'authorization_code', + client_id: APP_CLIENT_ID, + code: 'authorization_code', + code_verifier: 'code_verifier', + }); + expect(JSON.parse(apiRequests[2].body)).toEqual({ + grant_type: 'refresh_token', + client_id: APP_CLIENT_ID, + refresh_token: 'refresh_token', + }); + expect(form(apiRequests[3])).toEqual({ + grant_type: 'authorization_code', + client_id: APP_CLIENT_ID, + code: 'authorization_code', + code_verifier: 'code_verifier', + }); + for (const request of apiRequests) { + expect(request.body).not.toContain('client_secret'); + expect(request.headers.has('authorization')).toBe(false); + } + expect(exchanges).toHaveLength(0); + }); + + it('WIF: a public client gets the same error as before from a method that needs an API key', async () => { + const workos = new WorkOS({ clientId: APP_CLIENT_ID }); + + const error = await workos.userManagement + .authenticateWithPassword({ + email: 'user@example.com', + password: 'password', + }) + .catch((thrown: unknown) => thrown); + + expect(error).toBeInstanceOf(ApiKeyRequiredException); + expect(error).toMatchObject({ + message: expect.stringMatching( + /^API key required for "\/user_management\/authenticate"\. /, + ), + path: '/user_management/authenticate', + }); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('WIF: a client with an API key still sends it as the client secret', async () => { + const workos = new WorkOS('sk_test_static', { clientId: APP_CLIENT_ID }); + + api = (_count, request) => + request.url.endsWith('/sso/token') + ? profileAndToken() + : authenticationResponse(); + + await workos.userManagement.authenticateWithPassword({ + email: 'user@example.com', + password: 'password', + }); + await workos.userManagement.authenticateWithCode({ + code: 'authorization_code', + codeVerifier: 'code_verifier', + }); + await workos.userManagement.authenticateWithRefreshToken({ + refreshToken: 'refresh_token', + }); + await workos.sso.getProfileAndToken({ + clientId: APP_CLIENT_ID, + code: 'authorization_code', + }); + + expect( + apiRequests + .slice(0, 3) + .map((request) => JSON.parse(request.body).client_secret), + ).toEqual(['sk_test_static', 'sk_test_static', 'sk_test_static']); + expect(form(apiRequests[3]).client_secret).toBe('sk_test_static'); + expect(apiRequests.map(bearer)).toEqual( + Array(4).fill('Bearer sk_test_static'), + ); + expect(exchanges).toHaveLength(0); + }); + }); + describe('providers and configuration', () => { it('WIF-21: tokenFile re-reads the file on every exchange', async () => { const directory = await mkdtemp(path.join(os.tmpdir(), 'workos-wif-')); diff --git a/src/workos.ts b/src/workos.ts index a38a4276b..774ad5169 100644 --- a/src/workos.ts +++ b/src/workos.ts @@ -246,7 +246,9 @@ export class WorkOS { /** * Require API key for methods that need it. Credentials passed to the - * constructor authorize the same methods an API key does. + * constructor authorize the same methods an API key does, except the ones + * that send the API key as the client secret: see + * {@link requireApiKeyAsClientSecret}. * @param methodName - Name of the method requiring API key (for error message) * @throws ApiKeyRequiredException if neither an API key nor credentials were provided */ @@ -256,6 +258,30 @@ export class WorkOS { } } + /** + * Refuse a method that sends the API key as the client secret when this + * client was built with credentials. Such a client has no API key, so the + * request would go out with no client secret and with the credentials' + * access token, which is not a client secret. + * + * A client with an API key is not affected. Neither is a public client, + * which has neither an API key nor credentials: its PKCE and refresh token + * flows leave the client secret out on purpose. + * @param methodName - Name of the calling method (for error message) + * @param path - The API path the method calls + * @throws ApiKeyRequiredException before any request is sent + */ + requireApiKeyAsClientSecret(methodName: string, path: string): void { + if (this.options.credentials && !this.hasApiKey) { + throw new ApiKeyRequiredException( + path, + `${methodName} needs an API key: this request sends it as the client secret. ` + + 'A client that authenticates with workload identity has no API key, ' + + 'so use a client built with one for this call.', + ); + } + } + async post( path: string, entity: Entity, From 860975100db9ccf1dea4a865568c5773f336497e Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:09:33 -0500 Subject: [PATCH 12/14] fix(workload-identity): Type createWorkOS for a client built with credentials `createWorkOS` picked its return type from `apiKey` alone. Every client accepts `credentials`, so `createWorkOS({ clientId, credentials })` was typed as the public client, which hides `organizations` and the rest of the API a workload identity client is for, and `createWorkOS({ credentials })` matched no overload. A third overload now takes options that require `credentials` and returns the full `WorkOS` type. The public and API-key option types no longer accept `credentials`, so each call matches exactly one overload. An API key together with credentials, which the constructor rejects, is now a compile error too. Types only: the factory still passes its options to the constructor unchanged. --- src/factory.spec.ts | 72 +++++++++++++++++++++++++++++++++++++++++++++ src/factory.ts | 34 +++++++++++++++++++-- src/index.ts | 1 + src/index.worker.ts | 1 + 4 files changed, 105 insertions(+), 3 deletions(-) diff --git a/src/factory.spec.ts b/src/factory.spec.ts index ca00786f9..ac4a79287 100644 --- a/src/factory.spec.ts +++ b/src/factory.spec.ts @@ -3,10 +3,19 @@ import { type PublicUserManagement, type PublicSSO, } from './factory'; +import { WorkloadIdentityCredentials } from './workload-identity'; +import { WorkOS } from './workos'; describe('createWorkOS', () => { const OLD_ENV = process.env; + const workloadIdentityCredentials = () => + new WorkloadIdentityCredentials({ + clientId: 'client_wif', + tokenUrl: 'https://auth.workos.test/oauth2/token', + identityTokenProvider: async () => 'identity-token', + }); + beforeEach(() => { jest.resetModules(); process.env = { ...OLD_ENV }; @@ -102,6 +111,39 @@ describe('createWorkOS', () => { }); }); + describe('with credentials (workload identity client)', () => { + it('returns a WorkOS instance with credentials and no API key', () => { + const credentials = workloadIdentityCredentials(); + const workos = createWorkOS({ credentials }); + + expect(workos.options.credentials).toBe(credentials); + expect(workos.key).toBeUndefined(); + expect(workos.baseURL).toBeDefined(); + }); + + it('keeps the clientId passed next to the credentials', () => { + const workos = createWorkOS({ + clientId: 'client_123', + credentials: workloadIdentityCredentials(), + }); + + expect(workos.clientId).toBe('client_123'); + }); + + it('has access to all services', () => { + const workos = createWorkOS({ + clientId: 'client_123', + credentials: workloadIdentityCredentials(), + }); + + expect(workos.userManagement).toBeDefined(); + expect(workos.sso).toBeDefined(); + expect(workos.organizations).toBeDefined(); + expect(workos.directorySync).toBeDefined(); + expect(workos.auditLogs).toBeDefined(); + }); + }); + /** * Type-level tests - these verify compile-time behavior. * If these compile, the types are working correctly. @@ -163,6 +205,36 @@ describe('createWorkOS', () => { expect(typeof workos.userManagement.createUser).toBe('function'); }); + it('credentials client has full WorkOS type', () => { + // Each assignment compiles only when the factory returns the full + // WorkOS type, with or without a clientId next to the credentials. + const withCredentials: WorkOS = createWorkOS({ + credentials: workloadIdentityCredentials(), + }); + const withClientId: WorkOS = createWorkOS({ + clientId: 'client_123', + credentials: workloadIdentityCredentials(), + }); + + for (const workos of [withCredentials, withClientId]) { + expect(workos.organizations).toBeDefined(); + expect(workos.directorySync).toBeDefined(); + expect(typeof workos.userManagement.listUsers).toBe('function'); + } + }); + + it('does not accept an API key together with credentials', () => { + const options = { + apiKey: 'sk_test_123', + credentials: workloadIdentityCredentials(), + }; + + // @ts-expect-error - an API key with credentials matches no overload + expect(() => createWorkOS(options)).toThrow( + 'WorkOS accepts an API key or credentials, not both', + ); + }); + it('PublicWorkOS does not expose confidential methods', () => { const workos = createWorkOS({ clientId: 'client_123' }); diff --git a/src/factory.ts b/src/factory.ts index 917b610a5..26022fdbe 100644 --- a/src/factory.ts +++ b/src/factory.ts @@ -4,6 +4,7 @@ import type { UserManagement } from './user-management/user-management'; import type { SSO } from './sso/sso'; import type { PKCE } from './pkce/pkce'; import type { WorkOSOptions } from './common/interfaces'; +import type { Credentials } from './common/net/credentials'; /** * Method names available without API key - single source of truth. @@ -61,6 +62,8 @@ export interface PublicClientOptions extends Omit { clientId: string; /** Discriminant: ensures TypeScript selects PublicWorkOS overload when apiKey is absent */ apiKey?: never; + /** Discriminant: a client with credentials is not a public client */ + credentials?: never; } /** @@ -68,6 +71,21 @@ export interface PublicClientOptions extends Omit { */ export interface ConfidentialClientOptions extends WorkOSOptions { apiKey: string; + /** An API key and credentials together are an error */ + credentials?: never; +} + +/** + * Options for creating a client that authorizes with credentials, such as + * `WorkloadIdentityCredentials`, in place of an API key. + */ +export interface CredentialsClientOptions extends Omit< + WorkOSOptions, + 'apiKey' +> { + credentials: Credentials; + /** An API key and credentials together are an error */ + apiKey?: never; } /** @@ -75,10 +93,11 @@ export interface ConfidentialClientOptions extends WorkOSOptions { * * Returns a narrowed `PublicWorkOS` type when only `clientId` is provided, * ensuring compile-time safety for public client usage. Returns the full - * `WorkOS` type when an API key is provided. + * `WorkOS` type when an API key or `credentials` is provided. * * Unlike the `WorkOS` constructor, this factory does NOT read from - * environment variables. Pass credentials explicitly for predictable types. + * environment variables. Pass the API key or `credentials` explicitly for + * predictable types. * * @example * // Public client (browser, mobile, CLI) - returns PublicWorkOS @@ -93,11 +112,20 @@ export interface ConfidentialClientOptions extends WorkOSOptions { * clientId: 'client_123' * }); * await workos.userManagement.listUsers(); // OK + * + * @example + * // Workload identity (server, no API key) - returns full WorkOS + * const workos = createWorkOS({ + * credentials: new WorkloadIdentityCredentials({ ... }), + * }); + * await workos.organizations.listOrganizations(); // OK */ export function createWorkOS(options: PublicClientOptions): PublicWorkOS; export function createWorkOS(options: ConfidentialClientOptions): WorkOS; +export function createWorkOS(options: CredentialsClientOptions): WorkOS; export function createWorkOS( - options: PublicClientOptions | ConfidentialClientOptions, + options: + PublicClientOptions | ConfidentialClientOptions | CredentialsClientOptions, ): PublicWorkOS | WorkOS { return new WorkOS(options); } diff --git a/src/index.ts b/src/index.ts index 4c57f275f..cdc0af484 100644 --- a/src/index.ts +++ b/src/index.ts @@ -50,6 +50,7 @@ export { type PublicSSO, type PublicClientOptions, type ConfidentialClientOptions, + type CredentialsClientOptions, } from './factory'; class WorkOSNode extends WorkOS { diff --git a/src/index.worker.ts b/src/index.worker.ts index 2e80cfa75..97e25f281 100644 --- a/src/index.worker.ts +++ b/src/index.worker.ts @@ -31,6 +31,7 @@ export { type PublicSSO, type PublicClientOptions, type ConfidentialClientOptions, + type CredentialsClientOptions, } from './factory'; class WorkOSWorker extends WorkOS { From 37ef60dab93165fa2f0a25f9945944e4a5d6ecd9 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:31:06 -0500 Subject: [PATCH 13/14] fix(workload-identity): Keep the assertion out of errors when the token endpoint repeats it A token endpoint may repeat the assertion it was sent in its `error` or `error_description`. The SDK copied both strings into `WorkloadIdentityError`, so the identity token then appeared in the error's code, description, message and stack. Every occurrence of the assertion is now replaced with `[redacted]` before either string is kept. Each retry calls the provider again, so the assertion replaced is the one that attempt sent. The replacement happens before the description is cut to 500 characters, so a cut cannot leave the start of a token behind. It covers a terminal error and the last failure when the retries run out. --- README.md | 2 +- src/workload-identity/constants.ts | 6 ++ .../workload-identity-credentials.ts | 26 +++++- .../workload-identity-error.ts | 4 +- .../workload-identity.spec.ts | 86 +++++++++++++++++++ 5 files changed, 119 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5e96816e1..1a1b515cd 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ WorkOS accepts an identity token for one exchange. The SDK makes a new exchange ### Errors -A failed exchange throws a `WorkloadIdentityError`. Its `code` is the OAuth error code from the token endpoint (for example `invalid_grant`) or an SDK code (`exchange_failed`, `invalid_response`, `provider_failed`, `invalid_configuration`), `description` is the server's explanation, and `hint` says what to check. The exchange is retried on network failures, 429 and 5xx responses. An API request that gets a 401 is retried once with a new token. +A failed exchange throws a `WorkloadIdentityError`. Its `code` is the OAuth error code from the token endpoint (for example `invalid_grant`) or an SDK code (`exchange_failed`, `invalid_response`, `provider_failed`, `invalid_configuration`), `description` is the server's explanation, and `hint` says what to check. The error never contains the identity token: if the token endpoint repeats it, the SDK puts `[redacted]` in its place. The exchange is retried on network failures, 429 and 5xx responses. An API request that gets a 401 is retried once with a new token. ## Public Client Mode (Browser/Mobile/CLI) diff --git a/src/workload-identity/constants.ts b/src/workload-identity/constants.ts index 87ebac686..9d3f269ad 100644 --- a/src/workload-identity/constants.ts +++ b/src/workload-identity/constants.ts @@ -26,3 +26,9 @@ export const EXCHANGE_DEADLINE_MS = 30_000; /** The server's `error_description` is cut to this many characters. */ export const ERROR_DESCRIPTION_LIMIT = 500; + +/** + * Stands in for the assertion wherever the token endpoint repeats it in its + * `error` or `error_description`. + */ +export const REDACTED_ASSERTION = '[redacted]'; diff --git a/src/workload-identity/workload-identity-credentials.ts b/src/workload-identity/workload-identity-credentials.ts index 7c3929678..00c075a42 100644 --- a/src/workload-identity/workload-identity-credentials.ts +++ b/src/workload-identity/workload-identity-credentials.ts @@ -20,6 +20,7 @@ import { ENVIRONMENT_ID_HEADER, EXCHANGE_DEADLINE_MS, JWT_BEARER_GRANT_TYPE, + REDACTED_ASSERTION, REFRESH_THRESHOLD_LIFETIME_FRACTION, REFRESH_THRESHOLD_MAX_MS, } from './constants'; @@ -393,7 +394,9 @@ export class WorkloadIdentityCredentials implements Credentials { } const { status, body } = result; - const oauthError = readOAuthError(body); + // Read with the assertion this attempt sent, so that a server that + // repeats it back cannot put it in an error. + const oauthError = readOAuthError(body, assertion); // The status is checked before the body: a 429 or 5xx is retried even // when it carries an OAuth error. @@ -621,20 +624,37 @@ async function readJson( } } +/** + * The OAuth error in a token endpoint response, if it has one. The server's + * two strings are the only text of its own that the SDK keeps, so the + * assertion is taken out of both here, before either reaches an error. + */ function readOAuthError( body: unknown, + assertion: string, ): { code: string; description: string } | undefined { if (!isRecord(body) || typeof body.error !== 'string' || !body.error) { return undefined; } return { - code: body.error, + code: withoutAssertion(body.error, assertion), description: - typeof body.error_description === 'string' ? body.error_description : '', + typeof body.error_description === 'string' + ? withoutAssertion(body.error_description, assertion) + : '', }; } +/** + * Replaces every occurrence of the assertion in text the token endpoint + * sent. A token endpoint may repeat the assertion it was given, and an error + * must never contain it. + */ +function withoutAssertion(text: string, assertion: string): string { + return assertion ? text.split(assertion).join(REDACTED_ASSERTION) : text; +} + function readTokenResponse(body: unknown): TokenResponse { if (!isRecord(body)) { throw new WorkloadIdentityError( diff --git a/src/workload-identity/workload-identity-error.ts b/src/workload-identity/workload-identity-error.ts index e345f0157..d5fd3aba3 100644 --- a/src/workload-identity/workload-identity-error.ts +++ b/src/workload-identity/workload-identity-error.ts @@ -58,7 +58,9 @@ const UNKNOWN_CODE_HINT = 'The token endpoint rejected the exchange.'; * failing identity token provider, or incomplete configuration. * * The message is `: `, followed by the description when there is - * one. It never contains the identity token or the access token. + * one. It never contains the identity token or the access token: where the + * token endpoint repeats the identity token in its error, the code and the + * description have `[redacted]` in its place. */ export class WorkloadIdentityError extends Error { readonly name = 'WorkloadIdentityError'; diff --git a/src/workload-identity/workload-identity.spec.ts b/src/workload-identity/workload-identity.spec.ts index c24cd5442..cbf1d50dd 100644 --- a/src/workload-identity/workload-identity.spec.ts +++ b/src/workload-identity/workload-identity.spec.ts @@ -812,12 +812,42 @@ describe('workload identity', () => { .catch((e) => e), ); + // A token endpoint that repeats the assertion in a terminal error. + tokenEndpoint = () => + oauthError('invalid_grant', `JWT ${ASSERTION} failed validation`); + const repeated = await setup({ identityTokenProvider: secretProvider }) + .workos.get('/organizations') + .catch((e) => e); + errors.push(repeated); + + // And one that repeats it with a 503 until the retries run out. + tokenEndpoint = () => ({ + ...oauthError('invalid_grant', `JWT ${ASSERTION} failed validation`), + status: 503, + }); + const repeatedUntilRetriesRanOut = await setup({ + identityTokenProvider: secretProvider, + }) + .workos.get('/organizations') + .catch((e) => e); + errors.push(repeatedUntilRetriesRanOut); + expect(errors.map((error) => (error as Error).name)).toEqual([ 'WorkloadIdentityError', 'WorkloadIdentityError', 'WorkloadIdentityError', 'UnauthorizedException', + 'WorkloadIdentityError', + 'WorkloadIdentityError', ]); + // The server's text is kept, with the assertion replaced. + for (const error of [repeated, repeatedUntilRetriesRanOut]) { + expect(error.code).toBe('invalid_grant'); + expect(error.description).toBe('JWT [redacted] failed validation'); + expect(error.message).toBe( + `invalid_grant: ${error.hint} JWT [redacted] failed validation`, + ); + } // Both secrets did reach the mocks, so their absence below means // something. expect(exchanges.some((e) => e.body.includes(ASSERTION))).toBe(true); @@ -837,6 +867,62 @@ describe('workload identity', () => { expect(seen).not.toContain(ASSERTION); expect(seen).not.toContain(ACCESS_TOKEN); }); + + it('WIF: the assertion each attempt sent is replaced in the error code and description, before the description is cut', async () => { + // A new assertion on every attempt, and a token endpoint that repeats + // whichever one it was sent. + let calls = 0; + const identityTokenProvider = async () => `SECRET-ASSERTION-${++calls}`; + const repeatsAssertion = + (status: number, text: (assertion: string) => string): Responder => + (_count, request) => ({ + status, + json: { + error: `rejected ${form(request).assertion}`, + error_description: text(form(request).assertion), + }, + }); + const everything = (error: unknown) => + [ + String(error), + (error as Error).stack, + inspect(error, { depth: null, showHidden: true }), + JSON.stringify(error, Object.getOwnPropertyNames(error as object)), + ].join('\n'); + + // Retried until the retries run out: the error kept is from the last + // attempt, whose assertion is not the first one. + tokenEndpoint = repeatsAssertion( + 503, + (assertion) => `JWT ${assertion} failed, and so did ${assertion}`, + ); + const retried = await setup({ identityTokenProvider }) + .workos.get('/organizations') + .catch((e) => e); + + expect(exchanges.length).toBeGreaterThan(1); + expect(form(exchanges[exchanges.length - 1]).assertion).toBe( + `SECRET-ASSERTION-${exchanges.length}`, + ); + expect(retried.code).toBe('rejected [redacted]'); + expect(retried.description).toBe( + 'JWT [redacted] failed, and so did [redacted]', + ); + expect(everything(retried)).not.toContain('SECRET-ASSERTION'); + + // Replaced first and cut second: an assertion that straddles the limit + // leaves no part of itself behind. + tokenEndpoint = repeatsAssertion( + 400, + (assertion) => `${'x'.repeat(495)}${assertion}`, + ); + const cut = await setup({ identityTokenProvider }) + .workos.get('/organizations') + .catch((e) => e); + + expect(cut.description).toBe(`${'x'.repeat(495)}[reda`); + expect(everything(cut)).not.toContain('SECRET'); + }); }); describe('authentication precedence', () => { From e36f5eac3a84a463a71454a8de35d29fd5fecc03 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:31:07 -0500 Subject: [PATCH 14/14] fix(workload-identity): Make one bounded STS request per AWS provider call The AWS SDK retries inside its client, so one provider call sent three STS requests when STS throttled or answered 5xx. The exchange already calls the provider again when it retries, and providers are meant to make one request per call. The client also had no limit on connecting or on waiting for an answer, so a call to a stalled STS did not end. The provider's own STS client now makes one attempt, whatever `AWS_MAX_ATTEMPTS` or the shared config file says, and has the same 10-second limit the other two providers use: on connecting, on the wait for the response, and on a response that goes silent. `throwOnRequestTimeout` is set because the AWS SDK only logs a warning for its request limit without it. No process-wide AWS configuration, environment variable, credential source or region rule changes. --- packages/workload-identity-aws/README.md | 1 + .../workload-identity-aws/src/index.spec.ts | 144 +++++++++++++++++- packages/workload-identity-aws/src/index.ts | 20 +++ 3 files changed, 160 insertions(+), 5 deletions(-) diff --git a/packages/workload-identity-aws/README.md b/packages/workload-identity-aws/README.md index 312620b89..639792b22 100644 --- a/packages/workload-identity-aws/README.md +++ b/packages/workload-identity-aws/README.md @@ -28,6 +28,7 @@ const workos = new WorkOS({ - AWS credentials come from the AWS SDK's default chain. - `region` is optional when the AWS SDK can resolve one, for example from `AWS_REGION`. The call uses that region's STS endpoint, never the global endpoint. +- Each call makes one STS request, with a 10-second limit on connecting and on the request. The AWS SDK's own retries are turned off on this client, whatever `AWS_MAX_ATTEMPTS` says, because the WorkOS SDK calls the provider again when it retries the exchange. - The AWS account needs outbound identity federation enabled, and the role needs permission for `sts:GetWebIdentityToken`. The package depends on `@aws-sdk/client-sts` and does not depend on `@workos-inc/node`. diff --git a/packages/workload-identity-aws/src/index.spec.ts b/packages/workload-identity-aws/src/index.spec.ts index f3ed8a22e..4c43b3abd 100644 --- a/packages/workload-identity-aws/src/index.spec.ts +++ b/packages/workload-identity-aws/src/index.spec.ts @@ -1,5 +1,7 @@ // @oagen-ignore-file import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'; +import http from 'node:http'; +import { AddressInfo } from 'node:net'; import { awsSts } from './index'; const AUDIENCE = 'https://api.workos.com'; @@ -13,6 +15,7 @@ interface StsCall { describe('awsSts', () => { const OLD_ENV = process.env; + const servers: http.Server[] = []; /** * Stubs the one STS method the provider calls. The client itself is real, @@ -53,20 +56,72 @@ describe('awsSts', () => { return calls; } + /** + * A local stand-in for the regional STS endpoint, for the tests that let + * the provider's own client send its request. The client reaches it through + * `AWS_ENDPOINT_URL_STS`, with its own retry and timeout settings. Nothing + * here reaches AWS. + */ + async function stsEndpoint( + respond: (res: http.ServerResponse) => void, + ): Promise<{ requests: () => number }> { + let requests = 0; + const server = http.createServer((req, res) => { + requests++; + req.resume(); + respond(res); + }); + servers.push(server); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + const { port } = server.address() as AddressInfo; + + process.env.AWS_ENDPOINT_URL_STS = `http://127.0.0.1:${port}`; + process.env.AWS_ACCESS_KEY_ID = 'test-access-key-id'; + process.env.AWS_SECRET_ACCESS_KEY = 'test-secret-access-key'; + + return { requests: () => requests }; + } + + const xml = (status: number, body: string) => (res: http.ServerResponse) => { + res.writeHead(status, { 'content-type': 'text/xml' }); + res.end(body); + }; + + const stsError = (status: number, code: string) => + xml( + status, + `Sender${code}${code}request-1`, + ); + beforeEach(() => { - // No region from the machine running the tests. + // No region, credentials or retry settings from the machine running the + // tests. process.env = { ...OLD_ENV, AWS_CONFIG_FILE: '/nonexistent/aws/config', AWS_SHARED_CREDENTIALS_FILE: '/nonexistent/aws/credentials', }; - delete process.env.AWS_REGION; - delete process.env.AWS_DEFAULT_REGION; - delete process.env.AWS_PROFILE; + for (const name of [ + 'AWS_REGION', + 'AWS_DEFAULT_REGION', + 'AWS_PROFILE', + 'AWS_SESSION_TOKEN', + 'AWS_MAX_ATTEMPTS', + 'AWS_RETRY_MODE', + 'AWS_ENDPOINT_URL', + 'AWS_ENDPOINT_URL_STS', + ]) { + delete process.env[name]; + } }); - afterEach(() => { + afterEach(async () => { + jest.useRealTimers(); process.env = OLD_ENV; + for (const server of servers.splice(0)) { + server.closeAllConnections(); + await new Promise((done) => server.close(done)); + } }); it('WIF-AWS-01: calls GetWebIdentityToken with the audience and RS256 on a regional endpoint and returns the token', async () => { @@ -148,6 +203,85 @@ describe('awsSts', () => { ); }); + it.each([ + ['throttles', 400, 'Throttling'], + ['answers 503', 503, 'ServiceUnavailable'], + ])( + 'makes one STS request per call when STS %s', + async (_name, status, code) => { + const sts = await stsEndpoint(stsError(status, code)); + + await expect(awsSts(AUDIENCE, 'us-east-1')()).rejects.toThrow( + `sts:GetWebIdentityToken failed with ${code}.`, + ); + + // The AWS SDK would send three. The exchange calls the provider again + // when it retries, so the provider does not. + expect(sts.requests()).toBe(1); + }, + ); + + it('sets one attempt and 10-second limits on its own STS client, whatever the environment says', async () => { + process.env.AWS_MAX_ATTEMPTS = '5'; + const send = jest.spyOn(STSClient.prototype, 'send'); + const sts = await stsEndpoint( + xml( + 200, + 'aws-jwt', + ), + ); + + await expect(awsSts(AUDIENCE, 'us-east-1')()).resolves.toBe('aws-jwt'); + + const client = send.mock.contexts[0] as STSClient; + // The settings the client's HTTP handler used for that request. + const handler = client.config.requestHandler as unknown as { + httpHandlerConfigs(): Record; + }; + + expect(sts.requests()).toBe(1); + await expect(client.config.maxAttempts()).resolves.toBe(1); + expect(handler.httpHandlerConfigs()).toMatchObject({ + connectionTimeout: 10_000, + requestTimeout: 10_000, + throwOnRequestTimeout: true, + socketTimeout: 10_000, + }); + }); + + it('gives up after 10 seconds on an STS that accepts the request and does not answer', async () => { + const sts = await stsEndpoint(() => undefined); + + jest.useFakeTimers({ + doNotFake: ['nextTick', 'queueMicrotask', 'setImmediate'], + }); + const turns = async (condition: () => boolean) => { + for (let turn = 0; turn < 1000 && !condition(); turn++) { + await new Promise((done) => setImmediate(done)); + } + }; + + let outcome: unknown = 'pending'; + void awsSts(AUDIENCE, 'us-east-1')().then( + () => (outcome = 'resolved'), + (error: unknown) => (outcome = error), + ); + await turns(() => sts.requests() === 1); + expect(sts.requests()).toBe(1); + + await jest.advanceTimersByTimeAsync(9_999); + await turns(() => outcome !== 'pending'); + expect(outcome).toBe('pending'); + + await jest.advanceTimersByTimeAsync(1); + await turns(() => outcome !== 'pending'); + expect(outcome).toMatchObject({ + message: 'sts:GetWebIdentityToken failed with TimeoutError.', + }); + // Not sent again. + expect(sts.requests()).toBe(1); + }); + it('requires an audience', () => { expect(() => awsSts('')).toThrow('an audience is required'); }); diff --git a/packages/workload-identity-aws/src/index.ts b/packages/workload-identity-aws/src/index.ts index ed6d705e0..f461fe90f 100644 --- a/packages/workload-identity-aws/src/index.ts +++ b/packages/workload-identity-aws/src/index.ts @@ -1,10 +1,16 @@ // @oagen-ignore-file import { GetWebIdentityTokenCommand, STSClient } from '@aws-sdk/client-sts'; +const REQUEST_TIMEOUT_MS = 10_000; + /** * An identity token provider for AWS. Each call asks STS for a signed token * (`sts:GetWebIdentityToken`, RS256) that represents the calling role. * + * One call is one STS request, with a 10-second limit on connecting and on + * the request. The AWS SDK's own retries are off: the WorkOS SDK calls the + * provider again when it retries the exchange. + * * AWS credentials come from the AWS SDK's default chain. The account needs * outbound identity federation enabled, and the role needs permission for * `sts:GetWebIdentityToken`. @@ -35,6 +41,20 @@ export function awsSts( const client = new STSClient({ ...(region && { region }), useGlobalEndpoint: false, + // One attempt, whatever `AWS_MAX_ATTEMPTS` or the shared config file + // says. The AWS SDK would otherwise send up to three requests per call. + maxAttempts: 1, + // Limits for this client only. Without them the AWS SDK sets none that + // would end a request to an STS that stalls. + requestHandler: { + connectionTimeout: REQUEST_TIMEOUT_MS, + // From sending the request until the response headers arrive. It only + // logs a warning unless it is told to throw. + requestTimeout: REQUEST_TIMEOUT_MS, + throwOnRequestTimeout: true, + // A response that goes silent after its headers. + socketTimeout: REQUEST_TIMEOUT_MS, + }, }); return async () => {