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 7183c2b58..2ff41a531 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 b1b9c1156..7c240c37e 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 a9908fe75..395b9c21d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,6 @@ { - ".": "12.4.0" + ".": "12.4.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/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. diff --git a/README.md b/README.md index 96c535bad..1a1b515cd 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,104 @@ 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_...', // optional + identityTokenProvider: githubActions('https://api.workos.com'), + }), +}); + +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. + +### 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({ + clientId: 'client_...', + tokenUrl: 'https:///oauth2/token', + 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'; + +// 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 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`. + +### 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 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) 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 385cd45a0..83ce39229 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "@workos-inc/node", "version": "12.4.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.1175.0", + "integrity": "sha512-lhKpFnN5ui9Eg+M6HGNBl7cEksvYXBuQRhbViu7Z/W1caXUCfdhdND+D1xfiHlPnpd16OCke+mFGEarpui6rHg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@aws-sdk/credential-provider-node": "^3.972.98", + "@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.1", + "integrity": "sha512-sERtJaZjzvBdFMm2uei4k0WwPNUJtIrMBH9h0AEw7G0KkhIbnN3e5ZcwGjbVKClR+rrJCmyL1jhtXkseE7DU4A==", + "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.85", + "integrity": "sha512-IkIfFWmDbUyDEdNZpyAMmD3Givrm11I9UrqbgmLu1kUL/oh96QMqbfuHcbH08ErngZPDCQ2+7fW3U4r/W2k2Xg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@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.87", + "integrity": "sha512-NWQNmfmllENW1TOpMfhEZeRzEvbSaFsS5yrb2TZJ0wu+fVL5hyVSfGVLd8HTWb2UECD2bCw/kDXaA6dR1VJf3g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@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.31", + "integrity": "sha512-K6jkaKaAaVn9qAl/I14lzDHnYWHiESkxYLnmPYnJg3OfTRtWz39NerpidQIzqbMpoE/pmFqhgSJ+Sx/j1++8sA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@aws-sdk/credential-provider-env": "^3.972.85", + "@aws-sdk/credential-provider-http": "^3.972.87", + "@aws-sdk/credential-provider-login": "^3.972.93", + "@aws-sdk/credential-provider-process": "^3.972.85", + "@aws-sdk/credential-provider-sso": "^3.973.29", + "@aws-sdk/credential-provider-web-identity": "^3.972.91", + "@aws-sdk/nested-clients": "^3.998.4", + "@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.93", + "integrity": "sha512-JofxFKJyNGLc9MmFMKy/vmjVwvNIWKNvHOf8rkXheH9x4+WJpIexhk1cqbmxWkodDYAodqGTiCEdBAVuiyH0iA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@aws-sdk/nested-clients": "^3.998.4", + "@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.98", + "integrity": "sha512-EpRL6YwSqvNlMjvRmwR2o3exV6DaETTdaWr1U7fZ456LQeK6ErOSluc6mWMY+OjkrBVFK4PgrU4NlERXTcgzKg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "^3.972.85", + "@aws-sdk/credential-provider-http": "^3.972.87", + "@aws-sdk/credential-provider-ini": "^3.973.31", + "@aws-sdk/credential-provider-process": "^3.972.85", + "@aws-sdk/credential-provider-sso": "^3.973.29", + "@aws-sdk/credential-provider-web-identity": "^3.972.91", + "@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.85", + "integrity": "sha512-19kc3xj6woR3Nb2NWFxowRkCnuR43jMFcTLLLCqkzB/rPxxE1+NfHnAP5fpXgrI4xRRgDzvWeDREjhGrJxqfxA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@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.29", + "integrity": "sha512-DJuKIs0bn5MZXc5uE1sf/R67YVC4ivFnL/dbKHukhdb5B6Fy80k8/BqiQykzXEqoT/qlSQaqYXU29hqVAYjcsg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@aws-sdk/nested-clients": "^3.998.4", + "@aws-sdk/token-providers": "3.1175.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.91", + "integrity": "sha512-4k4beWSkxhwKeGMVfgppv/LwCfCd1zAycWgqop7GHkdvdNK9TTkWn299LjUQOgDMfBX2Sv08t+J1mAWKHatttw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@aws-sdk/nested-clients": "^3.998.4", + "@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.4", + "integrity": "sha512-8Vzg3e9ia6eHQStnoSn17asRNWHrf/ozgQslLMGOdM5JifyV+AAk1+lgVXcQMmrzgRhR9phRUEFxAOg/cBh7MQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@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.1175.0", + "integrity": "sha512-irdg9wmKjTDumWoZeXIM3ecgfriHEEm0Q05bjiHwGNRCXXexz+5roMS28IzKWELI5QX/XZjL1vvvaIyptlCfAQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "^3.981.1", + "@aws-sdk/nested-clients": "^3.998.4", + "@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==", @@ -4422,6 +4682,81 @@ "@sinonjs/commons": "^3.0.1" } }, + "node_modules/@smithy/core": { + "version": "3.41.0", + "integrity": "sha512-fuZ34H1uizS3WgcX9VXG7Uy8od5A5/kCc+CR3NkHLNm2H/BE9AUHG02VIdu8ZB7FYhLqsr/RZbqAoXuOCg/Oxg==", + "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==", @@ -5117,6 +5452,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-toolchain/darwin-arm64": { "version": "0.27.0", "integrity": "sha512-A3v83rNyHWlnJeeMBsWggZ+RZDP2BEMHIiMk+j23LqtVch24MXwg8veflkQgZ2GtCtZOxcG+NkztnsSUS4rWEQ==", @@ -5477,6 +5824,11 @@ "node": ">=6.0.0" } }, + "node_modules/bowser": { + "version": "2.15.1", + "integrity": "sha512-ma47ABeUiTsmG4McKDtGCgQSiTCatM97Mlbn13K42N1kPSFE14oN3WFMjtyL4KubhGvQTqYheKl4Qx2bJtMXLQ==", + "license": "MIT" + }, "node_modules/brace-expansion": { "version": "5.0.9", "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", @@ -9129,9 +9481,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", @@ -9700,6 +10050,33 @@ "optional": true } } + }, + "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 08c0ae139..622b2864d 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..639792b22 --- /dev/null +++ b/packages/workload-identity-aws/README.md @@ -0,0 +1,34 @@ +# @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. +- 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/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..4c43b3abd --- /dev/null +++ b/packages/workload-identity-aws/src/index.spec.ts @@ -0,0 +1,288 @@ +// @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'; + +interface StsCall { + client: STSClient; + command: GetWebIdentityTokenCommand; + region: string; + endpoint: string; +} + +describe('awsSts', () => { + const OLD_ENV = process.env; + const servers: http.Server[] = []; + + /** + * 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; + } + + /** + * 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, 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', + }; + 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(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 () => { + 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.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 new file mode 100644 index 000000000..f461fe90f --- /dev/null +++ b/packages/workload-identity-aws/src/index.ts @@ -0,0 +1,96 @@ +// @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`. + * + * @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({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', + * 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, + // 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 () => { + // 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..ed006da1c --- /dev/null +++ b/packages/workload-identity-gcp/README.md @@ -0,0 +1,31 @@ +# @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 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/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..172992926 --- /dev/null +++ b/packages/workload-identity-gcp/src/index.spec.ts @@ -0,0 +1,153 @@ +// @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 = '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; port: number; 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}`, 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 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 realRequest = http.request; + + jest.spyOn(http, 'request').mockImplementation((( + options: http.RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ) => { + requested.push(`http://${options.host}${options.path}`); + + if (options.host !== METADATA_HOST) { + throw new Error(`Unexpected request to ${options.host}`); + } + + return realRequest( + { ...options, host: '127.0.0.1', port: mock.port }, + callback, + ); + }) as typeof http.request); + + 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('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 + // 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 new file mode 100644 index 000000000..204b612d6 --- /dev/null +++ b/packages/workload-identity-gcp/src/index.ts @@ -0,0 +1,92 @@ +// @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'; + +/** + * 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 + * 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. 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`. + * + * @example + * new WorkloadIdentityCredentials({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', + * identityTokenProvider: gcpMetadata('https://api.workos.com'), + * }); + */ +export function gcpMetadata(audience: string): () => Promise { + if (!audience) { + throw new TypeError('gcpMetadata: an audience is required.'); + } + + 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); + + 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; + } + + 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.'), + ); + } + }); + }, + ); + + request.on('error', reject); + request.end(); + }); +} 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..c2585810f --- /dev/null +++ b/packages/workload-identity-github-actions/src/index.ts @@ -0,0 +1,73 @@ +// @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({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', + * 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..a99053fd3 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,11 +1,43 @@ { "$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", + "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", + "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", + "initial-version": "0.1.0" } } } 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/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/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..9826ff5d9 --- /dev/null +++ b/src/common/net/credentials.ts @@ -0,0 +1,70 @@ +// @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); + } + + /** + * 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 699de1bbb..09e3d8773 100644 --- a/src/common/net/fetch-client.ts +++ b/src/common/net/fetch-client.ts @@ -13,20 +13,45 @@ import { HttpClientResponse, } from './http-client'; import { ParseError } from '../exceptions/parse-error'; +import { StaticKeyCredentials } from './credentials'; +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; +} + +/** 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; constructor( readonly baseURL: string, readonly options?: FetchHttpClientOptions, fetchFn?: typeof fetch, + settings: FetchHttpClientSettings = {}, ) { super(baseURL, options); + this.credentials = settings.credentials; + // Default to global fetch if available if (!fetchFn) { if (!globalThis.fetch) { @@ -182,6 +207,7 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { body?: any, headers?: RequestHeaders, signal?: AbortSignal, + attempt?: AttemptState, ): Promise { signal?.throwIfAborted(); @@ -228,15 +254,32 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { let redirected = false; 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 && 'then' in resolving ? await resolving : resolving; + 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, // The API never redirects. Following one would re-send the body (which @@ -372,11 +415,15 @@ 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; // Tracked apart from the error: an abort can reject with a null reason. let failed = false; + const attempt: AttemptState = {}; try { response = await this.fetchRequest( @@ -385,12 +432,44 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface { body, requestHeaders, signal, + attempt, ); } catch (e) { requestError = e; failed = true; } + // 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; + failed = false; + + try { + response = await this.fetchRequest( + url, + method, + body, + requestHeaders, + signal, + ); + } catch (e) { + requestError = e; + failed = true; + } + } + if ( !signal?.aborted && this.shouldRetryRequest(requestError, retryAttempts, maxRetryAttempts) @@ -448,6 +527,74 @@ 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, + ): CredentialSnapshot | Promise | undefined { + if ( + !this.credentials || + FetchHttpClient.hasHeader(headers, 'Authorization') + ) { + return undefined; + } + + if (this.credentials instanceof StaticKeyCredentials) { + return this.credentials.resolveNow(); + } + + 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/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 a78252898..cdc0af484 100644 --- a/src/index.ts +++ b/src/index.ts @@ -39,6 +39,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, @@ -47,6 +50,7 @@ export { type PublicSSO, type PublicClientOptions, type ConfidentialClientOptions, + type CredentialsClientOptions, } from './factory'; class WorkOSNode extends WorkOS { @@ -67,10 +71,6 @@ class WorkOSNode extends WorkOS { headers['User-Agent'] = userAgent; - if (this.key) { - headers['Authorization'] = `Bearer ${this.key}`; - } - const opts = { ...options.config, timeout: options.timeout, @@ -78,7 +78,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 e776ff931..97e25f281 100644 --- a/src/index.worker.ts +++ b/src/index.worker.ts @@ -22,6 +22,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, @@ -30,6 +31,7 @@ export { type PublicSSO, type PublicClientOptions, type ConfidentialClientOptions, + type CredentialsClientOptions, } from './factory'; class WorkOSWorker extends WorkOS { 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/constants.ts b/src/workload-identity/constants.ts new file mode 100644 index 000000000..9d3f269ad --- /dev/null +++ b/src/workload-identity/constants.ts @@ -0,0 +1,34 @@ +// @oagen-ignore-file + +/** + * 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 = + '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; + +/** + * 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/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..ed7523b8f --- /dev/null +++ b/src/workload-identity/token-env.ts @@ -0,0 +1,28 @@ +// @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({ + * clientId: 'client_123', + * tokenUrl: 'https://auth.example.com/oauth2/token', + * 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..16c79187d --- /dev/null +++ b/src/workload-identity/token-file.ts @@ -0,0 +1,66 @@ +// @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({ + * 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'), + * }); + */ +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..00c075a42 --- /dev/null +++ b/src/workload-identity/workload-identity-credentials.ts @@ -0,0 +1,688 @@ +// @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, + REDACTED_ASSERTION, + 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. 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; + /** + * 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 + * `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`. */ + resource?: string; + /** + * 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; +} + +/** + * 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 | undefined; + 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 - 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, or when `tokenUrl` + * is not an absolute `https` URL. + */ + constructor( + options: WorkloadIdentityCredentialsOptions, + /** @internal */ + internals: WorkloadIdentityInternals = {}, + ) { + const clientId = options?.clientId || getEnv('WORKOS_CLIENT_ID'); + const tokenUrl = options?.tokenUrl; + + if (!clientId) { + throw missingSetting('clientId', 'WORKOS_CLIENT_ID'); + } + if (!tokenUrl) { + throw new WorkloadIdentityError( + 'invalid_configuration', + 'tokenUrl is required', + ); + } + if (typeof options?.identityTokenProvider !== 'function') { + throw new WorkloadIdentityError( + 'invalid_configuration', + 'identityTokenProvider is required', + ); + } + + 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. + this.environmentId = options.environmentId || undefined; + this.resource = options.resource || DEFAULT_RESOURCE; + this.scope = options.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); + + const headers: Record = { + Authorization: `Bearer ${token}`, + }; + + if (this.environmentId) { + headers[ENVIRONMENT_ID_HEADER] = this.environmentId; + } + + return { + headers, + 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; + // 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. + 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}` }, + }); + } +} + +function missingSetting(field: string, variable: string) { + return new WorkloadIdentityError( + 'invalid_configuration', + `${field} is required (or set ${variable})`, + ); +} + +/** + * 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. + */ +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; + } +} + +/** + * 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: withoutAssertion(body.error, assertion), + 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( + '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..d5fd3aba3 --- /dev/null +++ b/src/workload-identity/workload-identity-error.ts @@ -0,0 +1,88 @@ +// @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 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 is not one the token endpoint accepts. Leave the resource unset to use the default, https://api.workos.com.', + ], + [ + 'invalid_client', + '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 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', + '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: 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'; + /** 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..cbf1d50dd --- /dev/null +++ b/src/workload-identity/workload-identity.spec.ts @@ -0,0 +1,1674 @@ +// @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 { sealData } from '../common/crypto/seal'; +import { + ApiKeyRequiredException, + UnauthorizedException, +} from '../common/exceptions'; +import userFixture from '../user-management/fixtures/user.json'; +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']) { + 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: 'orgs: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: 'orgs:write', + }); + expect(form(exchanges[1])).not.toHaveProperty('client_secret'); + expect(exchanges[1].headers.has('authorization')).toBe(false); + }); + + 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({ + 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-02: (b) with no environment ID the API request carries the access token and no environment header', async () => { + // The SDK does not read this variable. `afterEach` restores it. + process.env.WORKOS_ENVIRONMENT_ID = 'environment_env'; + + 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', ''], + ['a null', null], + ])( + '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); + }, + ); + + 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; + + 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(); + }); + + // 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, + 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(requested).toEqual([TOKEN_URL]); + 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), + ); + + // 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); + 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); + }); + + 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', () => { + 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. + 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$/, + ); + + // (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('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-')); + 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 only clientId defaults 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) 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 = + '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(TOKEN_URL); + expect(form(exchanges[2]).client_id).toBe('client_env'); + expect(form(exchanges[2])).not.toHaveProperty('scope'); + + // (d) An explicit client ID wins over the variable. + await new WorkOS({ + credentials: new WorkloadIdentityCredentials({ + clientId: CLIENT_ID, + tokenUrl: TOKEN_URL, + identityTokenProvider: async () => 'assertion-1', + }), + }).get('/organizations'); + + 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([ + [ + 'clientId', + { clientId: undefined }, + 'clientId is required (or set WORKOS_CLIENT_ID)', + ], + ['tokenUrl', { tokenUrl: '' }, 'tokenUrl is required'], + [ + 'identityTokenProvider', + { identityTokenProvider: undefined }, + 'identityTokenProvider is required', + ], + [ + 'a valid tokenUrl', + { tokenUrl: 'not a url' }, + 'tokenUrl must be an absolute https 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.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 () => { + 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 c5190a046..774ad5169 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,10 +227,6 @@ export class WorkOS { Object.assign(headers, configHeaders); } - if (this.key) { - headers['Authorization'] = `Bearer ${this.key}`; - } - return new FetchHttpClient( this.baseURL, { @@ -211,6 +236,7 @@ export class WorkOS { headers, }, options.fetchFn, + { credentials: this.requestCredentials }, ) as HttpClient; } @@ -219,16 +245,43 @@ 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, 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 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); } } + /** + * 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, @@ -426,6 +479,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 }); }