From f3a0d736d9c14ea66ffaabdc45fcc79e03d6b657 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 01:11:19 -0800 Subject: [PATCH 01/15] feat: add workload identity federation Authenticate with the identity the platform already gives a workload, instead of a stored API key. `WorkOS.Client.new(credentials: pid)` takes a `WorkOS.WorkloadIdentity.Credentials` process, which exchanges the workload's identity token for a short-lived access token (jwt-bearer), caches it, and refreshes it before it expires. SDK: - Every client now authenticates through `WorkOS.Credentials`. Credentials are resolved before every HTTP attempt, including transport retries. On a 401 the rejected token generation is invalidated and the same request is sent once more. A static API key is the trivial implementation and behaves as before. - `WorkOS.WorkloadIdentity.Credentials` runs at most one exchange at a time for all callers, bounded at 30 seconds. A caller that stops waiting does not stop the exchange. The exchange retries transport failures, 429 and 5xx with the SDK's own retry count and backoff. - `WorkOS.WorkloadIdentity.token_file/1` and `token_env/1` providers, and `WorkOS.WorkloadIdentityError` with a code, description and hint. - Passing both `api_key:` and `credentials:` raises. With `credentials:`, `WORKOS_API_KEY` is ignored. Provider packages, each its own Mix project with no dependency on workos: - workload_identity_github_actions (workos_workload_identity_github_actions) - workload_identity_gcp (workos_workload_identity_gcp) - workload_identity_aws (workos_workload_identity_aws), on `aws` and `aws_credentials` Release and CI: - release-please entries for the three packages, starting at 0.1.0, with separate release PRs. release.yml publishes each package from its own tag; the SDK job now runs only for `v*` tags. - script/ci, ci.yml and lint.yml build, lint and test each package. The SDK does not list the provider packages as optional dependencies: Hex rejects path dependencies when it builds a package, and the providers are not on Hex yet. Spec: docs/ideation/wif-backend-sdks/spec-phase-8.md Review passed in 2 cycles. --- .github/workflows/ci.yml | 66 + .github/workflows/lint.yml | 62 + .github/workflows/release-please.yml | 46 +- .github/workflows/release.yml | 119 ++ .release-please-manifest.json | 5 +- README.md | 67 +- lib/workos/client.ex | 218 +++- lib/workos/credential_snapshot.ex | 28 + lib/workos/credentials.ex | 39 + lib/workos/credentials/static_key.ex | 25 + lib/workos/errors.ex | 3 +- lib/workos/workload_identity.ex | 73 ++ lib/workos/workload_identity/credentials.ex | 346 +++++ lib/workos/workload_identity/exchange.ex | 235 ++++ lib/workos/workload_identity_error.ex | 85 ++ release-please-config.json | 25 + script/ci | 25 + test/workos/workload_identity_test.exs | 1147 +++++++++++++++++ workload_identity_aws/.formatter.exs | 3 + workload_identity_aws/.gitignore | 9 + workload_identity_aws/CHANGELOG.md | 1 + workload_identity_aws/LICENSE | 21 + workload_identity_aws/README.md | 38 + workload_identity_aws/config/config.exs | 11 + .../lib/workos/workload_identity/aws.ex | 190 +++ .../workload_identity/aws/http_client.ex | 66 + workload_identity_aws/mix.exs | 69 + workload_identity_aws/mix.lock | 18 + .../test/support/stub_http_client.ex | 21 + .../test/support/test_server.ex | 96 ++ workload_identity_aws/test/test_helper.exs | 3 + .../workos/workload_identity/aws_test.exs | 269 ++++ workload_identity_gcp/.formatter.exs | 3 + workload_identity_gcp/.gitignore | 9 + workload_identity_gcp/CHANGELOG.md | 1 + workload_identity_gcp/LICENSE | 21 + workload_identity_gcp/README.md | 35 + .../lib/workos/workload_identity/gcp.ex | 105 ++ workload_identity_gcp/mix.exs | 65 + workload_identity_gcp/mix.lock | 12 + .../test/support/test_server.ex | 96 ++ workload_identity_gcp/test/test_helper.exs | 3 + .../workos/workload_identity/gcp_test.exs | 87 ++ .../.formatter.exs | 3 + workload_identity_github_actions/.gitignore | 9 + workload_identity_github_actions/CHANGELOG.md | 1 + workload_identity_github_actions/LICENSE | 21 + workload_identity_github_actions/README.md | 41 + .../workload_identity/github_actions.ex | 152 +++ workload_identity_github_actions/mix.exs | 65 + workload_identity_github_actions/mix.lock | 12 + .../test/support/test_server.ex | 96 ++ .../test/test_helper.exs | 3 + .../workload_identity/github_actions_test.exs | 149 +++ 54 files changed, 4395 insertions(+), 23 deletions(-) create mode 100644 lib/workos/credential_snapshot.ex create mode 100644 lib/workos/credentials.ex create mode 100644 lib/workos/credentials/static_key.ex create mode 100644 lib/workos/workload_identity.ex create mode 100644 lib/workos/workload_identity/credentials.ex create mode 100644 lib/workos/workload_identity/exchange.ex create mode 100644 lib/workos/workload_identity_error.ex create mode 100644 test/workos/workload_identity_test.exs create mode 100644 workload_identity_aws/.formatter.exs create mode 100644 workload_identity_aws/.gitignore create mode 100644 workload_identity_aws/CHANGELOG.md create mode 100644 workload_identity_aws/LICENSE create mode 100644 workload_identity_aws/README.md create mode 100644 workload_identity_aws/config/config.exs create mode 100644 workload_identity_aws/lib/workos/workload_identity/aws.ex create mode 100644 workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex create mode 100644 workload_identity_aws/mix.exs create mode 100644 workload_identity_aws/mix.lock create mode 100644 workload_identity_aws/test/support/stub_http_client.ex create mode 100644 workload_identity_aws/test/support/test_server.ex create mode 100644 workload_identity_aws/test/test_helper.exs create mode 100644 workload_identity_aws/test/workos/workload_identity/aws_test.exs create mode 100644 workload_identity_gcp/.formatter.exs create mode 100644 workload_identity_gcp/.gitignore create mode 100644 workload_identity_gcp/CHANGELOG.md create mode 100644 workload_identity_gcp/LICENSE create mode 100644 workload_identity_gcp/README.md create mode 100644 workload_identity_gcp/lib/workos/workload_identity/gcp.ex create mode 100644 workload_identity_gcp/mix.exs create mode 100644 workload_identity_gcp/mix.lock create mode 100644 workload_identity_gcp/test/support/test_server.ex create mode 100644 workload_identity_gcp/test/test_helper.exs create mode 100644 workload_identity_gcp/test/workos/workload_identity/gcp_test.exs create mode 100644 workload_identity_github_actions/.formatter.exs create mode 100644 workload_identity_github_actions/.gitignore create mode 100644 workload_identity_github_actions/CHANGELOG.md create mode 100644 workload_identity_github_actions/LICENSE create mode 100644 workload_identity_github_actions/README.md create mode 100644 workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex create mode 100644 workload_identity_github_actions/mix.exs create mode 100644 workload_identity_github_actions/mix.lock create mode 100644 workload_identity_github_actions/test/support/test_server.ex create mode 100644 workload_identity_github_actions/test/test_helper.exs create mode 100644 workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3739dd0c..eb161c67 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,3 +95,69 @@ jobs: - name: Run tests run: mix test + + # Each workload identity provider package is its own Mix project with its + # own release, so each is built and tested on its own, on the same version + # pairs as the SDK. + providers: + name: ${{ matrix.package }} (Elixir ${{ matrix.beam.elixir }} / OTP ${{ matrix.beam.otp }}) + + runs-on: ubuntu-latest + defaults: + run: + working-directory: ${{ matrix.package }} + strategy: + fail-fast: false + matrix: + package: + - workload_identity_github_actions + - workload_identity_gcp + - workload_identity_aws + beam: + - elixir: '1.20' + otp: '28' + - elixir: '1.19' + otp: '28' + - elixir: '1.18' + otp: '27' + + steps: + - name: Check out this repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Set up Elixir and Erlang/OTP + uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + id: beam + with: + elixir-version: ${{ matrix.beam.elixir }} + otp-version: ${{ matrix.beam.otp }} + + - name: Restore dependencies and build cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + id: mix-cache + with: + path: | + ${{ matrix.package }}/deps + ${{ matrix.package }}/_build + key: ${{ runner.os }}-otp-${{ steps.beam.outputs.otp-version }}-elixir-${{ steps.beam.outputs.elixir-version }}-mix-${{ env.MIX_ENV }}-${{ matrix.package }}-${{ hashFiles(format('{0}/mix.lock', matrix.package)) }} + + - name: Install and compile dependencies + if: steps.mix-cache.outputs.cache-hit != 'true' + run: | + mix deps.get + mix deps.compile + + - name: Save dependencies and build cache + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + if: steps.mix-cache.outputs.cache-hit != 'true' + with: + path: | + ${{ matrix.package }}/deps + ${{ matrix.package }}/_build + key: ${{ steps.mix-cache.outputs.cache-primary-key }} + + - name: Compile with warnings as errors + run: mix compile --warnings-as-errors + + - name: Run tests + run: mix test diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index feae8667..30f746a8 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -75,6 +75,68 @@ jobs: - name: Run Credo run: mix credo --strict -a + # The same checks for each workload identity provider package. Each is its + # own Mix project, so the root checks above do not reach them. + lint-providers: + name: Format & Credo (${{ matrix.package }}) + runs-on: ubuntu-latest + defaults: + run: + working-directory: ${{ matrix.package }} + strategy: + fail-fast: false + matrix: + package: + - workload_identity_github_actions + - workload_identity_gcp + - workload_identity_aws + steps: + - name: Check out this repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Set up Elixir and Erlang/OTP + uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + id: beam + with: + elixir-version: ${{ env.ELIXIR_VERSION }} + otp-version: ${{ env.OTP_VERSION }} + + - name: Restore dependencies and build cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + id: mix-cache + with: + path: | + ${{ matrix.package }}/deps + ${{ matrix.package }}/_build + key: ${{ runner.os }}-otp-${{ steps.beam.outputs.otp-version }}-elixir-${{ steps.beam.outputs.elixir-version }}-mix-${{ env.MIX_ENV }}-${{ matrix.package }}-${{ hashFiles(format('{0}/mix.lock', matrix.package)) }} + + - name: Install and compile dependencies + if: steps.mix-cache.outputs.cache-hit != 'true' + run: | + mix deps.get + mix deps.compile + + - name: Save dependencies and build cache + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + if: steps.mix-cache.outputs.cache-hit != 'true' + with: + path: | + ${{ matrix.package }}/deps + ${{ matrix.package }}/_build + key: ${{ steps.mix-cache.outputs.cache-primary-key }} + + - name: Check for unused dependencies + run: mix deps.unlock --check-unused + + - name: Check formatting + run: mix format --check-formatted + + - name: Compile with warnings as errors + run: mix compile --warnings-as-errors + + - name: Run Credo + run: mix credo --strict -a + dialyzer: name: Dialyzer runs-on: ubuntu-latest diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index eb216db5..df8c9204 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -24,10 +24,18 @@ jobs: # (changelog enrichment, release notes) can fail it. release-please: runs-on: ubuntu-latest + # `release_created` and `tag_name` describe the SDK (the root package) + # only. Each provider package has its own release PR, tag + # (`-vX.Y.Z`) and outputs, keyed by its path. Publishing does not + # read these outputs: release.yml publishes on the `release: published` + # event and picks the package from the tag. outputs: - pr: ${{ steps.release.outputs.pr }} + prs: ${{ steps.release.outputs.prs }} release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} + github_actions_release_created: ${{ steps.release.outputs['workload_identity_github_actions--release_created'] }} + gcp_release_created: ${{ steps.release.outputs['workload_identity_gcp--release_created'] }} + aws_release_created: ${{ steps.release.outputs['workload_identity_aws--release_created'] }} steps: - name: Generate token id: generate-token @@ -48,10 +56,32 @@ jobs: # release or any publish that depends on release-please. enrich-release-pr: needs: release-please - if: needs.release-please.outputs.pr + if: needs.release-please.outputs.prs runs-on: ubuntu-latest steps: + # Release PRs are separate per package, so `prs` can also hold a + # provider package's PR. Only the SDK's own PR is enriched: the + # .changelog-pending fragments and the root CHANGELOG.md belong to it. + # The provider PRs are the ones that name a workload_identity package + # in their branch or title. + - name: Select the SDK release PR + id: sdk-pr + env: + PRS_JSON: ${{ needs.release-please.outputs.prs }} + run: | + set -euo pipefail + pr="$(jq -c '[.[] | select((.headBranchName + " " + .title) | test("workload_identity") | not)][0] // empty' <<<"$PRS_JSON")" + if [ -z "$pr" ]; then + echo "No SDK release PR in this run; nothing to enrich." + exit 0 + fi + { + echo "branch=$(jq -r '.headBranchName' <<<"$pr")" + echo "title=$(jq -r '.title' <<<"$pr")" + } >> "$GITHUB_OUTPUT" + - name: Generate token + if: steps.sdk-pr.outputs.branch id: generate-token uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 with: @@ -61,9 +91,10 @@ jobs: permission-pull-requests: write - name: Checkout release PR branch + if: steps.sdk-pr.outputs.branch uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: - ref: ${{ fromJSON(needs.release-please.outputs.pr).headBranchName }} + ref: ${{ steps.sdk-pr.outputs.branch }} token: ${{ steps.generate-token.outputs.token }} # Inline pending changelog fragments under the version heading @@ -74,8 +105,9 @@ jobs: # release-please wrote. Fragments are deleted in the same commit. # Idempotent: if no fragments exist, skip silently. - name: Inline rich changelog fragments + if: steps.sdk-pr.outputs.branch env: - PR_JSON: ${{ needs.release-please.outputs.pr }} + PR_TITLE: ${{ steps.sdk-pr.outputs.title }} run: | set -euo pipefail shopt -s nullglob @@ -85,7 +117,7 @@ jobs: exit 0 fi - VERSION=$(echo "$PR_JSON" | jq -r '.title' | grep -oE '[0-9]+\.[0-9]+\.[0-9]+') + VERSION=$(echo "$PR_TITLE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+') export VERSION python3 - <<'PY' @@ -157,7 +189,9 @@ jobs: # After release-please tags the release and creates the GitHub Release, # replace its body with the rich section from CHANGELOG.md (release-please # writes only its terse default rendering). Cosmetic-only: never fails the - # release if the section can't be found. + # release if the section can't be found. SDK releases only: the plain + # `release_created` and `tag_name` outputs are the root package's, and + # provider releases keep release-please's default notes. update-release-notes: needs: release-please if: needs.release-please.outputs.release_created == 'true' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c36ca2cf..ea532661 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,9 +8,14 @@ defaults: run: shell: bash +# Every package in this repo has its own release and tag: `vX.Y.Z` for the SDK +# and `-vX.Y.Z` for each workload identity provider package. Each +# published release runs this workflow once, and the tag decides which one job +# publishes. jobs: publish: name: Publish to Hex + if: startsWith(github.event.release.tag_name, 'v') runs-on: ubuntu-latest permissions: contents: read @@ -46,3 +51,117 @@ jobs: run: mix hex.publish --yes env: HEX_API_KEY: ${{ secrets.HEX_API_KEY }} + + publish-workload-identity-github-actions: + name: Publish workos_workload_identity_github_actions to Hex + if: startsWith(github.event.release.tag_name, 'workos_workload_identity_github_actions-v') + runs-on: ubuntu-latest + permissions: + contents: read + defaults: + run: + shell: bash + working-directory: workload_identity_github_actions + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Set up Elixir and Erlang/OTP + uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + with: + # The minimum supported pair, as for the SDK. + elixir-version: '1.18' + otp-version: '27' + + - name: Install dependencies + run: mix deps.get + + - name: Verify tag matches mix.exs version + run: | + TAG_VERSION="${GITHUB_REF_NAME#workos_workload_identity_github_actions-v}" + MIX_VERSION="$(grep -oE '@version "[^"]+"' mix.exs | cut -d'"' -f2)" + if [ "$TAG_VERSION" != "$MIX_VERSION" ]; then + echo "Tag $GITHUB_REF_NAME does not match workload_identity_github_actions/mix.exs version $MIX_VERSION" >&2 + exit 1 + fi + + - name: Publish to Hex + run: mix hex.publish --yes + env: + HEX_API_KEY: ${{ secrets.HEX_API_KEY }} + + publish-workload-identity-gcp: + name: Publish workos_workload_identity_gcp to Hex + if: startsWith(github.event.release.tag_name, 'workos_workload_identity_gcp-v') + runs-on: ubuntu-latest + permissions: + contents: read + defaults: + run: + shell: bash + working-directory: workload_identity_gcp + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Set up Elixir and Erlang/OTP + uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + with: + # The minimum supported pair, as for the SDK. + elixir-version: '1.18' + otp-version: '27' + + - name: Install dependencies + run: mix deps.get + + - name: Verify tag matches mix.exs version + run: | + TAG_VERSION="${GITHUB_REF_NAME#workos_workload_identity_gcp-v}" + MIX_VERSION="$(grep -oE '@version "[^"]+"' mix.exs | cut -d'"' -f2)" + if [ "$TAG_VERSION" != "$MIX_VERSION" ]; then + echo "Tag $GITHUB_REF_NAME does not match workload_identity_gcp/mix.exs version $MIX_VERSION" >&2 + exit 1 + fi + + - name: Publish to Hex + run: mix hex.publish --yes + env: + HEX_API_KEY: ${{ secrets.HEX_API_KEY }} + + publish-workload-identity-aws: + name: Publish workos_workload_identity_aws to Hex + if: startsWith(github.event.release.tag_name, 'workos_workload_identity_aws-v') + runs-on: ubuntu-latest + permissions: + contents: read + defaults: + run: + shell: bash + working-directory: workload_identity_aws + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Set up Elixir and Erlang/OTP + uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + with: + # The minimum supported pair, as for the SDK. + elixir-version: '1.18' + otp-version: '27' + + - name: Install dependencies + run: mix deps.get + + - name: Verify tag matches mix.exs version + run: | + TAG_VERSION="${GITHUB_REF_NAME#workos_workload_identity_aws-v}" + MIX_VERSION="$(grep -oE '@version "[^"]+"' mix.exs | cut -d'"' -f2)" + if [ "$TAG_VERSION" != "$MIX_VERSION" ]; then + echo "Tag $GITHUB_REF_NAME does not match workload_identity_aws/mix.exs version $MIX_VERSION" >&2 + exit 1 + fi + + - name: Publish to Hex + run: mix hex.publish --yes + env: + HEX_API_KEY: ${{ secrets.HEX_API_KEY }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ada7355e..8c8c3a1c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,6 @@ { - ".": "3.1.0" + ".": "3.1.0", + "workload_identity_github_actions": "0.0.0", + "workload_identity_gcp": "0.0.0", + "workload_identity_aws": "0.0.0" } diff --git a/README.md b/README.md index beb6bbc0..bcd7725f 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ client = WorkOS.client(api_key: "sk_example_123456789") All API functions take the client as their first argument and return `{:ok, result}` or `{:error, error}` tuples. Errors are typed: `WorkOS.ApiError` for non-2xx API responses (with a `:kind` atom such as `:not_found`) and `WorkOS.TransportError` for network failures. -Client configuration is per-instance — there is no global state. Options: `:api_key`, `:base_url`, `:timeout`, `:max_retries`, `:req_options`. Per-request options (`:headers`, `:timeout`, `:idempotency_key`, `:query`) can be passed as the final argument to any API function. +Client configuration is per-instance — there is no global state. Options: `:api_key`, `:credentials`, `:base_url`, `:timeout`, `:max_retries`, `:req_options`. Per-request options (`:headers`, `:timeout`, `:idempotency_key`, `:query`) can be passed as the final argument to any API function. ### Pagination @@ -45,6 +45,71 @@ page |> Enum.each(&IO.inspect/1) ``` +### Workload identity + +A workload that already has an identity from its platform (a GitHub Actions job, a Google Cloud service account, an AWS role) can authenticate without a stored API key. The SDK exchanges the platform's identity token for a short-lived WorkOS access token, caches it, and refreshes it before it expires. + +Start a credentials process and pass it to the client: + +```elixir +{:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: provider + ) + +client = WorkOS.Client.new(credentials: credentials) +``` + +`:client_id`, `:token_url`, `:environment_id` and `:scope` fall back to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL`, `WORKOS_ENVIRONMENT_ID` and `WORKOS_WIF_SCOPE` environment variables. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. + +In an application, supervise the process under a name of your choosing and build clients from the name: + +```elixir +children = [ + {WorkOS.WorkloadIdentity.Credentials, name: MyApp.WorkOSCredentials, identity_token_provider: provider} +] + +client = WorkOS.Client.new(credentials: MyApp.WorkOSCredentials) +``` + +The `provider` returns the workload's identity token. Each platform's provider is its own package, with no dependency on `workos`. Add the one you need: + +```elixir +def deps do + [ + {:workos_workload_identity_github_actions, "~> 0.1"}, + # or {:workos_workload_identity_gcp, "~> 0.1"} + # or {:workos_workload_identity_aws, "~> 0.1"} + ] +end +``` + +```elixir +# GitHub Actions. The workflow or job needs `permissions: id-token: write`. +provider = WorkOS.WorkloadIdentity.GitHubActions.github_actions("https://api.workos.com") + +# Google Cloud: Compute Engine, GKE, Cloud Run, Cloud Functions, App Engine. +provider = WorkOS.WorkloadIdentity.GCP.gcp_metadata("https://api.workos.com") + +# AWS: Lambda, EC2, ECS, EKS. The region is optional when AWS_REGION is set. +provider = WorkOS.WorkloadIdentity.AWS.aws_sts("https://api.workos.com", "us-east-1") +``` + +The argument is the audience the identity token is requested for. + +No package is needed when the token is already in a file or an environment variable, or when you fetch it yourself. A provider is any zero-arity function (or `{module, function, args}` tuple) that returns `{:ok, token}` or `{:error, reason}`: + +```elixir +provider = WorkOS.WorkloadIdentity.token_file("/var/run/secrets/tokens/workos") +provider = WorkOS.WorkloadIdentity.token_env("MY_IDENTITY_TOKEN") +provider = fn -> MyApp.Identity.fetch_token() end +``` + +When the exchange fails, API functions return `{:error, %WorkOS.WorkloadIdentityError{}}`. Its `:code` is the OAuth error code from the token endpoint (for example `"invalid_grant"`), and its `:hint` says what to check. + ## SDK Versioning For our SDKs WorkOS follows a Semantic Versioning process where all releases will have a version X.Y.Z (like 1.0.0) pattern wherein Z would be a bug fix (I.e. 1.0.1), Y would be a minor release (1.1.0) and X would be a major release (2.0.0). We permit any breaking changes to only be released in major versions and strongly recommend reading changelogs before making any major version upgrades. diff --git a/lib/workos/client.ex b/lib/workos/client.ex index b1b2a077..ed9fd5c1 100644 --- a/lib/workos/client.ex +++ b/lib/workos/client.ex @@ -10,9 +10,19 @@ defmodule WorkOS.Client do The API key falls back to the `WORKOS_API_KEY` environment variable. + To authenticate with workload identity federation instead of an API key, + start a `WorkOS.WorkloadIdentity.Credentials` process and pass it in: + + client = WorkOS.Client.new(credentials: credentials) + ## Options for `new/1` - * `:api_key` — API key (required unless the env var is set) + * `:api_key` — API key (required unless the env var is set or + `:credentials` is given) + * `:credentials` — the pid or registered name of a started + `WorkOS.WorkloadIdentity.Credentials` process. Passing both `:api_key` + and `:credentials` raises `WorkOS.ConfigurationError`. With + `:credentials`, `WORKOS_API_KEY` is ignored and never sent. * `:client_id` — client ID used by authentication flows and URL builders (falls back to the `WORKOS_CLIENT_ID` environment variable) * `:base_url` — override the API base URL @@ -28,10 +38,20 @@ defmodule WorkOS.Client do import Bitwise - defstruct [:api_key, :client_id, :base_url, :jwt_issuer, :timeout, :max_retries, :req_options] + defstruct [ + :api_key, + :credentials, + :client_id, + :base_url, + :jwt_issuer, + :timeout, + :max_retries, + :req_options + ] @type t :: %__MODULE__{ - api_key: String.t(), + api_key: String.t() | nil, + credentials: WorkOS.Credentials.t() | nil, client_id: String.t() | nil, base_url: String.t(), jwt_issuer: [String.t()] | nil, @@ -54,20 +74,21 @@ defmodule WorkOS.Client do @idempotency_header "idempotency-key" @request_id_header "x-request-id" + # Req private keys. Private data survives Req's own retries and redirects, + # so the one 401 recovery a logical request is allowed cannot be reset. + @snapshot_key :workos_credential_snapshot + @recovery_used_key :workos_credential_recovery_used + @doc """ Builds a new client. See the module documentation for options. """ @spec new(keyword()) :: t() def new(opts \\ []) do - api_key = opts[:api_key] || System.get_env(@api_key_env) - - if !(is_binary(api_key) and api_key != "") do - raise WorkOS.ConfigurationError, - message: "Missing API key. Pass `api_key:` to WorkOS.Client.new/1 or set WORKOS_API_KEY." - end + {api_key, credentials} = authentication(opts) %__MODULE__{ api_key: api_key, + credentials: credentials, client_id: opts[:client_id] || System.get_env(@client_id_env), base_url: String.trim_trailing(opts[:base_url] || @default_base_url, "/"), jwt_issuer: normalize_issuers(Keyword.get_lazy(opts, :jwt_issuer, &issuer_from_env/0)), @@ -106,15 +127,16 @@ defmodule WorkOS.Client do body = if query_method?, do: nil, else: params max_retries = opts[:max_retries] || client.max_retries + timeout = opts[:timeout] || client.timeout + credentials = credentials(client) req_options = [ method: method, url: path, base_url: normalize_base_url(opts[:base_url]) || client.base_url, - auth: {:bearer, client.api_key}, headers: build_headers(client, method, opts, max_retries), - receive_timeout: opts[:timeout] || client.timeout, + receive_timeout: timeout, retry: &retryable?/2, retry_delay: &retry_delay/1, max_retries: max_retries, @@ -123,17 +145,175 @@ defmodule WorkOS.Client do |> put_query(query) |> put_body(body) - req = Req.new(req_options) |> Req.merge(client.req_options) + req = + req_options + |> Req.new() + |> Req.merge(client.req_options) + |> Req.Request.append_request_steps( + workos_credentials: &put_credentials(&1, credentials, timeout) + ) + |> Req.Request.prepend_response_steps( + workos_credential_recovery: &recover_credentials(&1, credentials) + ) req |> Req.request() |> handle_response() end + # -- credentials ------------------------------------------------------------ + # + # Every client authenticates through `WorkOS.Credentials`. A static API key + # is the trivial implementation; a client built by hand with only a key + # (as `WorkOS.PublicClient` does) gets it too. + + defp credentials(%__MODULE__{credentials: nil, api_key: api_key}), + do: {WorkOS.Credentials.StaticKey, api_key} + + defp credentials(%__MODULE__{credentials: credentials}), do: credentials + + # Authentication precedence, in order: an explicit key together with + # explicit credentials is an error; explicit credentials are used and + # WORKOS_API_KEY is ignored; an explicit key is used; only when neither is + # passed does WORKOS_API_KEY apply. + defp authentication(opts) do + case {opts[:api_key], opts[:credentials]} do + {api_key, nil} -> + {api_key!(api_key || System.get_env(@api_key_env)), nil} + + {nil, server} -> + {nil, {WorkOS.WorkloadIdentity.Credentials, credentials_server!(server)}} + + {_api_key, _server} -> + raise WorkOS.ConfigurationError, + message: + "Pass either `api_key:` or `credentials:` to WorkOS.Client.new/1, not both. " <> + "A client authenticates with one or the other." + end + end + + defp api_key!(api_key) when is_binary(api_key) and api_key != "", do: api_key + + defp api_key!(_missing) do + raise WorkOS.ConfigurationError, + message: "Missing API key. Pass `api_key:` to WorkOS.Client.new/1 or set WORKOS_API_KEY." + end + + # Anything `GenServer.call/3` can address. + defp credentials_server!(server) when is_pid(server), do: server + + defp credentials_server!(server) when is_atom(server) and not is_boolean(server), + do: server + + defp credentials_server!({:global, _name} = server), do: server + defp credentials_server!({:via, module, _name} = server) when is_atom(module), do: server + + defp credentials_server!({name, node} = server) when is_atom(name) and is_atom(node), + do: server + + defp credentials_server!(_other) do + raise WorkOS.ConfigurationError, + message: + "`credentials:` must be the pid or registered name of a started " <> + "WorkOS.WorkloadIdentity.Credentials process." + end + + # Request step. Req runs request steps once per `Req.request/1`, but calls + # the adapter for every HTTP attempt: the first one, each transport retry, + # each redirect and the 401 recovery. Wrapping the adapter is therefore what + # resolves the credentials before every attempt, so a retry never sends an + # expired token. It runs last, after Req has chosen the adapter. + defp put_credentials(%Req.Request{} = request, credentials, timeout) do + adapter = request.adapter + origin = origin(request.url) + + %{request | adapter: &send_attempt(&1, adapter, credentials, timeout, origin)} + end + + defp send_attempt(request, adapter, credentials, timeout, origin) do + if origin(request.url) == origin or request.options[:redirect_trusted] == true do + send_with_credentials(request, adapter, credentials, timeout) + else + # A redirect to another origin. Req has already removed the + # Authorization header; keep every credential header off the request. + run_adapter(adapter, drop_credentials(request)) + end + end + + defp send_with_credentials(request, adapter, credentials, timeout) do + case WorkOS.Credentials.resolve(credentials, timeout) do + {:ok, %WorkOS.CredentialSnapshot{} = snapshot} -> + run_adapter(adapter, put_snapshot(request, snapshot)) + + {:error, exception} -> + # Terminal for the request: `retryable?/2` only retries Req's own + # transport errors. + {request, exception} + end + end + + # The snapshot's headers overwrite any the request already has. The snapshot + # is kept so a 401 invalidates this credential, not whichever one is + # current by then. + defp put_snapshot(request, snapshot) do + snapshot.headers + |> Enum.reduce(request, fn {name, value}, request -> + Req.Request.put_header(request, name, value) + end) + |> Req.Request.put_private(@snapshot_key, snapshot) + end + + defp run_adapter(adapter, request) when is_function(adapter, 1), do: adapter.(request) + + defp run_adapter({module, function, args}, request), + do: apply(module, function, [request | args]) + + defp drop_credentials(request) do + headers = + case Req.Request.get_private(request, @snapshot_key) do + %WorkOS.CredentialSnapshot{headers: headers} -> headers + nil -> [] + end + + headers + |> Enum.reduce(request, fn {name, _value}, request -> + Req.Request.delete_header(request, name) + end) + |> Req.Request.put_private(@snapshot_key, nil) + end + + defp origin(%URI{scheme: scheme, host: host, port: port}), do: {scheme, host, port} + + # Response step, ahead of Req's retry step. On a 401 for a recoverable + # snapshot it invalidates that snapshot's generation and sends the same + # request again (same body, same idempotency key), once per logical + # request. The resend does not count against the retry limit and does not + # wait for a backoff. Whatever comes back is handled as a normal response. + defp recover_credentials({request, %Req.Response{status: 401} = response}, credentials) do + snapshot = Req.Request.get_private(request, @snapshot_key) + recovery_used? = Req.Request.get_private(request, @recovery_used_key, false) + + if match?(%WorkOS.CredentialSnapshot{recoverable: true}, snapshot) and not recovery_used? do + request = Req.Request.put_private(request, @recovery_used_key, true) + :ok = WorkOS.Credentials.invalidate(credentials, snapshot.generation) + + {request, response_or_exception} = Req.Request.run_request(%{request | halted: false}) + Req.Request.halt(request, response_or_exception) + else + {request, response} + end + end + + defp recover_credentials(request_and_response, _credentials), do: request_and_response + defp handle_response({:ok, %Req.Response{status: status} = response}) when status in 200..299, do: {:ok, decode_body(response)} defp handle_response({:ok, %Req.Response{} = response}), do: {:error, api_error(response)} + # Errors from resolving credentials are already typed. + defp handle_response({:error, %WorkOS.WorkloadIdentityError{} = error}), do: {:error, error} + defp handle_response({:error, %WorkOS.TransportError{} = error}), do: {:error, error} + defp handle_response({:error, %{__exception__: true} = exception}), do: {:error, %WorkOS.TransportError{message: Exception.message(exception), reason: exception}} @@ -241,7 +421,15 @@ defmodule WorkOS.Client do end end - defp user_agent, do: "workos-elixir/#{Application.spec(:workos, :vsn)}" + @doc false + @spec user_agent() :: String.t() + def user_agent, do: "workos-elixir/#{Application.spec(:workos, :vsn)}" + + # The retry count and backoff are shared with the workload identity token + # exchange, so there is one set of values. + @doc false + @spec default_max_retries() :: non_neg_integer() + def default_max_retries, do: @default_max_retries defp retryable?(_request, %Req.Response{status: status}), do: status in @retryable_status_codes @@ -249,7 +437,9 @@ defmodule WorkOS.Client do defp retryable?(_request, %Req.TransportError{}), do: true defp retryable?(_request, _other), do: false - defp retry_delay(attempt) do + @doc false + @spec retry_delay(non_neg_integer()) :: non_neg_integer() + def retry_delay(attempt) do base = min(@initial_retry_delay_ms * :math.pow(@retry_multiplier, attempt), @max_retry_delay_ms) diff --git a/lib/workos/credential_snapshot.ex b/lib/workos/credential_snapshot.ex new file mode 100644 index 00000000..614fa575 --- /dev/null +++ b/lib/workos/credential_snapshot.ex @@ -0,0 +1,28 @@ +# @oagen-ignore-file + +defmodule WorkOS.CredentialSnapshot do + @moduledoc """ + The credential one HTTP attempt is sent with. + + A snapshot is immutable. `WorkOS.Client` resolves one before every HTTP + attempt, sets its headers on the request, and keeps it for that attempt, so + a 401 can invalidate exactly the credential that was rejected. + + * `:headers` — the authorization headers for this attempt + * `:generation` — opaque; identifies the credential the headers came from + * `:recoverable` — whether a 401 on this snapshot is worth one re-resolve + + The headers hold a bearer token, so they are left out when a snapshot is + inspected. + """ + + @derive {Inspect, only: [:generation, :recoverable]} + @enforce_keys [:headers, :generation, :recoverable] + defstruct [:headers, :generation, :recoverable] + + @type t :: %__MODULE__{ + headers: [{String.t(), String.t()}], + generation: term(), + recoverable: boolean() + } +end diff --git a/lib/workos/credentials.ex b/lib/workos/credentials.ex new file mode 100644 index 00000000..aa891002 --- /dev/null +++ b/lib/workos/credentials.ex @@ -0,0 +1,39 @@ +# @oagen-ignore-file + +defmodule WorkOS.Credentials do + @moduledoc """ + The contract every `WorkOS.Client` authenticates through. + + Two operations: + + * `c:resolve/2` returns the `WorkOS.CredentialSnapshot` to send one HTTP + attempt with. It may wait, up to the given timeout. + * `c:invalidate/2` marks the credential behind a generation as rejected. + It never waits on the network. + + The SDK ships two implementations. A static API key is + `WorkOS.Credentials.StaticKey`: one fixed header, never recoverable. + Workload identity federation is `WorkOS.WorkloadIdentity.Credentials`: a + short-lived access token that is exchanged, cached and refreshed by a + process the application starts. + """ + + @typedoc """ + An implementing module and the value its callbacks take. + """ + @type t :: {module(), term()} + + @callback resolve(credentials :: term(), timeout()) :: + {:ok, WorkOS.CredentialSnapshot.t()} | {:error, Exception.t()} + + @callback invalidate(credentials :: term(), generation :: term()) :: :ok + + @doc false + @spec resolve(t(), timeout()) :: {:ok, WorkOS.CredentialSnapshot.t()} | {:error, Exception.t()} + def resolve({module, credentials}, timeout), do: module.resolve(credentials, timeout) + + @doc false + @spec invalidate(t(), term()) :: :ok + def invalidate({module, credentials}, generation), + do: module.invalidate(credentials, generation) +end diff --git a/lib/workos/credentials/static_key.ex b/lib/workos/credentials/static_key.ex new file mode 100644 index 00000000..46215fef --- /dev/null +++ b/lib/workos/credentials/static_key.ex @@ -0,0 +1,25 @@ +# @oagen-ignore-file + +defmodule WorkOS.Credentials.StaticKey do + @moduledoc """ + `WorkOS.Credentials` for a static API key. + + The key is sent as a bearer token on every attempt. A 401 is never + recovered, because resolving again would return the same key. + """ + + @behaviour WorkOS.Credentials + + @impl WorkOS.Credentials + def resolve(api_key, _timeout) when is_binary(api_key) do + {:ok, + %WorkOS.CredentialSnapshot{ + headers: [{"authorization", "Bearer " <> api_key}], + generation: 0, + recoverable: false + }} + end + + @impl WorkOS.Credentials + def invalidate(_api_key, _generation), do: :ok +end diff --git a/lib/workos/errors.ex b/lib/workos/errors.ex index 5b254355..75305741 100644 --- a/lib/workos/errors.ex +++ b/lib/workos/errors.ex @@ -5,7 +5,8 @@ defmodule WorkOS.Error do Union of the error values SDK functions can return in `{:error, error}` tuples. """ - @type error :: WorkOS.ApiError.t() | WorkOS.TransportError.t() + @type error :: + WorkOS.ApiError.t() | WorkOS.TransportError.t() | WorkOS.WorkloadIdentityError.t() end defmodule WorkOS.ApiError do diff --git a/lib/workos/workload_identity.ex b/lib/workos/workload_identity.ex new file mode 100644 index 00000000..f07f8b26 --- /dev/null +++ b/lib/workos/workload_identity.ex @@ -0,0 +1,73 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity do + @moduledoc """ + Workload identity federation: authenticate to WorkOS with the identity your + platform already gives the workload, instead of a stored API key. + + An identity token provider returns the workload's JWT. The SDK exchanges it + for a short-lived WorkOS access token, caches the token, and refreshes it + before it expires. See `WorkOS.WorkloadIdentity.Credentials` to set it up. + + ## Identity token providers + + A provider is a zero-arity function, or a `{module, function, args}` tuple, + that returns `{:ok, token}` or `{:error, reason}`. It is called again for + every exchange attempt, so it needs no cache and no retries of its own. + + This module has the two providers that read a token the platform has + already written somewhere: `token_file/1` and `token_env/1`. Any function of + the same shape works as a custom provider: + + provider = fn -> MyApp.Vault.fetch_jwt() end + + Providers for GitHub Actions, Google Cloud and AWS are separate packages: + `workos_workload_identity_github_actions`, `workos_workload_identity_gcp` + and `workos_workload_identity_aws`. + """ + + @typedoc """ + Returns the workload's identity token. + """ + @type identity_token_provider :: + (-> {:ok, String.t()} | {:error, term()}) | {module(), atom(), [term()]} + + @doc """ + Returns a provider that reads the token from a file. + + The file is read again on every call, so a rotated token is picked up. + Surrounding whitespace is trimmed. A missing or empty file is an error. + + WorkOS.WorkloadIdentity.token_file("/var/run/secrets/tokens/workos") + """ + @spec token_file(Path.t()) :: (-> {:ok, String.t()} | {:error, String.t()}) + def token_file(path) when is_binary(path), do: fn -> read_file(path) end + + @doc """ + Returns a provider that reads the token from an environment variable. + + The variable is read again on every call. An unset or empty variable is an + error. + + WorkOS.WorkloadIdentity.token_env("MY_IDENTITY_TOKEN") + """ + @spec token_env(String.t()) :: (-> {:ok, String.t()} | {:error, String.t()}) + def token_env(name) when is_binary(name), do: fn -> read_env(name) end + + defp read_file(path) do + case File.read(path) do + {:ok, contents} -> file_token(String.trim(contents), path) + {:error, reason} -> {:error, "identity token file #{path} could not be read: #{reason}"} + end + end + + defp file_token("", path), do: {:error, "identity token file #{path} is empty"} + defp file_token(token, _path), do: {:ok, token} + + defp read_env(name) do + case System.get_env(name) do + token when is_binary(token) and token != "" -> {:ok, token} + _unset_or_empty -> {:error, "environment variable #{name} is not set or is empty"} + end + end +end diff --git a/lib/workos/workload_identity/credentials.ex b/lib/workos/workload_identity/credentials.ex new file mode 100644 index 00000000..aadc7575 --- /dev/null +++ b/lib/workos/workload_identity/credentials.ex @@ -0,0 +1,346 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.Credentials do + @moduledoc """ + Workload identity credentials: a process that exchanges the workload's + identity token for a short-lived WorkOS access token, caches it, and + refreshes it before it expires. + + Start one and pass it to the client. There is no global instance; every + process has its own cache. + + {:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: WorkOS.WorkloadIdentity.token_file("/var/run/secrets/token") + ) + + client = WorkOS.Client.new(credentials: credentials) + + In an application, put it in the supervision tree under a name of your + choosing, so a restarted process is still reachable: + + children = [ + {WorkOS.WorkloadIdentity.Credentials, + name: MyApp.WorkOSCredentials, + identity_token_provider: WorkOS.WorkloadIdentity.token_env("MY_IDENTITY_TOKEN")} + ] + + client = WorkOS.Client.new(credentials: MyApp.WorkOSCredentials) + + ## Options + + * `:identity_token_provider` — required. A zero-arity function or a + `{module, function, args}` tuple that returns `{:ok, token}` or + `{:error, reason}`. See `WorkOS.WorkloadIdentity`. + * `:client_id` — the M2M application's client ID. Falls back to the + `WORKOS_CLIENT_ID` environment variable. + * `:token_url` — the exchange endpoint. Falls back to + `WORKOS_WIF_TOKEN_URL`. There is no built-in default. + * `:environment_id` — sent as the `x-url-environment-id` header on every + API request. Falls back to `WORKOS_ENVIRONMENT_ID`. + * `:resource` — the `resource` form field. Defaults to + `https://api.workos.com`. + * `:scope` — the `scope` form field. Falls back to `WORKOS_WIF_SCOPE`; + left out of the exchange when unset. + * `:name` — registers the process, as in `GenServer.start_link/3`. + * `:req_options` — extra `Req` options merged into the exchange request + (advanced; used by tests to inject `plug:`). The exchange never + retries through Req, never follows a redirect and never sends an + `Authorization` header, whatever is passed here. + + An explicit option always wins over its environment variable. The + environment variables only fill in omitted options; they never turn + workload identity on by themselves. Configuration is fixed once the process + starts. A missing required option makes `start_link/1` return + `{:error, %WorkOS.WorkloadIdentityError{code: "invalid_configuration"}}`. + + ## Behavior + + * The token is reused until less than `min(60 seconds, 20% of its + lifetime)` remains. It is refreshed on demand, by the request that finds + it inside that window; there is no background timer. + * At most one exchange runs at a time. Callers that arrive while it runs + wait for its result. A caller that stops waiting (its call times out) + does not stop the exchange for the others. + * The exchange has 30 seconds in total, including retries. A failed + exchange is not cached; the next call starts a new one. + * The token is held in memory only. + """ + + use GenServer + + @behaviour WorkOS.Credentials + + alias WorkOS.CredentialSnapshot + alias WorkOS.WorkloadIdentity.Exchange + alias WorkOS.WorkloadIdentityError + + @environment_header "x-url-environment-id" + @default_resource "https://api.workos.com" + @exchange_deadline_ms 30_000 + + # A token is refreshed once less than min(60 s, lifetime / 5) remains. + @refresh_threshold_ms 60_000 + @refresh_lifetime_divisor 5 + + @client_id_env "WORKOS_CLIENT_ID" + @token_url_env "WORKOS_WIF_TOKEN_URL" + @scope_env "WORKOS_WIF_SCOPE" + @environment_id_env "WORKOS_ENVIRONMENT_ID" + + # -- public API ------------------------------------------------------------- + + @doc """ + Starts a credentials process linked to the caller. See the module + documentation for options. + """ + @spec start_link(keyword()) :: GenServer.on_start() + def start_link(opts) when is_list(opts) do + {name, opts} = Keyword.pop(opts, :name) + + with {:ok, config} <- config(opts) do + GenServer.start_link(__MODULE__, config, if(name, do: [name: name], else: [])) + end + end + + @doc """ + Returns the snapshot to send one HTTP attempt with: the access token as a + bearer header, plus the environment header. + + Waits for a token exchange when no fresh token is cached, for at most + `timeout` milliseconds. Giving up does not stop the exchange. + """ + @impl WorkOS.Credentials + @spec resolve(GenServer.server(), timeout()) :: + {:ok, CredentialSnapshot.t()} + | {:error, WorkloadIdentityError.t() | WorkOS.TransportError.t()} + def resolve(server, timeout) do + GenServer.call(server, :resolve, timeout) + catch + :exit, {:timeout, _call} -> + {:error, + %WorkOS.TransportError{ + message: "Timed out waiting for workload identity credentials.", + reason: :timeout + }} + + :exit, _reason -> + {:error, + %WorkOS.TransportError{ + message: "The workload identity credentials process is not running.", + reason: :credentials_unavailable + }} + end + + @doc """ + Marks the token of the given generation as rejected, so the next + `resolve/2` exchanges again. A generation that is no longer current is + ignored: a late 401 for an old token does not discard a newer one. + """ + @impl WorkOS.Credentials + @spec invalidate(GenServer.server(), term()) :: :ok + def invalidate(server, generation), do: GenServer.cast(server, {:invalidate, generation}) + + # -- configuration ---------------------------------------------------------- + + defp config(opts) do + # `:clock`, `:sleep` and `:deadline_ms` are test seams. + opts = + Keyword.validate!(opts, [ + :client_id, + :token_url, + :environment_id, + :resource, + :scope, + :identity_token_provider, + req_options: [], + clock: &monotonic_ms/0, + sleep: &Process.sleep/1, + deadline_ms: @exchange_deadline_ms + ]) + + with {:ok, client_id} <- required(opts, :client_id, @client_id_env), + {:ok, token_url} <- required(opts, :token_url, @token_url_env), + {:ok, environment_id} <- required(opts, :environment_id, @environment_id_env), + {:ok, provider} <- provider(opts[:identity_token_provider]) do + {:ok, + %{ + client_id: client_id, + token_url: token_url, + environment_id: environment_id, + resource: present(opts[:resource]) || @default_resource, + scope: present(opts[:scope]) || present(System.get_env(@scope_env)), + identity_token_provider: provider, + req_options: opts[:req_options], + clock: opts[:clock], + sleep: opts[:sleep], + deadline_ms: opts[:deadline_ms] + }} + end + end + + defp required(opts, key, env) do + case present(opts[key]) || present(System.get_env(env)) do + nil -> invalid_configuration("#{key} is required (or set #{env})") + value -> {:ok, value} + end + end + + defp provider(provider) when is_function(provider, 0), do: {:ok, provider} + + defp provider({module, function, args} = provider) + when is_atom(module) and is_atom(function) and is_list(args), + do: {:ok, provider} + + defp provider(nil), do: invalid_configuration("identity_token_provider is required") + + defp provider(_other) do + invalid_configuration( + "identity_token_provider must be a zero-arity function or a {module, function, args} tuple" + ) + end + + defp invalid_configuration(description), + do: {:error, WorkloadIdentityError.new("invalid_configuration", description)} + + defp present(value) when is_binary(value) and value != "", do: value + defp present(_value), do: nil + + defp monotonic_ms, do: System.monotonic_time(:millisecond) + + # -- server ----------------------------------------------------------------- + # + # State: the cached token with its lifetime, expiry and generation, and the + # exchange in flight, if any. The generation starts at 0 with no token and + # goes up by one each time a token is stored. + # + # The token is held as a zero-arity function, in the state and in the + # exchange task's result. A function prints as `#Function<...>`, so the + # token cannot show up in a crash report, a stack trace, `:sys.get_state/1` + # or any other place the state or a message is inspected. + + @impl GenServer + def init(config) do + # The exchange task is linked so it stops with this process. Trapping + # exits keeps a task that dies from taking the cache down with it. + _ = Process.flag(:trap_exit, true) + + {:ok, + %{config: config, token: nil, lifetime_ms: 0, expires_at: 0, generation: 0, inflight: nil}} + end + + @impl GenServer + def handle_call(:resolve, from, state) do + if fresh?(state) do + {:reply, {:ok, snapshot(state)}, state} + else + state = join_or_start_exchange(state) + {:noreply, update_in(state.inflight.waiters, &[from | &1])} + end + end + + # An unknown request must not crash the process: the crash would take the + # cached token with it. + def handle_call(_request, _from, state), do: {:reply, {:error, :unknown_request}, state} + + @impl GenServer + def handle_cast({:invalidate, generation}, %{generation: generation} = state), + do: {:noreply, %{state | token: nil}} + + def handle_cast(_stale_generation_or_unknown, state), do: {:noreply, state} + + @impl GenServer + def handle_info({ref, result}, %{inflight: %{task: %Task{ref: ref}}} = state) do + _ = Process.demonitor(ref, [:flush]) + {:noreply, finish(state, result)} + end + + def handle_info( + {:DOWN, ref, :process, _pid, _reason}, + %{inflight: %{task: %Task{ref: ref}}} = state + ) do + {:noreply, finish(state, {:error, stopped("the token exchange stopped unexpectedly")})} + end + + def handle_info({:exchange_deadline, ref}, %{inflight: %{task: %Task{ref: ref} = task}} = state) do + result = + case Task.shutdown(task, :brutal_kill) do + {:ok, result} -> + result + + _killed -> + {:error, stopped("the token exchange did not finish within its deadline")} + end + + {:noreply, finish(state, result)} + end + + # Exit signals from finished tasks, and timers or monitors of an exchange + # that is already over. + def handle_info(_message, state), do: {:noreply, state} + + # -- cache ------------------------------------------------------------------ + + defp fresh?(%{token: nil}), do: false + + defp fresh?(state), + do: state.expires_at - now(state) >= refresh_threshold(state.lifetime_ms) + + defp refresh_threshold(lifetime_ms), + do: min(@refresh_threshold_ms, div(lifetime_ms, @refresh_lifetime_divisor)) + + defp now(%{config: %{clock: clock}}), do: clock.() + + defp snapshot(state) do + %CredentialSnapshot{ + headers: [ + {"authorization", "Bearer " <> state.token.()}, + {@environment_header, state.config.environment_id} + ], + generation: state.generation, + recoverable: true + } + end + + # -- shared exchange ---------------------------------------------------------- + + defp join_or_start_exchange(%{inflight: nil, config: config} = state) do + task = Task.async(fn -> config |> Exchange.run() |> seal() end) + timer = Process.send_after(self(), {:exchange_deadline, task.ref}, config.deadline_ms) + %{state | inflight: %{task: task, timer: timer, waiters: []}} + end + + defp join_or_start_exchange(state), do: state + + # The token is stored and the in-flight exchange cleared before any waiter + # is replied to, so a caller that gets an error and calls again starts a + # new exchange instead of joining the finished one. + defp finish(%{inflight: %{timer: timer, waiters: waiters}} = state, result) do + _ = Process.cancel_timer(timer) + {reply, state} = store(%{state | inflight: nil}, result) + Enum.each(waiters, &GenServer.reply(&1, reply)) + state + end + + defp seal({:ok, token, lifetime_ms}), do: {:ok, fn -> token end, lifetime_ms} + defp seal({:error, error}), do: {:error, error} + + defp store(state, {:ok, token, lifetime_ms}) when is_function(token, 0) do + state = %{ + state + | token: token, + lifetime_ms: lifetime_ms, + expires_at: now(state) + lifetime_ms, + generation: state.generation + 1 + } + + {{:ok, snapshot(state)}, state} + end + + defp store(state, {:error, %WorkloadIdentityError{} = error}), do: {{:error, error}, state} + + defp stopped(description), do: WorkloadIdentityError.new("exchange_failed", description) +end diff --git a/lib/workos/workload_identity/exchange.ex b/lib/workos/workload_identity/exchange.ex new file mode 100644 index 00000000..891e92a5 --- /dev/null +++ b/lib/workos/workload_identity/exchange.ex @@ -0,0 +1,235 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.Exchange do + @moduledoc false + + # One jwt-bearer token exchange: call the identity token provider, POST the + # form to the token endpoint, read the access token. Transport failures, + # 429, 5xx and provider failures are retried with the SDK's own retry count + # and backoff; the provider is called again and the form rebuilt for every + # attempt. An OAuth error on any other status is final. + # + # `run/1` never raises and never returns either token in an error. The + # caller (`WorkOS.WorkloadIdentity.Credentials`) bounds the whole run with + # its deadline. + + alias WorkOS.WorkloadIdentityError + + @grant_type "urn:ietf:params:oauth:grant-type:jwt-bearer" + @default_lifetime_seconds 300 + + # Fixed for the exchange POST, whatever other Req options are in effect: + # this module runs its own retry loop, a redirect is never followed, and no + # Authorization header is ever sent. `post/2` also removes the deprecated + # `:follow_redirects` option, which Req reads ahead of `:redirect`, and adds + # a last request step that removes any `authorization` header, so it does + # not matter which option or step put one there. + @fixed_options [retry: false, redirect: false, decode_body: false, auth: nil] + + @redacted "[REDACTED]" + + @type result :: + {:ok, access_token :: String.t(), lifetime_ms :: pos_integer()} + | {:error, WorkloadIdentityError.t()} + + @spec run(map()) :: result() + def run(config) do + attempt(config, 0) + rescue + exception -> {:error, unexpected(exception.__struct__)} + catch + kind, _value -> {:error, unexpected(kind)} + end + + defp attempt(config, retries) do + case exchange_once(config) do + {:retry, error, retry_after_ms} -> + if retries < WorkOS.Client.default_max_retries() do + config.sleep.(retry_after_ms || WorkOS.Client.retry_delay(retries)) + attempt(config, retries + 1) + else + {:error, error} + end + + result -> + result + end + end + + defp exchange_once(config) do + with {:ok, assertion} <- assertion(config.identity_token_provider), + {:ok, response} <- post(config, assertion) do + read(response, assertion) + end + end + + # -- identity token provider ------------------------------------------------ + + defp assertion(provider) do + case call(provider) do + {:ok, token} when is_binary(token) and token != "" -> + {:ok, token} + + {:ok, _empty} -> + provider_failed("the provider returned an empty token", :empty_token) + + {:error, reason} -> + provider_failed(describe(reason), reason) + + _other -> + provider_failed( + "the provider did not return {:ok, token} or {:error, reason}", + :invalid_return + ) + end + rescue + exception -> provider_failed(Exception.message(exception), exception) + catch + kind, _value -> provider_failed("the provider stopped with a #{kind}", kind) + end + + defp call(provider) when is_function(provider, 0), do: provider.() + defp call({module, function, args}), do: apply(module, function, args) + + defp provider_failed(description, reason), + do: {:retry, WorkloadIdentityError.new("provider_failed", description, reason), nil} + + # A provider's error is described only when it is already text. Other terms + # are kept in `:reason` and never interpolated. + defp describe(%{__exception__: true} = exception), do: Exception.message(exception) + defp describe(reason) when is_binary(reason), do: reason + defp describe(reason) when is_atom(reason), do: Atom.to_string(reason) + defp describe(_reason), do: "" + + # -- token endpoint --------------------------------------------------------- + + defp post(config, assertion) do + request = + [ + method: :post, + url: config.token_url, + form: form(config, assertion), + headers: [{"accept", "application/json"}, {"user-agent", WorkOS.Client.user_agent()}] + ] + |> Req.new() + |> Req.merge(config.req_options) + |> Req.merge(@fixed_options) + |> Req.Request.delete_option(:follow_redirects) + |> Req.Request.append_request_steps( + workos_no_authorization: &Req.Request.delete_header(&1, "authorization") + ) + + case Req.request(request) do + {:ok, response} -> + {:ok, response} + + {:error, exception} -> + {:retry, WorkloadIdentityError.new("exchange_failed", "", transport_reason(exception)), + nil} + end + end + + # There is no client secret: the assertion is the credential. + defp form(config, assertion) do + fields = [ + grant_type: @grant_type, + assertion: assertion, + client_id: config.client_id, + resource: config.resource + ] + + if config.scope, do: fields ++ [scope: config.scope], else: fields + end + + # The status is checked before the body: a 429 or 5xx is retried even when + # its body has an OAuth error. + defp read(%Req.Response{status: status} = response, assertion) + when status == 429 or status in 500..599 do + {code, description} = oauth_error(decode(response), assertion) || {"exchange_failed", ""} + {:retry, WorkloadIdentityError.new(code, description), retry_after(response)} + end + + defp read(%Req.Response{status: status} = response, assertion) do + body = decode(response) + oauth_error = oauth_error(body, assertion) + + cond do + oauth_error -> + {code, description} = oauth_error + {:error, WorkloadIdentityError.new(code, description)} + + status in 300..399 -> + {:error, + WorkloadIdentityError.new( + "exchange_failed", + "the token endpoint answered with a redirect (HTTP #{status}), which is not followed" + )} + + status == 200 -> + access_token(body) + + true -> + {:error, + WorkloadIdentityError.new( + "invalid_response", + "the token endpoint returned HTTP #{status}" + )} + end + end + + defp access_token(%{"access_token" => token} = body) when is_binary(token) and token != "", + do: {:ok, token, lifetime_ms(body["expires_in"])} + + defp access_token(_body), + do: + {:error, WorkloadIdentityError.new("invalid_response", "the response had no access_token")} + + defp lifetime_ms(seconds) when is_number(seconds) and seconds > 0, + do: max(trunc(seconds * 1000), 1) + + defp lifetime_ms(_absent_or_invalid), do: @default_lifetime_seconds * 1000 + + defp decode(%Req.Response{body: body}) when is_binary(body) do + case JSON.decode(body) do + {:ok, %{} = decoded} -> decoded + _other -> nil + end + end + + defp decode(_response), do: nil + + # The endpoint's own text goes into the error, so an endpoint that echoes + # the assertion back must not be able to put it there. + defp oauth_error(%{"error" => code} = body, assertion) when is_binary(code) and code != "", + do: {scrub(code, assertion), scrub(body["error_description"], assertion)} + + defp oauth_error(_body, _assertion), do: nil + + defp scrub(text, assertion) when is_binary(text), + do: String.replace(text, assertion, @redacted) + + defp scrub(_absent, _assertion), do: "" + + # `Retry-After` is honored on the statuses where Req honors it for API + # requests: 429 and 503. Req raises on a value that is neither seconds nor + # an HTTP date; such a header is ignored and the normal backoff applies. + defp retry_after(%Req.Response{status: status} = response) when status in [429, 503] do + Req.Response.get_retry_after(response) + rescue + _malformed -> nil + end + + defp retry_after(_response), do: nil + + # Req's own transport errors carry a reason atom and nothing from the + # request. Any other exception is reduced to its module name. + defp transport_reason(%Req.TransportError{} = exception), do: exception + defp transport_reason(%{__struct__: module}), do: module + + defp unexpected(what) do + WorkloadIdentityError.new( + "exchange_failed", + "the token exchange stopped unexpectedly (#{inspect(what)})" + ) + end +end diff --git a/lib/workos/workload_identity_error.ex b/lib/workos/workload_identity_error.ex new file mode 100644 index 00000000..cfc1818c --- /dev/null +++ b/lib/workos/workload_identity_error.ex @@ -0,0 +1,85 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentityError do + @moduledoc """ + A workload identity federation failure: the credentials are misconfigured, + the identity token provider failed, or the token exchange was rejected. + + * `:code` — the OAuth error code from the token endpoint (for example + `"invalid_grant"`), or one of the SDK's own codes: `"exchange_failed"`, + `"invalid_response"`, `"provider_failed"`, `"invalid_configuration"` + * `:description` — the token endpoint's `error_description`, cut to 500 + characters, or a short detail for an SDK code; `""` when there is none + * `:hint` — one sentence on what to check; never empty + * `:reason` — the underlying error when there is one (the provider's + error, or the transport exception), otherwise `nil` + + The message is `: `, followed by the description when there is + one. Neither the identity token nor the access token ever appears in it. + """ + + defexception [:code, :description, :hint, :reason] + + @type t :: %__MODULE__{ + code: String.t(), + description: String.t(), + hint: String.t(), + reason: term() + } + + @description_limit 500 + + # The one table of hints. The wording is pending the server's final error + # codes, so change it here and nowhere else. + @hints %{ + "invalid_grant" => + "The identity token did not match a trust rule for this application, or the token has " <> + "expired. Check the issuer, audience and subject claims against the trust rule.", + "invalid_target" => + "The resource or audience is wrong. The trust rule's audience must match the audience " <> + "the identity token was requested with, and the resource must be registered for the " <> + "environment.", + "invalid_client" => + "Check that the client ID is the M2M application that has the trust rule.", + "unauthorized_client" => + "This application is not allowed to use workload identity federation. Check that the " <> + "feature is enabled for the environment and that the application has a trust rule.", + "invalid_scope" => + "The requested scope is not allowed for this application. Fix the scope or leave it unset.", + "invalid_request" => + "The token request was malformed. Check that the token URL points at the " <> + "`/oauth2/token` endpoint.", + "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." + } + + @other_oauth_hint "The token endpoint rejected the exchange." + + @doc false + @spec new(String.t(), term(), term()) :: t() + def new(code, description \\ "", reason \\ nil) when is_binary(code) do + %__MODULE__{ + code: code, + description: describe(description), + hint: Map.get(@hints, code, @other_oauth_hint), + reason: reason + } + end + + @impl Exception + def message(%__MODULE__{code: code, hint: hint, description: ""}), do: "#{code}: #{hint}" + + def message(%__MODULE__{code: code, hint: hint, description: description}), + do: "#{code}: #{hint} #{description}" + + defp describe(description) when is_binary(description), + do: String.slice(description, 0, @description_limit) + + defp describe(_description), do: "" +end diff --git a/release-please-config.json b/release-please-config.json index 5877d92a..d48540c6 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,9 +1,34 @@ { + "separate-pull-requests": true, "packages": { ".": { "release-type": "elixir", "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true + }, + "workload_identity_github_actions": { + "release-type": "elixir", + "initial-version": "0.1.0", + "component": "workos_workload_identity_github_actions", + "package-name": "workos_workload_identity_github_actions", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" + }, + "workload_identity_gcp": { + "release-type": "elixir", + "initial-version": "0.1.0", + "component": "workos_workload_identity_gcp", + "package-name": "workos_workload_identity_gcp", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" + }, + "workload_identity_aws": { + "release-type": "elixir", + "initial-version": "0.1.0", + "component": "workos_workload_identity_aws", + "package-name": "workos_workload_identity_aws", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" } }, "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" diff --git a/script/ci b/script/ci index 1850a606..a90f9149 100755 --- a/script/ci +++ b/script/ci @@ -27,4 +27,29 @@ mix dialyzer echo "==> Running tests..." mix test +# Each workload identity provider package is its own Mix project with its own +# release, so each has to pass on its own. Dialyzer is not run on them: they +# are one small module each and carry no dialyxir dependency. +for package in workload_identity_*/; do + package="${package%/}" + ( + cd "$package" + + echo "==> ${package}: fetching dependencies..." + mix deps.get + + echo "==> ${package}: compiling (warnings as errors)..." + mix compile --warnings-as-errors + + echo "==> ${package}: checking formatting..." + mix format --check-formatted + + echo "==> ${package}: credo (lint)..." + mix credo --strict -a + + echo "==> ${package}: running tests..." + mix test + ) +done + echo "==> All checks passed." diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs new file mode 100644 index 00000000..d27f42c1 --- /dev/null +++ b/test/workos/workload_identity_test.exs @@ -0,0 +1,1147 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentityTest do + # Conformance cases WIF-01 to WIF-24 for workload identity federation, plus + # the edge cases around them. Several cases set process-wide environment + # variables, so the module is not async. No test touches the network: the + # token endpoint and the API are function plugs. + use ExUnit.Case, async: false + + import ExUnit.CaptureLog + + alias WorkOS.WorkloadIdentity + alias WorkOS.WorkloadIdentity.Credentials + alias WorkOS.WorkloadIdentityError + + @moduletag :wif + + @client_id "client_wif_test" + @environment_id "environment_wif_test" + @token_url "https://auth.wif.test/oauth2/token" + + @env_vars ~w(WORKOS_API_KEY WORKOS_CLIENT_ID WORKOS_WIF_TOKEN_URL WORKOS_WIF_SCOPE + WORKOS_ENVIRONMENT_ID MY_JWT) + + setup do + previous = Map.new(@env_vars, &{&1, System.get_env(&1)}) + + on_exit(fn -> + Enum.each(previous, fn + {name, nil} -> System.delete_env(name) + {name, value} -> System.put_env(name, value) + end) + end) + + Enum.each(@env_vars, &System.delete_env/1) + :ok + end + + # -- mocks ------------------------------------------------------------------ + # + # A mock is a script of steps and a record of the requests it received. + # Each request takes the next step; once the script runs out, the default + # step repeats. "Exchange count" is `length(requests(token_endpoint))`. + + defp mock(default, script) do + {:ok, agent} = + Agent.start_link(fn -> %{script: script, default: default, requests: [], issued: 0} end) + + agent + end + + defp token_endpoint(script \\ []), do: mock(:issue, script) + defp api(script \\ []), do: mock(:ok, script) + + defp requests(mock), do: Agent.get(mock, & &1.requests) + + defp next_step(mock, request) do + Agent.get_and_update(mock, fn state -> + {step, script} = + case state.script do + [step | rest] -> {step, rest} + [] -> {state.default, []} + end + + {step, %{state | script: script, requests: state.requests ++ [request]}} + end) + end + + defp next_access_token(mock) do + Agent.get_and_update(mock, fn state -> + {"access-#{state.issued + 1}", %{state | issued: state.issued + 1}} + end) + end + + defp header(conn, name), do: conn |> Plug.Conn.get_req_header(name) |> List.first() + + # Token endpoint steps: + # :issue | {:issue, expires_in: seconds | :absent, access_token: token} + # {:oauth_error, code, description} + # {:status, status, headers, body} + # {:transport_error, reason} + # {:hold, step} tells the test it is holding, then waits for :release + defp token_plug(mock) do + test = self() + + fn conn -> + step = + next_step(mock, %{ + method: conn.method, + host: conn.host, + path: conn.request_path, + form: conn.body_params, + content_type: header(conn, "content-type"), + authorization: header(conn, "authorization") + }) + + answer_token(conn, step, mock, test) + end + end + + defp answer_token(conn, {:hold, step}, mock, test) do + send(test, {:holding, self()}) + + receive do + :release -> answer_token(conn, step, mock, test) + after + 10_000 -> raise "the held token response was never released" + end + end + + defp answer_token(conn, :issue, mock, test), do: answer_token(conn, {:issue, []}, mock, test) + + defp answer_token(conn, {:issue, opts}, mock, _test) do + body = %{ + "access_token" => opts[:access_token] || next_access_token(mock), + "token_type" => "Bearer" + } + + body = + case Keyword.get(opts, :expires_in, 300) do + :absent -> body + expires_in -> Map.put(body, "expires_in", expires_in) + end + + Req.Test.json(conn, body) + end + + defp answer_token(conn, {:oauth_error, code, description}, _mock, _test) do + conn + |> Plug.Conn.put_status(400) + |> Req.Test.json(%{"error" => code, "error_description" => description}) + end + + defp answer_token(conn, {:status, status, headers, body}, _mock, _test), + do: conn |> put_resp_headers(headers) |> Plug.Conn.send_resp(status, body) + + defp answer_token(conn, {:transport_error, reason}, _mock, _test), + do: Req.Test.transport_error(conn, reason) + + # API steps: :ok | {:status, status} | {:status, status, headers} + defp api_plug(mock) do + fn conn -> + step = + next_step(mock, %{ + method: conn.method, + host: conn.host, + path: conn.request_path, + authorization: header(conn, "authorization"), + environment_id: header(conn, "x-url-environment-id"), + idempotency_key: header(conn, "idempotency-key"), + body: Req.Test.raw_body(conn) + }) + + answer_api(conn, step) + end + end + + defp answer_api(conn, :ok), do: Req.Test.json(conn, %{"ok" => true}) + defp answer_api(conn, {:status, status}), do: answer_api(conn, {:status, status, []}) + + defp answer_api(conn, {:status, status, headers}) do + conn + |> put_resp_headers(headers) + |> Plug.Conn.put_status(status) + |> Req.Test.json(%{"message" => "HTTP #{status}"}) + end + + defp put_resp_headers(conn, headers) do + Enum.reduce(headers, conn, fn {name, value}, conn -> + Plug.Conn.put_resp_header(conn, name, value) + end) + end + + # -- builders --------------------------------------------------------------- + + defp credentials_options(token_endpoint, opts) do + Keyword.merge( + [ + client_id: @client_id, + environment_id: @environment_id, + token_url: @token_url, + identity_token_provider: fn -> {:ok, "assertion-1"} end, + req_options: [plug: token_plug(token_endpoint)], + # A zero-delay sleeper, so retried exchanges do not slow the suite. + sleep: fn _ms -> :ok end + ], + opts + ) + end + + defp start_credentials(token_endpoint, opts \\ []) do + {:ok, credentials} = Credentials.start_link(credentials_options(token_endpoint, opts)) + credentials + end + + defp client(credentials, api, opts \\ []) do + WorkOS.Client.new([credentials: credentials, req_options: [plug: api_plug(api)]] ++ opts) + end + + defp get(client, opts \\ []), do: WorkOS.Client.request(client, :get, "/wif-check", %{}, opts) + + # An injected clock, in milliseconds. + defp clock do + ref = :atomics.new(1, signed: true) + {fn -> :atomics.get(ref, 1) end, fn seconds -> :atomics.put(ref, 1, seconds * 1000) end} + end + + # A provider that tells the test each time it is invoked. "Provider count" + # is `provider_count()`. + defp counted_provider(assertion \\ "assertion-1") do + test = self() + + fn -> + send(test, :provider_invoked) + {:ok, assertion} + end + end + + defp provider_count do + receive do + :provider_invoked -> 1 + provider_count() + after + 0 -> 0 + end + end + + defp wait_for_waiters(credentials, count, tries \\ 2_000) + + defp wait_for_waiters(_credentials, count, 0), + do: flunk("#{count} callers never ended up waiting on the exchange") + + defp wait_for_waiters(credentials, count, tries) do + case :sys.get_state(credentials) do + %{inflight: %{waiters: waiters}} when length(waiters) == count -> + :ok + + _state -> + Process.sleep(2) + wait_for_waiters(credentials, count, tries - 1) + end + end + + # -- exchange request and API request ---------------------------------------- + + test "WIF-01 the first request triggers one exchange POST with the right shape" do + token_endpoint = token_endpoint() + assert {:ok, _} = token_endpoint |> start_credentials() |> client(api()) |> get() + + assert [exchange] = requests(token_endpoint) + assert exchange.method == "POST" + assert exchange.host == "auth.wif.test" + assert exchange.path == "/oauth2/token" + assert exchange.content_type == "application/x-www-form-urlencoded" + assert exchange.authorization == nil + + # Exactly these fields: no scope and no client_secret. + assert exchange.form == %{ + "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion" => "assertion-1", + "client_id" => "client_wif_test", + "resource" => "https://api.workos.com" + } + + scoped = token_endpoint() + + assert {:ok, _} = + scoped |> start_credentials(scope: "organizations:write") |> client(api()) |> get() + + assert [exchange] = requests(scoped) + assert exchange.form["scope"] == "organizations:write" + refute Map.has_key?(exchange.form, "client_secret") + assert exchange.authorization == nil + end + + test "WIF-02 the API request carries the access token and the environment header" do + api = api() + assert {:ok, _} = token_endpoint() |> start_credentials() |> client(api) |> get() + + assert [request] = requests(api) + assert request.authorization == "Bearer access-1" + assert request.environment_id == "environment_wif_test" + end + + # -- cache and refresh -------------------------------------------------------- + + test "WIF-03 a second request within the token lifetime reuses the cached token" do + token_endpoint = token_endpoint() + api = api() + client = token_endpoint |> start_credentials() |> client(api) + + assert {:ok, _} = get(client) + assert {:ok, _} = get(client) + + assert length(requests(token_endpoint)) == 1 + assert Enum.map(requests(api), & &1.authorization) == ["Bearer access-1", "Bearer access-1"] + end + + test "WIF-04 with expires_in 300 the token is refreshed when less than 60 seconds remain" do + {now, set_seconds} = clock() + token_endpoint = token_endpoint() + api = api() + client = token_endpoint |> start_credentials(clock: now) |> client(api) + + assert {:ok, _} = get(client) + + set_seconds.(239) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 1 + + set_seconds.(241) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 2 + + assert Enum.map(requests(api), & &1.authorization) == + ["Bearer access-1", "Bearer access-1", "Bearer access-2"] + end + + test "WIF-05 with expires_in 100 the refresh threshold is 20 seconds, not 60" do + {now, set_seconds} = clock() + token_endpoint = token_endpoint([{:issue, expires_in: 100}]) + client = token_endpoint |> start_credentials(clock: now) |> client(api()) + + assert {:ok, _} = get(client) + + set_seconds.(79) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 1 + + set_seconds.(81) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 2 + end + + test "WIF-06 a response with no expires_in is treated as 300 seconds" do + {now, set_seconds} = clock() + token_endpoint = token_endpoint([{:issue, expires_in: :absent}]) + client = token_endpoint |> start_credentials(clock: now) |> client(api()) + + assert {:ok, _} = get(client) + + set_seconds.(239) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 1 + + set_seconds.(241) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 2 + end + + test "WIF-06 an expires_in that is not a positive number is treated as 300 seconds" do + for expires_in <- [0, -5, "300", nil] do + {now, set_seconds} = clock() + token_endpoint = token_endpoint([{:issue, expires_in: expires_in}]) + client = token_endpoint |> start_credentials(clock: now) |> client(api()) + + assert {:ok, _} = get(client) + + set_seconds.(239) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 1 + + set_seconds.(241) + assert {:ok, _} = get(client) + assert length(requests(token_endpoint)) == 2 + end + end + + test "WIF-07 two credentials instances never share a cached token" do + token_endpoint = token_endpoint() + first_api = api() + second_api = api() + + # Identical configuration, one token endpoint, two processes. + first = token_endpoint |> start_credentials() |> client(first_api) + second = token_endpoint |> start_credentials() |> client(second_api) + + assert {:ok, _} = get(first) + assert {:ok, _} = get(second) + + assert length(requests(token_endpoint)) == 2 + assert [%{authorization: "Bearer access-1"}] = requests(first_api) + assert [%{authorization: "Bearer access-2"}] = requests(second_api) + end + + # -- shared exchange ---------------------------------------------------------- + + test "WIF-08 twenty concurrent first requests on one instance produce exactly one exchange" do + token_endpoint = token_endpoint([{:hold, :issue}]) + api = api() + credentials = start_credentials(token_endpoint, identity_token_provider: counted_provider()) + client = client(credentials, api) + + tasks = for _ <- 1..20, do: Task.async(fn -> get(client) end) + + # The token endpoint holds its response until all twenty are waiting. + assert_receive {:holding, exchange}, 5_000 + wait_for_waiters(credentials, 20) + send(exchange, :release) + + results = Task.await_many(tasks, 5_000) + assert Enum.all?(results, &match?({:ok, _}, &1)) + + assert length(requests(token_endpoint)) == 1 + assert provider_count() == 1 + + api_requests = requests(api) + assert length(api_requests) == 20 + assert Enum.all?(api_requests, &(&1.authorization == "Bearer access-1")) + end + + test "WIF-23 a caller that times out does not cancel the shared exchange for the others" do + token_endpoint = token_endpoint([{:hold, :issue}]) + api = api() + credentials = start_credentials(token_endpoint) + client = client(credentials, api) + + # A gives up after 50 ms. B waits. + caller_a = Task.async(fn -> get(client, timeout: 50) end) + caller_b = Task.async(fn -> get(client) end) + + assert_receive {:holding, exchange}, 5_000 + wait_for_waiters(credentials, 2) + + assert {:error, %WorkOS.TransportError{reason: :timeout}} = Task.await(caller_a, 5_000) + + send(exchange, :release) + + assert {:ok, _} = Task.await(caller_b, 5_000) + assert length(requests(token_endpoint)) == 1 + assert [%{authorization: "Bearer access-1"}] = requests(api) + end + + test "an exchange task that dies fails every waiter and is not left in flight" do + token_endpoint = token_endpoint([{:hold, :issue}]) + credentials = start_credentials(token_endpoint) + + waiter = Task.async(fn -> Credentials.resolve(credentials, 5_000) end) + + # The held response is being served by the exchange task itself. + assert_receive {:holding, exchange}, 5_000 + wait_for_waiters(credentials, 1) + Process.exit(exchange, :kill) + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"}} = Task.await(waiter, 5_000) + assert Process.alive?(credentials) + + # The next call starts a new exchange, which succeeds. + assert {:ok, snapshot} = Credentials.resolve(credentials, 5_000) + assert {"authorization", "Bearer access-1"} in snapshot.headers + assert length(requests(token_endpoint)) == 2 + end + + test "an exchange that outlives its deadline fails every waiter and is not left in flight" do + token_endpoint = token_endpoint([{:hold, :issue}]) + credentials = start_credentials(token_endpoint, deadline_ms: 50) + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"}} = + Credentials.resolve(credentials, 5_000) + + # The next call starts a new exchange, which succeeds. + assert {:ok, snapshot} = Credentials.resolve(credentials, 5_000) + assert {"authorization", "Bearer access-1"} in snapshot.headers + assert length(requests(token_endpoint)) == 2 + end + + # -- 401 recovery ------------------------------------------------------------- + + test "WIF-09 a 401 invalidates that token generation, exchanges again and retries once" do + token_endpoint = token_endpoint() + api = api([{:status, 401}]) + + assert {:ok, _} = token_endpoint |> start_credentials() |> client(api) |> get() + + assert length(requests(token_endpoint)) == 2 + assert Enum.map(requests(api), & &1.authorization) == ["Bearer access-1", "Bearer access-2"] + end + + test "WIF-10 a second 401 after recovery is returned to the caller" do + token_endpoint = token_endpoint() + api = mock({:status, 401}, []) + + assert {:error, %WorkOS.ApiError{status: 401, kind: :authentication}} = + token_endpoint |> start_credentials() |> client(api) |> get() + + assert length(requests(token_endpoint)) == 2 + assert length(requests(api)) == 2 + end + + test "WIF-11 a late 401 for an old generation does not discard a newer token" do + token_endpoint = token_endpoint() + api = api() + credentials = start_credentials(token_endpoint) + + assert {:ok, %{generation: 1} = first} = Credentials.resolve(credentials, 5_000) + assert {"authorization", "Bearer access-1"} in first.headers + + assert :ok = Credentials.invalidate(credentials, 1) + assert {:ok, %{generation: 2} = second} = Credentials.resolve(credentials, 5_000) + assert {"authorization", "Bearer access-2"} in second.headers + + # A late 401 for generation 1 arrives after generation 2 is cached. + assert :ok = Credentials.invalidate(credentials, 1) + + assert {:ok, _} = credentials |> client(api) |> get() + + assert :sys.get_state(credentials).generation == 2 + assert length(requests(token_endpoint)) == 2 + assert [%{authorization: "Bearer access-2"}] = requests(api) + end + + test "WIF-12 transport retries inside one request do not reset the single 401 recovery" do + token_endpoint = token_endpoint() + # 401, then 503, then 401. A fourth attempt would get a 200. + api = api([{:status, 401}, {:status, 503, [{"retry-after", "0"}]}, {:status, 401}]) + client = token_endpoint |> start_credentials() |> client(api) + + capture_log(fn -> + assert {:error, %WorkOS.ApiError{status: 401}} = get(client) + end) + + assert length(requests(token_endpoint)) == 2 + assert length(requests(api)) == 3 + end + + test "WIF-13 the 401 retry sends the same request body and the same idempotency key" do + api = api([{:status, 401}]) + client = token_endpoint() |> start_credentials() |> client(api) + + # No explicit key: the SDK generates one for a POST. + assert {:ok, _} = + WorkOS.Client.request(client, :post, "/wif-check", %{name: "Acme", tags: ["a", "b"]}) + + assert [first, second] = requests(api) + assert first.body == second.body + assert first.body != "" + assert is_binary(first.idempotency_key) and first.idempotency_key != "" + assert first.idempotency_key == second.idempotency_key + assert [first.authorization, second.authorization] == ["Bearer access-1", "Bearer access-2"] + end + + test "credentials are resolved again before a transport retry, so a retry never sends an expired token" do + {now, set_seconds} = clock() + token_endpoint = token_endpoint() + api = api([{:status, 503, [{"retry-after", "0"}]}]) + credentials = start_credentials(token_endpoint, clock: now) + + # The token passes its refresh threshold while the first attempt is in + # flight. The API answers that attempt with a 503. + plug = fn conn -> + if requests(api) == [], do: set_seconds.(241) + api_plug(api).(conn) + end + + client = WorkOS.Client.new(credentials: credentials, req_options: [plug: plug]) + + capture_log(fn -> + assert {:ok, _} = get(client) + end) + + assert Enum.map(requests(api), & &1.authorization) == ["Bearer access-1", "Bearer access-2"] + assert length(requests(token_endpoint)) == 2 + end + + test "WIF-24 static API-key clients are unchanged" do + token_endpoint = token_endpoint() + api = api([:ok, {:status, 401}]) + client = WorkOS.Client.new(api_key: "sk_test_static", req_options: [plug: api_plug(api)]) + + assert {:ok, _} = get(client) + assert [request] = requests(api) + assert request.authorization == "Bearer sk_test_static" + assert request.environment_id == nil + + # A 401 is returned after exactly one attempt. + assert {:error, %WorkOS.ApiError{status: 401}} = get(client) + assert length(requests(api)) == 2 + + assert requests(token_endpoint) == [] + end + + # -- exchange retries and errors ------------------------------------------------ + + test "WIF-14 the exchange is retried on 503 and 429, calling the provider again each time" do + token_endpoint = + token_endpoint([ + {:status, 503, [], ""}, + {:status, 429, [{"retry-after", "0"}], ""} + ]) + + credentials = start_credentials(token_endpoint, identity_token_provider: counted_provider()) + + assert {:ok, _} = credentials |> client(api()) |> get() + assert length(requests(token_endpoint)) == 3 + assert provider_count() == 3 + end + + test "WIF-14 the exchange is retried when the connection fails" do + token_endpoint = token_endpoint([{:transport_error, :econnrefused}]) + credentials = start_credentials(token_endpoint, identity_token_provider: counted_provider()) + + assert {:ok, _} = credentials |> client(api()) |> get() + assert provider_count() == 2 + end + + test "WIF-14 the exchange is retried when the provider raises" do + test = self() + calls = :counters.new(1, []) + + provider = fn -> + send(test, :provider_invoked) + :counters.add(calls, 1, 1) + + if :counters.get(calls, 1) == 1 do + raise "the provider is not ready" + else + {:ok, "assertion-2"} + end + end + + token_endpoint = token_endpoint() + credentials = start_credentials(token_endpoint, identity_token_provider: provider) + + assert {:ok, _} = credentials |> client(api()) |> get() + assert provider_count() == 2 + assert [%{form: %{"assertion" => "assertion-2"}}] = requests(token_endpoint) + end + + test "WIF-14 the exchange waits at least as long as Retry-After says" do + test = self() + token_endpoint = token_endpoint([{:status, 429, [{"retry-after", "1"}], ""}]) + + credentials = + start_credentials(token_endpoint, sleep: fn ms -> send(test, {:slept, ms}) end) + + assert {:ok, _} = credentials |> client(api()) |> get() + + assert_received {:slept, ms} + assert ms >= 1_000 + assert length(requests(token_endpoint)) == 2 + end + + test "WIF-14 a 5xx is retried even when its body has an OAuth error, then surfaces that code" do + body = JSON.encode!(%{"error" => "temporarily_unavailable", "error_description" => "busy"}) + token_endpoint = mock({:status, 503, [{"retry-after", "0"}], body}, []) + client = token_endpoint |> start_credentials() |> client(api()) + + assert {:error, %WorkloadIdentityError{code: "temporarily_unavailable", description: "busy"}} = + get(client) + + assert length(requests(token_endpoint)) == WorkOS.Client.default_max_retries() + 1 + end + + test "WIF-15 an OAuth error is not retried and surfaces as a typed error carrying the code" do + for code <- ~w(invalid_grant invalid_target invalid_client unauthorized_client invalid_scope + invalid_request) do + description = "The server says #{code}." + token_endpoint = token_endpoint([{:oauth_error, code, description}]) + api = api() + + assert {:error, %WorkloadIdentityError{} = error} = + token_endpoint |> start_credentials() |> client(api) |> get() + + assert error.code == code + assert error.description == description + assert is_binary(error.hint) and error.hint != "" + assert Exception.message(error) == "#{code}: #{error.hint} #{description}" + + assert length(requests(token_endpoint)) == 1 + assert requests(api) == [] + end + end + + test "WIF-15 an unknown OAuth code still gets a hint, and a long description is cut to 500" do + token_endpoint = + token_endpoint([{:oauth_error, "something_new", String.duplicate("x", 600)}]) + + assert {:error, %WorkloadIdentityError{code: "something_new"} = error} = + token_endpoint |> start_credentials() |> client(api()) |> get() + + assert error.hint == "The token endpoint rejected the exchange." + assert String.length(error.description) == 500 + end + + test "WIF-16 after a failed exchange, the next request attempts a fresh exchange" do + token_endpoint = token_endpoint([{:oauth_error, "invalid_grant", "No trust rule matched."}]) + api = api() + client = token_endpoint |> start_credentials() |> client(api) + + assert {:error, %WorkloadIdentityError{code: "invalid_grant"}} = get(client) + assert {:ok, _} = get(client) + + assert length(requests(token_endpoint)) == 2 + assert [%{authorization: "Bearer access-1"}] = requests(api) + end + + test "WIF-17 neither the assertion nor the access token appears in any error or log line" do + assertion = "SECRET-ASSERTION-VALUE" + access_token = "SECRET-ACCESS-VALUE" + provider = fn -> {:ok, assertion} end + issue = {:issue, access_token: access_token} + + scenarios = [ + # An invalid_grant exchange. + fn -> + token_endpoint([{:oauth_error, "invalid_grant", "No trust rule matched."}]) + |> start_credentials(identity_token_provider: provider) + |> client(api()) + |> get() + end, + # A 500 from the token endpoint until retries run out. + fn -> + mock({:status, 500, [], "internal error"}, []) + |> start_credentials(identity_token_provider: provider) + |> client(api()) + |> get() + end, + # A provider that raises. + fn -> + mock(issue, []) + |> start_credentials(identity_token_provider: fn -> raise "the provider exploded" end) + |> client(api()) + |> get() + end, + # A second 401 from the API. + fn -> + mock(issue, []) + |> start_credentials(identity_token_provider: provider) + |> client(mock({:status, 401}, [])) + |> get() + end + ] + + {errors, log} = + with_log([level: :debug], fn -> + Enum.map(scenarios, fn scenario -> + assert {:error, error} = scenario.() + error + end) + end) + + assert [ + %WorkloadIdentityError{code: "invalid_grant"}, + %WorkloadIdentityError{code: "exchange_failed"}, + %WorkloadIdentityError{code: "provider_failed"}, + %WorkOS.ApiError{status: 401} + ] = errors + + for text <- [log | Enum.flat_map(errors, &[Exception.message(&1), inspect(&1)])], + secret <- [assertion, access_token] do + refute text =~ secret + end + end + + test "WIF-17 the access token is left out of snapshots and of the process status" do + credentials = + mock({:issue, access_token: "SECRET-ACCESS-VALUE"}, []) |> start_credentials() + + assert {:ok, snapshot} = Credentials.resolve(credentials, 5_000) + assert {"authorization", "Bearer SECRET-ACCESS-VALUE"} in snapshot.headers + + refute inspect(snapshot) =~ "SECRET-ACCESS-VALUE" + refute inspect(:sys.get_status(credentials), limit: :infinity) =~ "SECRET-ACCESS-VALUE" + refute inspect(:sys.get_state(credentials), limit: :infinity) =~ "SECRET-ACCESS-VALUE" + end + + test "WIF-17 an unknown call, cast or message neither stops the process nor exposes the token" do + credentials = + mock({:issue, access_token: "SECRET-ACCESS-VALUE"}, []) |> start_credentials() + + assert {:ok, _snapshot} = Credentials.resolve(credentials, 5_000) + + log = + capture_log([level: :debug], fn -> + assert GenServer.call(credentials, :not_a_request) == {:error, :unknown_request} + assert :ok = GenServer.cast(credentials, :not_a_request) + send(credentials, :not_a_request) + + # Still serving, from the same cached token. + assert {:ok, %{generation: 1}} = Credentials.resolve(credentials, 5_000) + end) + + assert Process.alive?(credentials) + refute log =~ "SECRET-ACCESS-VALUE" + end + + test "WIF-17 an assertion echoed back by the token endpoint is removed from the error" do + token_endpoint = + token_endpoint([ + {:oauth_error, "invalid_grant", "Rejected assertion SECRET-ASSERTION-VALUE."} + ]) + + assert {:error, %WorkloadIdentityError{code: "invalid_grant"} = error} = + token_endpoint + |> start_credentials( + identity_token_provider: fn -> {:ok, "SECRET-ASSERTION-VALUE"} end + ) + |> client(api()) + |> get() + + assert error.description == "Rejected assertion [REDACTED]." + refute Exception.message(error) =~ "SECRET-ASSERTION-VALUE" + refute inspect(error) =~ "SECRET-ASSERTION-VALUE" + end + + test "WIF-18 the exchange request does not follow redirects" do + elsewhere = token_endpoint() + + token_endpoint = + token_endpoint([ + {:status, 307, [{"location", "https://elsewhere.wif.test/oauth2/token"}], ""} + ]) + + # One plug serves both hosts, so a followed redirect would be recorded. + plug = fn conn -> + if conn.host == "elsewhere.wif.test", + do: token_plug(elsewhere).(conn), + else: token_plug(token_endpoint).(conn) + end + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"}} = + token_endpoint + |> start_credentials(req_options: [plug: plug]) + |> client(api()) + |> get() + + assert [%{method: "POST", host: "auth.wif.test"}] = requests(token_endpoint) + assert requests(elsewhere) == [] + end + + test "WIF-18 no Req option makes the exchange follow a redirect or send an Authorization header" do + elsewhere = token_endpoint() + + token_endpoint = + token_endpoint([ + {:status, 307, [{"location", "https://elsewhere.wif.test/oauth2/token"}], ""} + ]) + + plug = fn conn -> + if conn.host == "elsewhere.wif.test", + do: token_plug(elsewhere).(conn), + else: token_plug(token_endpoint).(conn) + end + + req_options = [ + plug: plug, + redirect: true, + follow_redirects: true, + auth: {:bearer, "sk_must_not_be_sent"}, + headers: [{"authorization", "Bearer sk_must_not_be_sent"}], + # Req signs the request, and adds the header, only when it is sent. + aws_sigv4: [access_key_id: "AKIDEXAMPLE", secret_access_key: "secret", service: :sts] + ] + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"}} = + token_endpoint + |> start_credentials(req_options: req_options) + |> client(api()) + |> get() + + assert [%{method: "POST", authorization: nil}] = requests(token_endpoint) + assert requests(elsewhere) == [] + end + + test "WIF-14 a Retry-After the SDK cannot read falls back to the normal backoff" do + test = self() + token_endpoint = token_endpoint([{:status, 429, [{"retry-after", "soon"}], ""}]) + + credentials = + start_credentials(token_endpoint, sleep: fn ms -> send(test, {:slept, ms}) end) + + assert {:ok, _} = credentials |> client(api()) |> get() + + assert_received {:slept, ms} + assert ms > 0 + assert length(requests(token_endpoint)) == 2 + end + + test "a 200 that is not JSON, or has no access token, is an invalid_response error" do + for response <- [ + {:status, 200, [], "not json"}, + {:status, 200, [], JSON.encode!(%{"token_type" => "Bearer"})}, + {:status, 200, [], JSON.encode!(%{"access_token" => ""})}, + {:status, 404, [], "not found"} + ] do + token_endpoint = token_endpoint([response]) + + assert {:error, %WorkloadIdentityError{code: "invalid_response"}} = + token_endpoint |> start_credentials() |> client(api()) |> get() + + assert length(requests(token_endpoint)) == 1 + end + end + + # -- authentication precedence --------------------------------------------------- + + test "WIF-19 passing both an API key and credentials is a configuration error" do + token_endpoint = token_endpoint() + api = api() + credentials = start_credentials(token_endpoint) + + assert_raise WorkOS.ConfigurationError, ~r/not both/, fn -> + WorkOS.Client.new( + api_key: "sk_test_explicit", + credentials: credentials, + req_options: [plug: api_plug(api)] + ) + end + + # No HTTP request was sent. + assert requests(token_endpoint) == [] + assert requests(api) == [] + end + + test "WIF-20 explicit credentials win over WORKOS_API_KEY, and a failing configuration never falls back to it" do + System.put_env("WORKOS_API_KEY", "sk_test_env") + api = api() + + # (a) Valid credentials. + client = token_endpoint() |> start_credentials() |> client(api) + assert client.api_key == nil + assert {:ok, _} = get(client) + + # (b) No token URL, explicitly or in the environment. + options = token_endpoint() |> credentials_options([]) |> Keyword.delete(:token_url) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = + Credentials.start_link(options) + + assert error.description == "token_url is required (or set WORKOS_WIF_TOKEN_URL)" + + # (c) Valid credentials whose exchange fails. + failing = token_endpoint([{:oauth_error, "invalid_client", "Unknown client."}]) + + assert {:error, %WorkloadIdentityError{code: "invalid_client"}} = + failing |> start_credentials() |> client(api) |> get() + + # The API saw one request, from (a), and never the environment key. + assert [%{authorization: "Bearer access-1"}] = requests(api) + end + + test "WIF-20 every required option is checked when the credentials are constructed" do + for {key, variable} <- [ + client_id: "WORKOS_CLIENT_ID", + token_url: "WORKOS_WIF_TOKEN_URL", + environment_id: "WORKOS_ENVIRONMENT_ID" + ] do + options = token_endpoint() |> credentials_options([]) |> Keyword.delete(key) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = + Credentials.start_link(options) + + assert error.description == "#{key} is required (or set #{variable})" + assert Exception.message(error) =~ "missing a required setting" + end + + options = + token_endpoint() |> credentials_options([]) |> Keyword.delete(:identity_token_provider) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"}} = + Credentials.start_link(options) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"}} = + Credentials.start_link(Keyword.put(options, :identity_token_provider, "a string")) + end + + test "the credentials option must name a process" do + assert_raise WorkOS.ConfigurationError, ~r/credentials/, fn -> + WorkOS.Client.new(credentials: "not a process") + end + end + + test "a credentials process that is not running is an error, not a crash" do + credentials = start_credentials(token_endpoint()) + client = client(credentials, api()) + :ok = GenServer.stop(credentials) + + assert {:error, %WorkOS.TransportError{reason: :credentials_unavailable}} = get(client) + end + + test "credentials can be registered under a name and found by it" do + name = :"wif_credentials_#{System.unique_integer([:positive])}" + api = api() + + assert {:ok, _pid} = + token_endpoint() |> credentials_options(name: name) |> Credentials.start_link() + + assert {:ok, _} = name |> client(api) |> get() + assert [%{authorization: "Bearer access-1"}] = requests(api) + end + + # -- custom providers ------------------------------------------------------------- + + @tag :tmp_dir + test "WIF-21 token_file re-reads the file on every exchange", %{tmp_dir: tmp_dir} do + {now, set_seconds} = clock() + path = Path.join(tmp_dir, "identity-token") + File.write!(path, "assertion-1\n") + + token_endpoint = token_endpoint() + + client = + token_endpoint + |> start_credentials(identity_token_provider: WorkloadIdentity.token_file(path), clock: now) + |> client(api()) + + assert {:ok, _} = get(client) + + # Rotate the file, then move the clock past the refresh threshold. + File.write!(path, " assertion-2\n\n") + set_seconds.(241) + assert {:ok, _} = get(client) + + assert Enum.map(requests(token_endpoint), & &1.form["assertion"]) == + ["assertion-1", "assertion-2"] + end + + @tag :tmp_dir + test "WIF-21 a missing or empty token file is a provider error", %{tmp_dir: tmp_dir} do + empty = Path.join(tmp_dir, "empty") + File.write!(empty, " \n") + + for path <- [empty, Path.join(tmp_dir, "missing")] do + token_endpoint = token_endpoint() + + assert {:error, %WorkloadIdentityError{code: "provider_failed"} = error} = + token_endpoint + |> start_credentials(identity_token_provider: WorkloadIdentity.token_file(path)) + |> client(api()) + |> get() + + assert error.description =~ path + assert requests(token_endpoint) == [] + end + end + + test "WIF-22 token_env and callback providers supply the assertion" do + # (a) token_env + System.put_env("MY_JWT", "assertion-env") + from_env = token_endpoint() + + assert {:ok, _} = + from_env + |> start_credentials(identity_token_provider: WorkloadIdentity.token_env("MY_JWT")) + |> client(api()) + |> get() + + assert [%{form: %{"assertion" => "assertion-env"}}] = requests(from_env) + + # (b) a callback, as a function and as a {module, function, args} tuple + for provider <- [fn -> {:ok, "assertion-cb"} end, {__MODULE__, :callback_provider, ["cb"]}] do + from_callback = token_endpoint() + + assert {:ok, _} = + from_callback + |> start_credentials(identity_token_provider: provider) + |> client(api()) + |> get() + + assert [%{form: %{"assertion" => "assertion-cb"}}] = requests(from_callback) + end + end + + @doc false + def callback_provider(suffix), do: {:ok, "assertion-" <> suffix} + + test "WIF-22 an unset or empty token_env variable is a provider error" do + for value <- [nil, ""] do + if value, do: System.put_env("MY_JWT", value), else: System.delete_env("MY_JWT") + token_endpoint = token_endpoint() + + assert {:error, %WorkloadIdentityError{code: "provider_failed"} = error} = + token_endpoint + |> start_credentials(identity_token_provider: WorkloadIdentity.token_env("MY_JWT")) + |> client(api()) + |> get() + + assert error.description =~ "MY_JWT" + assert requests(token_endpoint) == [] + end + end + + test "WIF-22 omitted fields default from the environment, and explicit values win" do + System.put_env("WORKOS_CLIENT_ID", "client_env") + System.put_env("WORKOS_WIF_TOKEN_URL", "https://env.wif.test/oauth2/token") + System.put_env("WORKOS_WIF_SCOPE", "scope_env") + System.put_env("WORKOS_ENVIRONMENT_ID", "environment_env") + + provider = fn -> {:ok, "assertion-1"} end + + # (c) Only a provider is passed. + token_endpoint = token_endpoint() + api = api() + + assert {:ok, credentials} = + Credentials.start_link( + identity_token_provider: provider, + req_options: [plug: token_plug(token_endpoint)] + ) + + assert {:ok, _} = credentials |> client(api) |> get() + + assert [exchange] = requests(token_endpoint) + assert exchange.host == "env.wif.test" + assert exchange.path == "/oauth2/token" + assert exchange.form["client_id"] == "client_env" + assert exchange.form["scope"] == "scope_env" + assert [%{environment_id: "environment_env"}] = requests(api) + + # (d) The same environment, with explicit values. + token_endpoint = token_endpoint() + api = api() + + assert {:ok, credentials} = + Credentials.start_link( + identity_token_provider: provider, + client_id: "client_explicit", + scope: "scope_explicit", + environment_id: "environment_explicit", + req_options: [plug: token_plug(token_endpoint)] + ) + + assert {:ok, _} = credentials |> client(api) |> get() + + assert [exchange] = requests(token_endpoint) + assert exchange.form["client_id"] == "client_explicit" + assert exchange.form["scope"] == "scope_explicit" + assert [%{environment_id: "environment_explicit"}] = requests(api) + end + + # -- redirects ---------------------------------------------------------------------- + + test "a redirect to another origin does not get the token or the environment header" do + api = api([{:status, 302, [{"location", "https://elsewhere.wif.test/landing"}]}]) + + capture_log(fn -> + assert {:ok, _} = token_endpoint() |> start_credentials() |> client(api) |> get() + end) + + assert [first, redirected] = requests(api) + assert first.host == "api.workos.com" + assert first.authorization == "Bearer access-1" + + assert redirected.host == "elsewhere.wif.test" + assert redirected.authorization == nil + assert redirected.environment_id == nil + end +end diff --git a/workload_identity_aws/.formatter.exs b/workload_identity_aws/.formatter.exs new file mode 100644 index 00000000..682fc6c6 --- /dev/null +++ b/workload_identity_aws/.formatter.exs @@ -0,0 +1,3 @@ +[ + inputs: ["{mix,.formatter}.exs", "{lib,test}/**/*.{ex,exs}"] +] diff --git a/workload_identity_aws/.gitignore b/workload_identity_aws/.gitignore new file mode 100644 index 00000000..5f62cf72 --- /dev/null +++ b/workload_identity_aws/.gitignore @@ -0,0 +1,9 @@ +/_build/ +/cover/ +/deps/ +/doc/ +/.fetch +erl_crash.dump +*.ez +*.tar +/tmp diff --git a/workload_identity_aws/CHANGELOG.md b/workload_identity_aws/CHANGELOG.md new file mode 100644 index 00000000..825c32f0 --- /dev/null +++ b/workload_identity_aws/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/workload_identity_aws/LICENSE b/workload_identity_aws/LICENSE new file mode 100644 index 00000000..9f65770c --- /dev/null +++ b/workload_identity_aws/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 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/workload_identity_aws/README.md b/workload_identity_aws/README.md new file mode 100644 index 00000000..c2abbabc --- /dev/null +++ b/workload_identity_aws/README.md @@ -0,0 +1,38 @@ +# WorkOS workload identity for AWS + +Identity token provider for [WorkOS](https://workos.com) workload identity federation on AWS. It asks STS for a web identity token (`GetWebIdentityToken`) for the workload's IAM role so the WorkOS SDK can exchange it for a short-lived access token. No API key is stored with the workload. + +It works on Lambda, EC2, ECS and EKS. The AWS account must have outbound identity federation enabled, and the workload's IAM policy must allow `sts:GetWebIdentityToken`. + +This package does not depend on `workos`. It depends on [`aws`](https://hex.pm/packages/aws), which builds and signs the STS request, and on [`aws_credentials`](https://hex.pm/packages/aws_credentials), which resolves and refreshes the workload's AWS credentials. + +## Installation + +Add it next to `workos` in `mix.exs`: + +```elixir +def deps do + [ + {:workos_workload_identity_aws, "~> 0.1"} + ] +end +``` + +## Usage + +```elixir +{:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: + WorkOS.WorkloadIdentity.AWS.aws_sts("https://api.workos.com", "us-east-1") + ) + +client = WorkOS.Client.new(credentials: credentials) +``` + +`aws_sts/2` takes the audience and an optional region, and returns a zero-arity function. Without a region argument it uses `AWS_REGION`, then `AWS_DEFAULT_REGION`, then the region the credential chain reports; it raises `ArgumentError` when none is found. Each call makes one signed request to the regional STS endpoint, asks for an `RS256` token, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.AWS.Error{}}`. + +AWS credentials come from the `aws_credentials` application's default chain: environment variables, shared credential files, ECS task roles, EKS Pod Identity, IAM roles for service accounts, and EC2 instance profiles. See its documentation to change the chain. diff --git a/workload_identity_aws/config/config.exs b/workload_identity_aws/config/config.exs new file mode 100644 index 00000000..a9b609d6 --- /dev/null +++ b/workload_identity_aws/config/config.exs @@ -0,0 +1,11 @@ +import Config + +# This file configures the package's own test runs only. Configuration is not +# inherited by applications that depend on the package. +if config_env() == :test do + # The tests stub the STS call. Keep the credential chain from reading + # ~/.aws or probing the container and instance metadata services. + config :aws_credentials, credential_providers: [] + + config :logger, level: :warning +end diff --git a/workload_identity_aws/lib/workos/workload_identity/aws.ex b/workload_identity_aws/lib/workos/workload_identity/aws.ex new file mode 100644 index 00000000..03222b86 --- /dev/null +++ b/workload_identity_aws/lib/workos/workload_identity/aws.ex @@ -0,0 +1,190 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.AWS do + @moduledoc """ + Identity token provider for AWS. + + `aws_sts/2` returns a provider: a zero-arity function that calls STS + `GetWebIdentityToken` for the given audience, signed with `RS256`, on the + regional STS endpoint, and returns `{:ok, token}` or + `{:error, %WorkOS.WorkloadIdentity.AWS.Error{}}`. + + The caller's AWS credentials come from the `aws_credentials` application, + which resolves them from the environment (Lambda), shared credential files, + ECS task roles, EKS (Pod Identity and IAM roles for service accounts) and + EC2 instance profiles, and refreshes them before they expire. The request is + built and signed by the `aws` package. + + The account must have outbound identity federation enabled, and the caller's + IAM policy must allow `sts:GetWebIdentityToken`. + + provider = WorkOS.WorkloadIdentity.AWS.aws_sts("https://api.workos.com", "us-east-1") + + {:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: provider + ) + + The provider holds no cache and does not retry; the WorkOS SDK retries it as + part of the token exchange. The token is never logged and never placed in + an error. + """ + + alias WorkOS.WorkloadIdentity.AWS.HTTPClient + + defmodule Error do + @moduledoc """ + Returned when STS did not issue a web identity token. + """ + + defexception [:message] + + @type t :: %__MODULE__{message: String.t()} + end + + @signing_algorithm "RS256" + @region_envs ["AWS_REGION", "AWS_DEFAULT_REGION"] + + @type provider :: (-> {:ok, String.t()} | {:error, Error.t()}) + + # The one call the provider makes, in the shape of + # `AWS.STS.get_web_identity_token/2`. Tests replace it. + @typep sts :: (region :: String.t(), input :: map() -> {:ok, map(), term()} | {:error, term()}) + + @doc """ + Returns an identity token provider for the given audience. + + The audience is required. The conventional value is `https://api.workos.com`. + + The region is optional when one can be resolved: from `AWS_REGION`, then + `AWS_DEFAULT_REGION`, then the region the credential chain reports (for + example from the EC2 instance metadata service). When no region is found, + this function raises `ArgumentError`. STS is always called on the regional + endpoint for that region, never on the global endpoint. + """ + @spec aws_sts(String.t(), String.t() | nil) :: provider() + def aws_sts(audience, region \\ nil) do + __provider__(audience, region, &get_web_identity_token/2) + end + + # The STS call is a test seam. It is not a public option. + @doc false + @spec __provider__(String.t(), String.t() | nil, sts()) :: provider() + def __provider__(audience, region, sts) + when is_binary(audience) and audience != "" and is_function(sts, 2) do + region = non_empty(region) || resolve_region() + + if is_nil(region) do + raise ArgumentError, + "aws_sts/2 could not find an AWS region. Pass one as the second argument, " <> + "or set AWS_REGION or AWS_DEFAULT_REGION." + end + + # `Audience` is a list in the STS API. The AWS query protocol writes list + # members as `Audience.member.N`, so the key is spelled out here. + # `DurationSeconds` is left unset so STS applies its default. + input = %{"Audience.member.1" => audience, "SigningAlgorithm" => @signing_algorithm} + + fn -> request(sts, region, input) end + end + + defp request(sts, region, input) do + case sts.(region, input) do + {:ok, body, _response} -> token(body) + {:error, reason} -> error(describe(reason)) + end + rescue + exception -> error("the STS client raised #{inspect(exception.__struct__)}") + end + + defp token(%{ + "GetWebIdentityTokenResponse" => %{ + "GetWebIdentityTokenResult" => %{"WebIdentityToken" => token} + } + }) + when is_binary(token) and token != "", + do: {:ok, token} + + defp token(_body), do: error("the response had no WebIdentityToken") + + defp get_web_identity_token(region, input) do + case credentials() do + %{access_key_id: _, secret_access_key: _} = credentials -> + credentials |> __client__(region) |> AWS.STS.get_web_identity_token(input) + + _none -> + {:error, :no_credentials} + end + end + + # An `aws` client for the regional STS endpoint, from one set of credentials + # out of the chain. Building it is a struct literal: it holds no connection, + # so it is rebuilt per call to pick up rotated credentials. + @doc false + @spec __client__(map(), String.t()) :: AWS.Client.t() + def __client__(%{access_key_id: access_key_id, secret_access_key: secret} = credentials, region) do + access_key_id + |> AWS.Client.create(secret, session_token(credentials), region) + |> AWS.Client.put_http_client({HTTPClient, []}) + end + + # The cached credentials, or nil. `aws_credentials` refreshes them itself. + defp credentials do + case :aws_credentials.get_credentials() do + %{} = credentials -> credentials + _undefined -> nil + end + catch + :exit, _reason -> nil + end + + defp session_token(%{token: token}) when is_binary(token), do: token + defp session_token(_credentials), do: nil + + defp resolve_region do + Enum.find_value(@region_envs, &non_empty(System.get_env(&1))) || + case credentials() do + %{region: region} when is_binary(region) -> non_empty(region) + _none -> nil + end + end + + defp non_empty(value) when value in [nil, ""], do: nil + defp non_empty(value), do: value + + # Only the AWS error code, the HTTP status or the failure kind is reported. + # Response bodies and raw reasons are never interpolated. + defp describe({:unexpected_response, %{status_code: status} = response}) do + case error_code(response) do + nil -> "STS returned HTTP #{status}" + code -> "STS returned #{code} (HTTP #{status})" + end + end + + defp describe(:no_credentials), do: "no AWS credentials were found" + defp describe(:timeout), do: "timeout" + defp describe({:failed_connect, _info}), do: "connection failed" + defp describe(_reason), do: "the request failed" + + defp error_code(%{body: body}) when is_binary(body) do + case Regex.run(~r{([A-Za-z0-9._:-]+)}, body) do + [_match, code] -> code + nil -> nil + end + end + + defp error_code(_response), do: nil + + defp error(detail) do + {:error, + %Error{ + message: + "sts:GetWebIdentityToken failed: #{detail}. Check that the caller's IAM policy " <> + "allows sts:GetWebIdentityToken and that outbound identity federation is " <> + "enabled for the account." + }} + end +end diff --git a/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex b/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex new file mode 100644 index 00000000..e9b96459 --- /dev/null +++ b/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex @@ -0,0 +1,66 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.AWS.HTTPClient do + @moduledoc false + + # Sends the request that `aws` has already built and signed, using `:httpc` + # from OTP. `aws` ships adapters for hackney and Finch only; this one keeps + # the package free of an HTTP client dependency. + + @behaviour AWS.HTTPClient + + @timeout_ms 10_000 + + @impl AWS.HTTPClient + def request(method, url, body, headers, _options) do + {content_type, headers} = pop_content_type(headers) + + request = + {String.to_charlist(url), Enum.map(headers, &to_charlists/1), content_type, + IO.iodata_to_binary(body)} + + http_options = + [timeout: @timeout_ms, connect_timeout: @timeout_ms, autoredirect: false] ++ + ssl_options(url) + + case :httpc.request(method, request, http_options, body_format: :binary) do + {:ok, {{_version, status, _reason}, response_headers, response_body}} -> + {:ok, + %{ + status_code: status, + headers: Enum.map(response_headers, fn {k, v} -> {to_string(k), to_string(v)} end), + body: response_body + }} + + {:error, reason} -> + {:error, reason} + end + end + + # `:httpc` takes the content type apart from the other headers. + defp pop_content_type(headers) do + case Enum.split_with(headers, fn {name, _value} -> String.downcase(name) == "content-type" end) do + {[{_name, content_type} | _], rest} -> {String.to_charlist(content_type), rest} + {[], rest} -> {~c"application/octet-stream", rest} + end + end + + defp to_charlists({name, value}), do: {String.to_charlist(name), String.to_charlist(value)} + + # Verify the endpoint's certificate against the operating system's trust + # store. OTP releases before 26 do not verify unless told to. + defp ssl_options("https://" <> _rest) do + [ + ssl: [ + verify: :verify_peer, + cacerts: :public_key.cacerts_get(), + depth: 10, + customize_hostname_check: [ + match_fun: :public_key.pkix_verify_hostname_match_fun(:https) + ] + ] + ] + end + + defp ssl_options(_url), do: [] +end diff --git a/workload_identity_aws/mix.exs b/workload_identity_aws/mix.exs new file mode 100644 index 00000000..7df9c086 --- /dev/null +++ b/workload_identity_aws/mix.exs @@ -0,0 +1,69 @@ +defmodule WorkOS.WorkloadIdentity.AWS.MixProject do + use Mix.Project + + @version "0.0.0" + @source_url "https://github.com/workos/workos-elixir" + + def project do + [ + app: :workos_workload_identity_aws, + version: @version, + name: "WorkOS workload identity for AWS", + elixir: "~> 1.18", + elixirc_paths: elixirc_paths(Mix.env()), + start_permanent: Mix.env() == :prod, + description: description(), + package: package(), + docs: docs(), + deps: deps() + ] + end + + # STS is called through `aws`, over `:httpc`, so no HTTP client dependency + # is needed beyond OTP. + def application do + [extra_applications: [:inets, :ssl, :public_key]] + end + + defp description do + """ + AWS identity token provider for WorkOS workload identity federation. + """ + end + + defp package do + [ + description: description(), + licenses: ["MIT"], + links: %{ + "GitHub" => @source_url, + "WorkOS" => "https://workos.com" + } + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + defp deps do + [ + # 1.0.11 is the first release with `AWS.STS.get_web_identity_token/3`. + {:aws, "~> 1.0 and >= 1.0.11"}, + # The credential chain: environment, shared files, ECS, EKS and EC2. + {:aws_credentials, "~> 1.1"}, + {:ex_doc, "~> 0.34", only: :dev, runtime: false}, + {:credo, "~> 1.7", only: [:dev, :test], runtime: false} + ] + end + + defp docs do + [ + extras: [ + "README.md": [title: "Overview"] + ], + main: "readme", + source_url: @source_url, + source_ref: "workos_workload_identity_aws-v#{@version}" + ] + end +end diff --git a/workload_identity_aws/mix.lock b/workload_identity_aws/mix.lock new file mode 100644 index 00000000..dd1ac69f --- /dev/null +++ b/workload_identity_aws/mix.lock @@ -0,0 +1,18 @@ +%{ + "aws": {:hex, :aws, "1.0.15", "a64ae362c79a33e52c998a52c332cb537bfce101fdd09acb875bef2affe92291", [:mix], [{:aws_signature, "~> 0.3", [hex: :aws_signature, repo: "hexpm", optional: false]}, {:finch, "~> 0.22", [hex: :finch, repo: "hexpm", optional: true]}, {:hackney, "~> 4.5", [hex: :hackney, repo: "hexpm", optional: true]}, {:jason, "~> 1.2", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "ca9eb4e28b144bc34a1b95e93441af7200839257849164c01edafc06750d2405"}, + "aws_credentials": {:hex, :aws_credentials, "1.1.1", "4a28d7d2c01956dd9a2cc52a7edd5cb1e58343766715753d4b8d0d043771b95c", [:rebar3], [{:eini, "~> 2.2.5", [hex: :eini_beam, repo: "hexpm", optional: false]}, {:iso8601, "~> 1.3.4", [hex: :iso8601, repo: "hexpm", optional: false]}, {:jsx, "~> 3.1.0", [hex: :jsx, repo: "hexpm", optional: false]}], "hexpm", "8655e0e3c82c5ad659729ea8717ae1f0a087ea268e15aefa674fc3d781c1e9e2"}, + "aws_signature": {:hex, :aws_signature, "0.4.3", "28a308f9d39fd8d197874b6b737e8cd50a41be4d4dd765f408ca0483b026c18d", [:rebar3], [], "hexpm", "7b4dc6fd48e583b61cef75b330c344e71c451ba70903d1506af1e38caf68bb0c"}, + "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, + "credo": {:hex, :credo, "1.7.19", "cc52129665fc7c15143d47838fda0f9cd6dac9ceced7bf4da6f85fcbfe64b12a", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "2d8bc95d5a7bb99dd2613621d4f08c6a3575c3fd4b62e6a2b48a100352a557b8"}, + "earmark_parser": {:hex, :earmark_parser, "1.4.46", "67607a0532e810c6f630a515c548d0b24949643f168cc556303bee4cf96105c7", [:mix], [], "hexpm", "9c44636e8a1c68c62f526b2dcd85d941dbbcee7ab82cf64ba06ce28bef8e89f5"}, + "eini": {:hex, :eini_beam, "2.2.5", "28fa0a4eb7ff885cc388877b73fbd56fcca3b2eae4d81e47c47f317b900da1da", [:rebar3], [], "hexpm", "511e9207649f3becb5d945f1813615987899cf78fa130f92be07193a6a74ecb8"}, + "ex_doc": {:hex, :ex_doc, "0.40.4", "66f2e42bf588594d5a8aab31cad87f2ddad09d0da1b1a2f379340ec2c2e497cb", [:mix], [{:earmark_parser, "~> 1.4.46", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "6222b9e423d76584ee34df2c82a5ed72c2d53dc153f7f483ad28b378694186cc"}, + "file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"}, + "iso8601": {:hex, :iso8601, "1.3.4", "7b1f095f86f6cf65e1e5a77872e8e8bf69bd58d4c3a415b3f77d9cc9423ecbb9", [:rebar3], [], "hexpm", "a334469c07f1c219326bc891a95f5eec8eb12dd8071a3fff56a7843cb20fae34"}, + "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"}, + "jsx": {:hex, :jsx, "3.1.0", "d12516baa0bb23a59bb35dccaf02a1bd08243fcbb9efe24f2d9d056ccff71268", [:rebar3], [], "hexpm", "0c5cc8fdc11b53cc25cf65ac6705ad39e54ecc56d1c22e4adb8f5a53fb9427f3"}, + "makeup": {:hex, :makeup, "1.2.3", "c3ef0ff83acf305384acba0f70bff87d8732502baa1eb3eb081d8c154fbe18f5", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "15970751b7021c2bcd7ed56a54b3def23affd3969fb7c214dffdf28e97ce6f76"}, + "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, + "makeup_erlang": {:hex, :makeup_erlang, "1.1.0", "835f7e60792e08824cda445639555d7bf1bbbddb1b60b306e33cb6f6db24dc74", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "1cd6780fb1dd1a03979abaed0fe82712b0625118fd5257d3ebbf73f960c73c3c"}, + "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, +} diff --git a/workload_identity_aws/test/support/stub_http_client.ex b/workload_identity_aws/test/support/stub_http_client.ex new file mode 100644 index 00000000..bdd8091f --- /dev/null +++ b/workload_identity_aws/test/support/stub_http_client.ex @@ -0,0 +1,21 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.AWS.StubHTTPClient do + @moduledoc false + + # An `AWS.HTTPClient` for tests. It reports the request `aws` built and + # signed to the test process and answers with a canned response, so the + # real request-building and response-decoding code runs with no network. + + @behaviour AWS.HTTPClient + + @impl AWS.HTTPClient + def request(method, url, body, headers, options) do + send( + Keyword.fetch!(options, :test), + {:http, %{method: method, url: url, body: IO.iodata_to_binary(body), headers: headers}} + ) + + Keyword.fetch!(options, :response) + end +end diff --git a/workload_identity_aws/test/support/test_server.ex b/workload_identity_aws/test/support/test_server.ex new file mode 100644 index 00000000..1a71fff8 --- /dev/null +++ b/workload_identity_aws/test/support/test_server.ex @@ -0,0 +1,96 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.TestServer do + @moduledoc false + + # A minimal HTTP/1.1 server on a loopback port, for tests only. It answers + # each connection with the next canned response (the last one repeats) and + # sends every request it reads to the process that started it, as + # `{:request, ref, %{method: _, target: _, headers: _, body: _}}`. + # + # It is linked to the test process, so it stops when the test ends. + + @type response :: {pos_integer(), [{String.t(), String.t()}], String.t()} + + @spec start([response()]) :: %{url: String.t(), ref: reference()} + def start(responses) when is_list(responses) and responses != [] do + owner = self() + ref = make_ref() + + spawn_link(fn -> + {:ok, listener} = + :gen_tcp.listen(0, [ + :binary, + packet: :http_bin, + active: false, + reuseaddr: true, + ip: {127, 0, 0, 1} + ]) + + {:ok, port} = :inet.port(listener) + send(owner, {:listening, ref, port}) + accept(listener, responses, owner, ref) + end) + + receive do + {:listening, ^ref, port} -> %{url: "http://127.0.0.1:#{port}", ref: ref} + after + 5_000 -> raise "test server did not start" + end + end + + defp accept(listener, responses, owner, ref) do + {:ok, socket} = :gen_tcp.accept(listener) + send(owner, {:request, ref, read_request(socket)}) + + {response, rest} = next(responses) + :ok = :gen_tcp.send(socket, encode(response)) + :ok = :gen_tcp.close(socket) + + accept(listener, rest, owner, ref) + end + + defp next([response]), do: {response, [response]} + defp next([response | rest]), do: {response, rest} + + defp read_request(socket) do + {:ok, {:http_request, method, {:abs_path, target}, _version}} = + :gen_tcp.recv(socket, 0, 5_000) + + headers = read_headers(socket, %{}) + length = headers |> Map.get("content-length", "0") |> String.to_integer() + + %{ + method: to_string(method), + target: target, + headers: headers, + body: read_body(socket, length) + } + end + + defp read_headers(socket, headers) do + case :gen_tcp.recv(socket, 0, 5_000) do + {:ok, {:http_header, _, name, _, value}} -> + read_headers(socket, Map.put(headers, name |> to_string() |> String.downcase(), value)) + + {:ok, :http_eoh} -> + headers + end + end + + defp read_body(_socket, 0), do: "" + + defp read_body(socket, length) do + :ok = :inet.setopts(socket, packet: :raw) + {:ok, body} = :gen_tcp.recv(socket, length, 5_000) + body + end + + defp encode({status, headers, body}) do + head = + [{"content-length", Integer.to_string(byte_size(body))}, {"connection", "close"} | headers] + |> Enum.map(fn {name, value} -> [name, ": ", value, "\r\n"] end) + + ["HTTP/1.1 ", Integer.to_string(status), " Mock\r\n", head, "\r\n", body] + end +end diff --git a/workload_identity_aws/test/test_helper.exs b/workload_identity_aws/test/test_helper.exs new file mode 100644 index 00000000..3416380c --- /dev/null +++ b/workload_identity_aws/test/test_helper.exs @@ -0,0 +1,3 @@ +# @oagen-ignore-file + +ExUnit.start() diff --git a/workload_identity_aws/test/workos/workload_identity/aws_test.exs b/workload_identity_aws/test/workos/workload_identity/aws_test.exs new file mode 100644 index 00000000..869e023a --- /dev/null +++ b/workload_identity_aws/test/workos/workload_identity/aws_test.exs @@ -0,0 +1,269 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.AWSTest do + # The region tests change process-wide environment variables, so these + # tests cannot run concurrently. + use ExUnit.Case, async: false + + alias WorkOS.WorkloadIdentity.AWS, as: Provider + alias WorkOS.WorkloadIdentity.AWS.Error + alias WorkOS.WorkloadIdentity.AWS.HTTPClient + alias WorkOS.WorkloadIdentity.AWS.StubHTTPClient + alias WorkOS.WorkloadIdentity.TestServer + + @audience "https://api.workos.com" + @region_envs ["AWS_REGION", "AWS_DEFAULT_REGION"] + + @success_xml """ + + + aws-jwt + 2026-11-12T00:05:00Z + + + 00000000-0000-0000-0000-000000000000 + + + """ + + @access_denied_xml """ + + + Sender + AccessDenied + User is not authorized to perform: sts:GetWebIdentityToken + + 00000000-0000-0000-0000-000000000000 + + """ + + setup do + previous = Map.new(@region_envs, &{&1, System.get_env(&1)}) + + on_exit(fn -> + Enum.each(previous, fn + {name, nil} -> System.delete_env(name) + {name, value} -> System.put_env(name, value) + end) + end) + + Enum.each(@region_envs, &System.delete_env/1) + :ok + end + + # The one-call STS seam: records its arguments and returns `result`, in the + # shape of `AWS.STS.get_web_identity_token/2`. + defp sts_stub(result) do + test = self() + + fn region, input -> + send(test, {:sts, region, input}) + result + end + end + + defp issued(token) do + body = %{ + "GetWebIdentityTokenResponse" => %{ + "GetWebIdentityTokenResult" => %{"WebIdentityToken" => token} + } + } + + {:ok, body, %{status_code: 200}} + end + + defp access_denied do + {:error, {:unexpected_response, %{status_code: 403, body: @access_denied_xml}}} + end + + # The real `aws` client the provider builds, with only the HTTP layer + # replaced. + defp real_sts(response) do + client = + %{access_key_id: "AKIDEXAMPLE", secret_access_key: "secret", token: "session-token"} + |> Provider.__client__("us-east-1") + |> AWS.Client.put_http_client({StubHTTPClient, [test: self(), response: response]}) + + fn "us-east-1", input -> AWS.STS.get_web_identity_token(client, input) end + end + + test "WIF-AWS-01 calls STS GetWebIdentityToken with the audience and RS256 in the given region" do + provider = Provider.__provider__(@audience, "us-east-1", sts_stub(issued("aws-jwt"))) + + assert provider.() == {:ok, "aws-jwt"} + + assert_receive {:sts, "us-east-1", input} + assert input == %{"Audience.member.1" => @audience, "SigningAlgorithm" => "RS256"} + refute_receive {:sts, _region, _input} + end + + test "WIF-AWS-01 the request goes to the regional STS endpoint, signed, with no duration" do + sts = real_sts({:ok, %{status_code: 200, headers: [], body: @success_xml}}) + + assert Provider.__provider__(@audience, "us-east-1", sts).() == {:ok, "aws-jwt"} + + assert_receive {:http, request} + assert request.method == :post + assert URI.parse(request.url).host == "sts.us-east-1.amazonaws.com" + assert URI.parse(request.url).scheme == "https" + + assert URI.decode_query(request.body) == %{ + "Action" => "GetWebIdentityToken", + "Version" => "2011-06-15", + "Audience.member.1" => @audience, + "SigningAlgorithm" => "RS256" + } + + headers = Map.new(request.headers, fn {name, value} -> {String.downcase(name), value} end) + assert headers["host"] == "sts.us-east-1.amazonaws.com" + assert headers["authorization"] =~ "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/" + assert headers["authorization"] =~ "/us-east-1/sts/aws4_request" + assert headers["x-amz-security-token"] == "session-token" + end + + test "WIF-AWS-01 with no region available, building the provider is an error" do + assert_raise ArgumentError, ~r/AWS region/, fn -> Provider.aws_sts(@audience) end + + assert_raise ArgumentError, ~r/AWS region/, fn -> + Provider.__provider__(@audience, "", sts_stub(issued("aws-jwt"))) + end + + refute_receive {:sts, _region, _input} + end + + test "WIF-AWS-01 the region falls back to AWS_REGION, then AWS_DEFAULT_REGION" do + System.put_env("AWS_DEFAULT_REGION", "eu-west-1") + + assert Provider.__provider__(@audience, nil, sts_stub(issued("aws-jwt"))).() == + {:ok, "aws-jwt"} + + assert_receive {:sts, "eu-west-1", _input} + + System.put_env("AWS_REGION", "ap-southeast-2") + + assert Provider.__provider__(@audience, nil, sts_stub(issued("aws-jwt"))).() == + {:ok, "aws-jwt"} + + assert_receive {:sts, "ap-southeast-2", _input} + + # An explicit region wins over both. + assert Provider.__provider__(@audience, "us-west-2", sts_stub(issued("aws-jwt"))).() == + {:ok, "aws-jwt"} + + assert_receive {:sts, "us-west-2", _input} + end + + test "WIF-AWS-02 an STS error is a provider error that names the call and the AWS error code" do + provider = Provider.__provider__(@audience, "us-east-1", sts_stub(access_denied())) + + assert {:error, %Error{message: message}} = provider.() + assert message =~ "sts:GetWebIdentityToken" + assert message =~ "AccessDenied" + assert message =~ "403" + end + + test "WIF-AWS-02 an access-denied response from STS is decoded into the same error" do + sts = real_sts({:ok, %{status_code: 403, headers: [], body: @access_denied_xml}}) + + assert {:error, %Error{message: message}} = + Provider.__provider__(@audience, "us-east-1", sts).() + + assert message =~ "sts:GetWebIdentityToken" + assert message =~ "AccessDenied" + end + + test "WIF-AWS-02 an STS client that raises is a provider error that names the call" do + sts = fn _region, _input -> raise "AccessDenied: SECRET-TOKEN-VALUE" end + + assert {:error, %Error{message: message} = error} = + Provider.__provider__(@audience, "us-east-1", sts).() + + assert message =~ "sts:GetWebIdentityToken" + refute message =~ "SECRET-TOKEN-VALUE" + refute inspect(error) =~ "SECRET-TOKEN-VALUE" + end + + test "WIF-AWS-02 the error never carries a response body" do + body = + "ThrottlingSECRET-TOKEN-VALUE" + + sts = sts_stub({:error, {:unexpected_response, %{status_code: 400, body: body}}}) + + assert {:error, %Error{message: message} = error} = + Provider.__provider__(@audience, "us-east-1", sts).() + + assert message =~ "Throttling" + refute inspect(error) =~ "SECRET-TOKEN-VALUE" + end + + test "a response with no token is an error" do + for result <- [issued(""), {:ok, %{}, %{status_code: 200}}, {:ok, nil, %{status_code: 200}}] do + provider = Provider.__provider__(@audience, "us-east-1", sts_stub(result)) + + assert {:error, %Error{message: message}} = provider.() + assert message =~ "sts:GetWebIdentityToken" + end + end + + test "with no AWS credentials the provider fails without a request" do + # The test configuration gives the credential chain no providers. + assert {:error, %Error{message: message}} = Provider.aws_sts(@audience, "us-east-1").() + assert message =~ "sts:GetWebIdentityToken" + assert message =~ "no AWS credentials" + end + + test "the audience is required" do + assert_raise FunctionClauseError, fn -> Provider.aws_sts("", "us-east-1") end + end + + describe "the :httpc adapter" do + test "sends the method, headers, content type and body it is given, and returns the response" do + server = TestServer.start([{200, [{"x-amzn-requestid", "abc"}], ""}]) + + headers = [ + {"Host", "sts.us-east-1.amazonaws.com"}, + {"Content-Type", "application/x-www-form-urlencoded"}, + {"Authorization", "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/..."}, + {"X-Amz-Date", "20261112T000000Z"} + ] + + assert {:ok, %{status_code: 200, body: "", headers: response_headers}} = + HTTPClient.request(:post, server.url <> "/", ["Action=", "X"], headers, []) + + assert {"x-amzn-requestid", "abc"} in response_headers + + ref = server.ref + assert_receive {:request, ^ref, request} + assert request.method == "POST" + assert request.target == "/" + assert request.body == "Action=X" + assert request.headers["host"] == "sts.us-east-1.amazonaws.com" + assert request.headers["content-type"] == "application/x-www-form-urlencoded" + assert request.headers["authorization"] == "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/..." + assert request.headers["x-amz-date"] == "20261112T000000Z" + end + + test "does not follow a redirect" do + elsewhere = TestServer.start([{200, [], ""}]) + server = TestServer.start([{307, [{"location", elsewhere.url <> "/"}], ""}]) + + assert {:ok, %{status_code: 307}} = + HTTPClient.request( + :post, + server.url <> "/", + "a=b", + [{"Content-Type", "text/plain"}], + [] + ) + + ref = elsewhere.ref + refute_receive {:request, ^ref, _request} + end + + test "returns a connection failure as an error" do + # Port 1 on loopback refuses connections. + assert {:error, _reason} = + HTTPClient.request(:post, "http://127.0.0.1:1/", "a=b", [], []) + end + end +end diff --git a/workload_identity_gcp/.formatter.exs b/workload_identity_gcp/.formatter.exs new file mode 100644 index 00000000..682fc6c6 --- /dev/null +++ b/workload_identity_gcp/.formatter.exs @@ -0,0 +1,3 @@ +[ + inputs: ["{mix,.formatter}.exs", "{lib,test}/**/*.{ex,exs}"] +] diff --git a/workload_identity_gcp/.gitignore b/workload_identity_gcp/.gitignore new file mode 100644 index 00000000..5f62cf72 --- /dev/null +++ b/workload_identity_gcp/.gitignore @@ -0,0 +1,9 @@ +/_build/ +/cover/ +/deps/ +/doc/ +/.fetch +erl_crash.dump +*.ez +*.tar +/tmp diff --git a/workload_identity_gcp/CHANGELOG.md b/workload_identity_gcp/CHANGELOG.md new file mode 100644 index 00000000..825c32f0 --- /dev/null +++ b/workload_identity_gcp/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/workload_identity_gcp/LICENSE b/workload_identity_gcp/LICENSE new file mode 100644 index 00000000..9f65770c --- /dev/null +++ b/workload_identity_gcp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 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/workload_identity_gcp/README.md b/workload_identity_gcp/README.md new file mode 100644 index 00000000..b5286f1f --- /dev/null +++ b/workload_identity_gcp/README.md @@ -0,0 +1,35 @@ +# WorkOS workload identity for Google Cloud + +Identity token provider for [WorkOS](https://workos.com) workload identity federation on Google Cloud. It fetches an identity token for the attached service account from the metadata server so the WorkOS SDK can exchange it for a short-lived access token. No API key is stored with the workload. + +It works wherever the metadata server is reachable: Compute Engine, GKE, Cloud Run, Cloud Functions and App Engine. + +This package does not depend on `workos`. It has no dependencies beyond OTP. + +## Installation + +Add it next to `workos` in `mix.exs`: + +```elixir +def deps do + [ + {:workos_workload_identity_gcp, "~> 0.1"} + ] +end +``` + +## Usage + +```elixir +{:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: WorkOS.WorkloadIdentity.GCP.gcp_metadata("https://api.workos.com") + ) + +client = WorkOS.Client.new(credentials: credentials) +``` + +`gcp_metadata/1` takes the audience and returns a zero-arity function. Each call makes one GET to the metadata server with a 10-second timeout, follows no redirect, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.GCP.Error{}}`. diff --git a/workload_identity_gcp/lib/workos/workload_identity/gcp.ex b/workload_identity_gcp/lib/workos/workload_identity/gcp.ex new file mode 100644 index 00000000..3be5c496 --- /dev/null +++ b/workload_identity_gcp/lib/workos/workload_identity/gcp.ex @@ -0,0 +1,105 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.GCP do + @moduledoc """ + Identity token provider for Google Cloud. + + `gcp_metadata/1` returns a provider: a zero-arity function that asks the + metadata server for an identity token of the attached service account, with + the given audience, and returns `{:ok, token}` or + `{:error, %WorkOS.WorkloadIdentity.GCP.Error{}}`. + + It works wherever the metadata server is reachable: Compute Engine, GKE, + Cloud Run, Cloud Functions and App Engine. + + provider = WorkOS.WorkloadIdentity.GCP.gcp_metadata("https://api.workos.com") + + {:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: provider + ) + + The provider holds no cache and does not retry; the WorkOS SDK retries it as + part of the token exchange. The token is never logged and never placed in + an error. + """ + + defmodule Error do + @moduledoc """ + Returned when the metadata server's identity token could not be fetched. + """ + + defexception [:message] + + @type t :: %__MODULE__{message: String.t()} + end + + @metadata_base_url "http://metadata.google.internal" + @identity_path "/computeMetadata/v1/instance/service-accounts/default/identity" + @timeout_ms 10_000 + + @type provider :: (-> {:ok, String.t()} | {:error, Error.t()}) + + @doc """ + Returns an identity token provider for the given audience. + + The audience is required. The conventional value is `https://api.workos.com`. + """ + @spec gcp_metadata(String.t()) :: provider() + def gcp_metadata(audience), do: __provider__(audience, @metadata_base_url) + + # The base URL is a test seam. It is not a public option and is not read + # from the environment. + @doc false + @spec __provider__(String.t(), String.t()) :: provider() + def __provider__(audience, base_url) when is_binary(audience) and audience != "" do + fn -> fetch(audience, base_url) end + end + + defp fetch(audience, base_url) do + url = + base_url <> + @identity_path <> + "?audience=" <> URI.encode(audience, &URI.char_unreserved?/1) <> "&format=full" + + headers = [{~c"metadata-flavor", ~c"Google"}] + http_options = [timeout: @timeout_ms, connect_timeout: @timeout_ms, autoredirect: false] + + case :httpc.request(:get, {String.to_charlist(url), headers}, http_options, + body_format: :binary + ) do + {:ok, {{_version, 200, _reason}, _headers, body}} -> + token(body) + + {:ok, {{_version, status, _reason}, _headers, _body}} -> + error("The Google Cloud metadata server returned HTTP #{status}.") + + {:error, reason} -> + error("The Google Cloud metadata server could not be reached: #{describe(reason)}.") + end + end + + defp token(body) do + case String.trim(body) do + "" -> error("The Google Cloud metadata server returned an empty identity token.") + token -> {:ok, token} + end + end + + # Only the failure kind is reported. The raw reason is never interpolated. + defp describe(:timeout), do: "timeout" + + defp describe({:failed_connect, info}) when is_list(info) do + case List.keyfind(info, :inet, 0) || List.keyfind(info, :inet6, 0) do + {_family, _options, reason} when is_atom(reason) -> "connection failed (#{reason})" + _other -> "connection failed" + end + end + + defp describe(_reason), do: "request failed" + + defp error(message), do: {:error, %Error{message: message}} +end diff --git a/workload_identity_gcp/mix.exs b/workload_identity_gcp/mix.exs new file mode 100644 index 00000000..62fc2cd7 --- /dev/null +++ b/workload_identity_gcp/mix.exs @@ -0,0 +1,65 @@ +defmodule WorkOS.WorkloadIdentity.GCP.MixProject do + use Mix.Project + + @version "0.0.0" + @source_url "https://github.com/workos/workos-elixir" + + def project do + [ + app: :workos_workload_identity_gcp, + version: @version, + name: "WorkOS workload identity for Google Cloud", + elixir: "~> 1.18", + elixirc_paths: elixirc_paths(Mix.env()), + start_permanent: Mix.env() == :prod, + description: description(), + package: package(), + docs: docs(), + deps: deps() + ] + end + + # The provider makes its one HTTP request with `:httpc`, so it needs no + # dependencies beyond OTP. + def application do + [extra_applications: [:inets, :ssl]] + end + + defp description do + """ + Google Cloud identity token provider for WorkOS workload identity federation. + """ + end + + defp package do + [ + description: description(), + licenses: ["MIT"], + links: %{ + "GitHub" => @source_url, + "WorkOS" => "https://workos.com" + } + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + defp deps do + [ + {:ex_doc, "~> 0.34", only: :dev, runtime: false}, + {:credo, "~> 1.7", only: [:dev, :test], runtime: false} + ] + end + + defp docs do + [ + extras: [ + "README.md": [title: "Overview"] + ], + main: "readme", + source_url: @source_url, + source_ref: "workos_workload_identity_gcp-v#{@version}" + ] + end +end diff --git a/workload_identity_gcp/mix.lock b/workload_identity_gcp/mix.lock new file mode 100644 index 00000000..b8598071 --- /dev/null +++ b/workload_identity_gcp/mix.lock @@ -0,0 +1,12 @@ +%{ + "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, + "credo": {:hex, :credo, "1.7.19", "cc52129665fc7c15143d47838fda0f9cd6dac9ceced7bf4da6f85fcbfe64b12a", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "2d8bc95d5a7bb99dd2613621d4f08c6a3575c3fd4b62e6a2b48a100352a557b8"}, + "earmark_parser": {:hex, :earmark_parser, "1.4.46", "67607a0532e810c6f630a515c548d0b24949643f168cc556303bee4cf96105c7", [:mix], [], "hexpm", "9c44636e8a1c68c62f526b2dcd85d941dbbcee7ab82cf64ba06ce28bef8e89f5"}, + "ex_doc": {:hex, :ex_doc, "0.40.4", "66f2e42bf588594d5a8aab31cad87f2ddad09d0da1b1a2f379340ec2c2e497cb", [:mix], [{:earmark_parser, "~> 1.4.46", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "6222b9e423d76584ee34df2c82a5ed72c2d53dc153f7f483ad28b378694186cc"}, + "file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"}, + "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"}, + "makeup": {:hex, :makeup, "1.2.3", "c3ef0ff83acf305384acba0f70bff87d8732502baa1eb3eb081d8c154fbe18f5", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "15970751b7021c2bcd7ed56a54b3def23affd3969fb7c214dffdf28e97ce6f76"}, + "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, + "makeup_erlang": {:hex, :makeup_erlang, "1.1.0", "835f7e60792e08824cda445639555d7bf1bbbddb1b60b306e33cb6f6db24dc74", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "1cd6780fb1dd1a03979abaed0fe82712b0625118fd5257d3ebbf73f960c73c3c"}, + "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, +} diff --git a/workload_identity_gcp/test/support/test_server.ex b/workload_identity_gcp/test/support/test_server.ex new file mode 100644 index 00000000..1a71fff8 --- /dev/null +++ b/workload_identity_gcp/test/support/test_server.ex @@ -0,0 +1,96 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.TestServer do + @moduledoc false + + # A minimal HTTP/1.1 server on a loopback port, for tests only. It answers + # each connection with the next canned response (the last one repeats) and + # sends every request it reads to the process that started it, as + # `{:request, ref, %{method: _, target: _, headers: _, body: _}}`. + # + # It is linked to the test process, so it stops when the test ends. + + @type response :: {pos_integer(), [{String.t(), String.t()}], String.t()} + + @spec start([response()]) :: %{url: String.t(), ref: reference()} + def start(responses) when is_list(responses) and responses != [] do + owner = self() + ref = make_ref() + + spawn_link(fn -> + {:ok, listener} = + :gen_tcp.listen(0, [ + :binary, + packet: :http_bin, + active: false, + reuseaddr: true, + ip: {127, 0, 0, 1} + ]) + + {:ok, port} = :inet.port(listener) + send(owner, {:listening, ref, port}) + accept(listener, responses, owner, ref) + end) + + receive do + {:listening, ^ref, port} -> %{url: "http://127.0.0.1:#{port}", ref: ref} + after + 5_000 -> raise "test server did not start" + end + end + + defp accept(listener, responses, owner, ref) do + {:ok, socket} = :gen_tcp.accept(listener) + send(owner, {:request, ref, read_request(socket)}) + + {response, rest} = next(responses) + :ok = :gen_tcp.send(socket, encode(response)) + :ok = :gen_tcp.close(socket) + + accept(listener, rest, owner, ref) + end + + defp next([response]), do: {response, [response]} + defp next([response | rest]), do: {response, rest} + + defp read_request(socket) do + {:ok, {:http_request, method, {:abs_path, target}, _version}} = + :gen_tcp.recv(socket, 0, 5_000) + + headers = read_headers(socket, %{}) + length = headers |> Map.get("content-length", "0") |> String.to_integer() + + %{ + method: to_string(method), + target: target, + headers: headers, + body: read_body(socket, length) + } + end + + defp read_headers(socket, headers) do + case :gen_tcp.recv(socket, 0, 5_000) do + {:ok, {:http_header, _, name, _, value}} -> + read_headers(socket, Map.put(headers, name |> to_string() |> String.downcase(), value)) + + {:ok, :http_eoh} -> + headers + end + end + + defp read_body(_socket, 0), do: "" + + defp read_body(socket, length) do + :ok = :inet.setopts(socket, packet: :raw) + {:ok, body} = :gen_tcp.recv(socket, length, 5_000) + body + end + + defp encode({status, headers, body}) do + head = + [{"content-length", Integer.to_string(byte_size(body))}, {"connection", "close"} | headers] + |> Enum.map(fn {name, value} -> [name, ": ", value, "\r\n"] end) + + ["HTTP/1.1 ", Integer.to_string(status), " Mock\r\n", head, "\r\n", body] + end +end diff --git a/workload_identity_gcp/test/test_helper.exs b/workload_identity_gcp/test/test_helper.exs new file mode 100644 index 00000000..3416380c --- /dev/null +++ b/workload_identity_gcp/test/test_helper.exs @@ -0,0 +1,3 @@ +# @oagen-ignore-file + +ExUnit.start() diff --git a/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs new file mode 100644 index 00000000..af6f2fdb --- /dev/null +++ b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs @@ -0,0 +1,87 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.GCPTest do + use ExUnit.Case, async: true + + alias WorkOS.WorkloadIdentity.GCP + alias WorkOS.WorkloadIdentity.GCP.Error + alias WorkOS.WorkloadIdentity.TestServer + + @audience "https://api.workos.com" + @identity_path "/computeMetadata/v1/instance/service-accounts/default/identity" + + # `GCP.__provider__/2` is `gcp_metadata/1` with the metadata base URL + # pointed at the mock. + defp provider(server, audience \\ @audience), do: GCP.__provider__(audience, server.url) + + test "WIF-GCP-01 GETs the identity URL with the encoded audience, format=full and the metadata header" do + server = TestServer.start([{200, [], "gcp-jwt\n"}]) + + assert provider(server).() == {:ok, "gcp-jwt"} + + ref = server.ref + assert_receive {:request, ^ref, request} + assert request.method == "GET" + + assert request.target == + @identity_path <> "?audience=https%3A%2F%2Fapi.workos.com&format=full" + + assert request.headers["metadata-flavor"] == "Google" + refute_receive {:request, ^ref, _second} + end + + test "WIF-GCP-01 percent-encodes an audience that has reserved characters" do + server = TestServer.start([{200, [], "gcp-jwt"}]) + + assert provider(server, "urn:workos:api/v1 test").() == {:ok, "gcp-jwt"} + + ref = server.ref + assert_receive {:request, ^ref, request} + + assert request.target == + @identity_path <> "?audience=urn%3Aworkos%3Aapi%2Fv1%20test&format=full" + end + + test "WIF-GCP-02 a non-200 status is an error that names the status" do + server = TestServer.start([{404, [], "not found"}]) + + assert {:error, %Error{message: message}} = provider(server).() + assert message =~ "404" + end + + test "WIF-GCP-02 an empty body is an error" do + for body <- ["", " \n"] do + server = TestServer.start([{200, [], body}]) + + assert {:error, %Error{message: message}} = provider(server).() + assert message =~ "empty" + end + end + + test "WIF-GCP-02 a redirect is an error and is not followed" do + elsewhere = TestServer.start([{200, [], "gcp-jwt"}]) + server = TestServer.start([{302, [{"location", elsewhere.url <> @identity_path}], ""}]) + + assert {:error, %Error{message: message}} = provider(server).() + assert message =~ "302" + + ref = elsewhere.ref + refute_receive {:request, ^ref, _request} + end + + test "a connection failure is an error" do + # Port 1 on loopback refuses connections. + assert {:error, %Error{message: message}} = + GCP.__provider__(@audience, "http://127.0.0.1:1").() + + assert message =~ "could not be reached" + end + + test "the audience is required" do + assert_raise FunctionClauseError, fn -> GCP.gcp_metadata("") end + end + + test "gcp_metadata/1 returns a zero-arity provider" do + assert is_function(GCP.gcp_metadata(@audience), 0) + end +end diff --git a/workload_identity_github_actions/.formatter.exs b/workload_identity_github_actions/.formatter.exs new file mode 100644 index 00000000..682fc6c6 --- /dev/null +++ b/workload_identity_github_actions/.formatter.exs @@ -0,0 +1,3 @@ +[ + inputs: ["{mix,.formatter}.exs", "{lib,test}/**/*.{ex,exs}"] +] diff --git a/workload_identity_github_actions/.gitignore b/workload_identity_github_actions/.gitignore new file mode 100644 index 00000000..5f62cf72 --- /dev/null +++ b/workload_identity_github_actions/.gitignore @@ -0,0 +1,9 @@ +/_build/ +/cover/ +/deps/ +/doc/ +/.fetch +erl_crash.dump +*.ez +*.tar +/tmp diff --git a/workload_identity_github_actions/CHANGELOG.md b/workload_identity_github_actions/CHANGELOG.md new file mode 100644 index 00000000..825c32f0 --- /dev/null +++ b/workload_identity_github_actions/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/workload_identity_github_actions/LICENSE b/workload_identity_github_actions/LICENSE new file mode 100644 index 00000000..9f65770c --- /dev/null +++ b/workload_identity_github_actions/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 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/workload_identity_github_actions/README.md b/workload_identity_github_actions/README.md new file mode 100644 index 00000000..95cc10e8 --- /dev/null +++ b/workload_identity_github_actions/README.md @@ -0,0 +1,41 @@ +# WorkOS workload identity for GitHub Actions + +Identity token provider for [WorkOS](https://workos.com) workload identity federation on GitHub Actions. It fetches the workflow's OIDC token so the WorkOS SDK can exchange it for a short-lived access token. No API key is stored in the repository. + +This package does not depend on `workos`. It has no dependencies beyond OTP. + +## Installation + +Add it next to `workos` in `mix.exs`: + +```elixir +def deps do + [ + {:workos_workload_identity_github_actions, "~> 0.1"} + ] +end +``` + +## Usage + +The workflow or job must grant the token permission: + +```yaml +permissions: + id-token: write +``` + +```elixir +{:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: + WorkOS.WorkloadIdentity.GitHubActions.github_actions("https://api.workos.com") + ) + +client = WorkOS.Client.new(credentials: credentials) +``` + +`github_actions/1` takes the audience and returns a zero-arity function. Each call reads `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, makes one GET with a 10-second timeout, follows no redirect, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.GitHubActions.Error{}}`. diff --git a/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex b/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex new file mode 100644 index 00000000..cac22a7b --- /dev/null +++ b/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex @@ -0,0 +1,152 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.GitHubActions do + @moduledoc """ + Identity token provider for GitHub Actions. + + `github_actions/1` returns a provider: a zero-arity function that asks the + runner's OIDC endpoint for a token with the given audience and returns + `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.GitHubActions.Error{}}`. + + The workflow or job must grant `permissions: id-token: write`. + + provider = WorkOS.WorkloadIdentity.GitHubActions.github_actions("https://api.workos.com") + + {:ok, credentials} = + WorkOS.WorkloadIdentity.Credentials.start_link( + client_id: "client_...", + environment_id: "environment_...", + token_url: "https://.../oauth2/token", + identity_token_provider: provider + ) + + The provider holds no cache and does not retry; the WorkOS SDK retries it as + part of the token exchange. The token is never logged and never placed in + an error. + """ + + defmodule Error do + @moduledoc """ + Returned when the GitHub Actions OIDC token could not be fetched. + """ + + defexception [:message] + + @type t :: %__MODULE__{message: String.t()} + end + + @url_env "ACTIONS_ID_TOKEN_REQUEST_URL" + @token_env "ACTIONS_ID_TOKEN_REQUEST_TOKEN" + @timeout_ms 10_000 + + @missing_env_message "GitHub Actions did not provide an OIDC token endpoint. " <> + "Add `permissions: id-token: write` to the workflow or job." + + @type provider :: (-> {:ok, String.t()} | {:error, Error.t()}) + + @doc """ + Returns an identity token provider for the given audience. + + The audience is required. The conventional value is `https://api.workos.com`. + `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` are read + on every call of the provider, not when it is built. + """ + @spec github_actions(String.t()) :: provider() + def github_actions(audience) when is_binary(audience) and audience != "" do + fn -> fetch(audience) end + end + + defp fetch(audience) do + with {:ok, url, request_token} <- endpoint(), + {:ok, body} <- get(with_audience(url, audience), request_token) do + parse(body) + end + end + + defp endpoint do + url = System.get_env(@url_env) + request_token = System.get_env(@token_env) + + if url in [nil, ""] or request_token in [nil, ""] do + error(@missing_env_message) + else + {:ok, url, request_token} + end + end + + # The runner's URL already has a query string; the audience is added to it. + defp with_audience(url, audience) do + url + |> URI.parse() + |> URI.append_query("audience=" <> URI.encode(audience, &URI.char_unreserved?/1)) + |> URI.to_string() + end + + defp get(url, request_token) do + headers = [ + {~c"authorization", String.to_charlist("Bearer " <> request_token)}, + {~c"accept", ~c"application/json"} + ] + + http_options = + [timeout: @timeout_ms, connect_timeout: @timeout_ms, autoredirect: false] ++ + ssl_options(url) + + case :httpc.request(:get, {String.to_charlist(url), headers}, http_options, + body_format: :binary + ) do + {:ok, {{_version, 200, _reason}, _headers, body}} -> + {:ok, body} + + {:ok, {{_version, status, _reason}, _headers, _body}} -> + error("The GitHub Actions OIDC token endpoint returned HTTP #{status}.") + + {:error, reason} -> + error("The GitHub Actions OIDC token endpoint could not be reached: #{describe(reason)}.") + end + end + + # Verify the endpoint's certificate against the operating system's trust + # store. OTP releases before 26 do not verify unless told to. + defp ssl_options("https://" <> _rest) do + [ + ssl: [ + verify: :verify_peer, + cacerts: :public_key.cacerts_get(), + depth: 10, + customize_hostname_check: [ + match_fun: :public_key.pkix_verify_hostname_match_fun(:https) + ] + ] + ] + end + + defp ssl_options(_url), do: [] + + defp parse(body) do + case JSON.decode(body) do + {:ok, %{"value" => value}} when is_binary(value) and value != "" -> + {:ok, value} + + _other -> + error( + "The GitHub Actions OIDC token endpoint response had no token in its `value` field." + ) + end + end + + # Only the failure kind is reported. The raw reason is never interpolated, + # so nothing from the request can end up in the message. + defp describe(:timeout), do: "timeout" + + defp describe({:failed_connect, info}) when is_list(info) do + case List.keyfind(info, :inet, 0) || List.keyfind(info, :inet6, 0) do + {_family, _options, reason} when is_atom(reason) -> "connection failed (#{reason})" + _other -> "connection failed" + end + end + + defp describe(_reason), do: "request failed" + + defp error(message), do: {:error, %Error{message: message}} +end diff --git a/workload_identity_github_actions/mix.exs b/workload_identity_github_actions/mix.exs new file mode 100644 index 00000000..150fdbfd --- /dev/null +++ b/workload_identity_github_actions/mix.exs @@ -0,0 +1,65 @@ +defmodule WorkOS.WorkloadIdentity.GitHubActions.MixProject do + use Mix.Project + + @version "0.0.0" + @source_url "https://github.com/workos/workos-elixir" + + def project do + [ + app: :workos_workload_identity_github_actions, + version: @version, + name: "WorkOS workload identity for GitHub Actions", + elixir: "~> 1.18", + elixirc_paths: elixirc_paths(Mix.env()), + start_permanent: Mix.env() == :prod, + description: description(), + package: package(), + docs: docs(), + deps: deps() + ] + end + + # The provider makes its one HTTP request with `:httpc`, so it needs no + # dependencies beyond OTP. + def application do + [extra_applications: [:inets, :ssl, :public_key]] + end + + defp description do + """ + GitHub Actions identity token provider for WorkOS workload identity federation. + """ + end + + defp package do + [ + description: description(), + licenses: ["MIT"], + links: %{ + "GitHub" => @source_url, + "WorkOS" => "https://workos.com" + } + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + defp deps do + [ + {:ex_doc, "~> 0.34", only: :dev, runtime: false}, + {:credo, "~> 1.7", only: [:dev, :test], runtime: false} + ] + end + + defp docs do + [ + extras: [ + "README.md": [title: "Overview"] + ], + main: "readme", + source_url: @source_url, + source_ref: "workos_workload_identity_github_actions-v#{@version}" + ] + end +end diff --git a/workload_identity_github_actions/mix.lock b/workload_identity_github_actions/mix.lock new file mode 100644 index 00000000..b8598071 --- /dev/null +++ b/workload_identity_github_actions/mix.lock @@ -0,0 +1,12 @@ +%{ + "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, + "credo": {:hex, :credo, "1.7.19", "cc52129665fc7c15143d47838fda0f9cd6dac9ceced7bf4da6f85fcbfe64b12a", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "2d8bc95d5a7bb99dd2613621d4f08c6a3575c3fd4b62e6a2b48a100352a557b8"}, + "earmark_parser": {:hex, :earmark_parser, "1.4.46", "67607a0532e810c6f630a515c548d0b24949643f168cc556303bee4cf96105c7", [:mix], [], "hexpm", "9c44636e8a1c68c62f526b2dcd85d941dbbcee7ab82cf64ba06ce28bef8e89f5"}, + "ex_doc": {:hex, :ex_doc, "0.40.4", "66f2e42bf588594d5a8aab31cad87f2ddad09d0da1b1a2f379340ec2c2e497cb", [:mix], [{:earmark_parser, "~> 1.4.46", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "6222b9e423d76584ee34df2c82a5ed72c2d53dc153f7f483ad28b378694186cc"}, + "file_system": {:hex, :file_system, "1.1.1", "31864f4685b0148f25bd3fbef2b1228457c0c89024ad67f7a81a3ffbc0bbad3a", [:mix], [], "hexpm", "7a15ff97dfe526aeefb090a7a9d3d03aa907e100e262a0f8f7746b78f8f87a5d"}, + "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"}, + "makeup": {:hex, :makeup, "1.2.3", "c3ef0ff83acf305384acba0f70bff87d8732502baa1eb3eb081d8c154fbe18f5", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "15970751b7021c2bcd7ed56a54b3def23affd3969fb7c214dffdf28e97ce6f76"}, + "makeup_elixir": {:hex, :makeup_elixir, "1.0.1", "e928a4f984e795e41e3abd27bfc09f51db16ab8ba1aebdba2b3a575437efafc2", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "7284900d412a3e5cfd97fdaed4f5ed389b8f2b4cb49efc0eb3bd10e2febf9507"}, + "makeup_erlang": {:hex, :makeup_erlang, "1.1.0", "835f7e60792e08824cda445639555d7bf1bbbddb1b60b306e33cb6f6db24dc74", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "1cd6780fb1dd1a03979abaed0fe82712b0625118fd5257d3ebbf73f960c73c3c"}, + "nimble_parsec": {:hex, :nimble_parsec, "1.4.2", "8efba0122db06df95bfaa78f791344a89352ba04baedd3849593bfce4d0dc1c6", [:mix], [], "hexpm", "4b21398942dda052b403bbe1da991ccd03a053668d147d53fb8c4e0efe09c973"}, +} diff --git a/workload_identity_github_actions/test/support/test_server.ex b/workload_identity_github_actions/test/support/test_server.ex new file mode 100644 index 00000000..1a71fff8 --- /dev/null +++ b/workload_identity_github_actions/test/support/test_server.ex @@ -0,0 +1,96 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.TestServer do + @moduledoc false + + # A minimal HTTP/1.1 server on a loopback port, for tests only. It answers + # each connection with the next canned response (the last one repeats) and + # sends every request it reads to the process that started it, as + # `{:request, ref, %{method: _, target: _, headers: _, body: _}}`. + # + # It is linked to the test process, so it stops when the test ends. + + @type response :: {pos_integer(), [{String.t(), String.t()}], String.t()} + + @spec start([response()]) :: %{url: String.t(), ref: reference()} + def start(responses) when is_list(responses) and responses != [] do + owner = self() + ref = make_ref() + + spawn_link(fn -> + {:ok, listener} = + :gen_tcp.listen(0, [ + :binary, + packet: :http_bin, + active: false, + reuseaddr: true, + ip: {127, 0, 0, 1} + ]) + + {:ok, port} = :inet.port(listener) + send(owner, {:listening, ref, port}) + accept(listener, responses, owner, ref) + end) + + receive do + {:listening, ^ref, port} -> %{url: "http://127.0.0.1:#{port}", ref: ref} + after + 5_000 -> raise "test server did not start" + end + end + + defp accept(listener, responses, owner, ref) do + {:ok, socket} = :gen_tcp.accept(listener) + send(owner, {:request, ref, read_request(socket)}) + + {response, rest} = next(responses) + :ok = :gen_tcp.send(socket, encode(response)) + :ok = :gen_tcp.close(socket) + + accept(listener, rest, owner, ref) + end + + defp next([response]), do: {response, [response]} + defp next([response | rest]), do: {response, rest} + + defp read_request(socket) do + {:ok, {:http_request, method, {:abs_path, target}, _version}} = + :gen_tcp.recv(socket, 0, 5_000) + + headers = read_headers(socket, %{}) + length = headers |> Map.get("content-length", "0") |> String.to_integer() + + %{ + method: to_string(method), + target: target, + headers: headers, + body: read_body(socket, length) + } + end + + defp read_headers(socket, headers) do + case :gen_tcp.recv(socket, 0, 5_000) do + {:ok, {:http_header, _, name, _, value}} -> + read_headers(socket, Map.put(headers, name |> to_string() |> String.downcase(), value)) + + {:ok, :http_eoh} -> + headers + end + end + + defp read_body(_socket, 0), do: "" + + defp read_body(socket, length) do + :ok = :inet.setopts(socket, packet: :raw) + {:ok, body} = :gen_tcp.recv(socket, length, 5_000) + body + end + + defp encode({status, headers, body}) do + head = + [{"content-length", Integer.to_string(byte_size(body))}, {"connection", "close"} | headers] + |> Enum.map(fn {name, value} -> [name, ": ", value, "\r\n"] end) + + ["HTTP/1.1 ", Integer.to_string(status), " Mock\r\n", head, "\r\n", body] + end +end diff --git a/workload_identity_github_actions/test/test_helper.exs b/workload_identity_github_actions/test/test_helper.exs new file mode 100644 index 00000000..3416380c --- /dev/null +++ b/workload_identity_github_actions/test/test_helper.exs @@ -0,0 +1,3 @@ +# @oagen-ignore-file + +ExUnit.start() diff --git a/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs b/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs new file mode 100644 index 00000000..d6d04c5d --- /dev/null +++ b/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs @@ -0,0 +1,149 @@ +# @oagen-ignore-file + +defmodule WorkOS.WorkloadIdentity.GitHubActionsTest do + # The provider reads process-wide environment variables, so these tests + # cannot run concurrently. + use ExUnit.Case, async: false + + alias WorkOS.WorkloadIdentity.GitHubActions + alias WorkOS.WorkloadIdentity.GitHubActions.Error + alias WorkOS.WorkloadIdentity.TestServer + + @url_env "ACTIONS_ID_TOKEN_REQUEST_URL" + @token_env "ACTIONS_ID_TOKEN_REQUEST_TOKEN" + @audience "https://api.workos.com" + + setup do + previous = Map.new([@url_env, @token_env], &{&1, System.get_env(&1)}) + + on_exit(fn -> + Enum.each(previous, fn + {name, nil} -> System.delete_env(name) + {name, value} -> System.put_env(name, value) + end) + end) + + System.delete_env(@url_env) + System.delete_env(@token_env) + :ok + end + + defp json(value), do: {200, [{"content-type", "application/json"}], JSON.encode!(value)} + + defp configure(server, token \\ "gha-request-token") do + System.put_env(@url_env, server.url <> "/token?api-version=2.0") + System.put_env(@token_env, token) + end + + test "WIF-GHA-01 GETs the request URL with the encoded audience appended and returns .value" do + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + configure(server) + + assert GitHubActions.github_actions(@audience).() == {:ok, "gha-jwt"} + + ref = server.ref + assert_receive {:request, ^ref, request} + assert request.method == "GET" + assert request.target == "/token?api-version=2.0&audience=https%3A%2F%2Fapi.workos.com" + assert request.headers["authorization"] == "Bearer gha-request-token" + assert request.headers["accept"] == "application/json" + refute_receive {:request, ^ref, _second} + end + + test "WIF-GHA-01 reads the environment on every call, not when the provider is built" do + provider = GitHubActions.github_actions(@audience) + + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + configure(server) + + assert provider.() == {:ok, "gha-jwt"} + end + + test "WIF-GHA-01 percent-encodes an audience that has reserved characters" do + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + configure(server) + + assert GitHubActions.github_actions("urn:workos:api/v1 test").() == {:ok, "gha-jwt"} + + ref = server.ref + assert_receive {:request, ^ref, request} + assert request.target == "/token?api-version=2.0&audience=urn%3Aworkos%3Aapi%2Fv1%20test" + end + + test "WIF-GHA-02 a missing request URL fails with the permissions hint and makes no request" do + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + System.put_env(@token_env, "gha-request-token") + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + assert message =~ "permissions: id-token: write" + + ref = server.ref + refute_receive {:request, ^ref, _request} + end + + test "WIF-GHA-02 a missing request token fails with the permissions hint and makes no request" do + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + System.put_env(@url_env, server.url <> "/token?api-version=2.0") + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + assert message =~ "permissions: id-token: write" + + ref = server.ref + refute_receive {:request, ^ref, _request} + end + + test "WIF-GHA-02 an empty variable counts as missing" do + System.put_env(@url_env, "") + System.put_env(@token_env, "") + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + assert message =~ "permissions: id-token: write" + end + + test "a non-200 status is an error that names the status and not the request token" do + server = TestServer.start([{404, [], "not found"}]) + configure(server, "SECRET-REQUEST-TOKEN") + + assert {:error, %Error{message: message} = error} = GitHubActions.github_actions(@audience).() + assert message =~ "404" + refute message =~ "SECRET-REQUEST-TOKEN" + refute inspect(error) =~ "SECRET-REQUEST-TOKEN" + end + + test "a response with no value, an empty value or a body that is not JSON is an error" do + for response <- [json(%{}), json(%{"value" => ""}), {200, [], ""}, {200, [], "not json"}] do + server = TestServer.start([response]) + configure(server) + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + assert message =~ "value" + end + end + + test "a redirect is not followed" do + elsewhere = TestServer.start([json(%{"value" => "gha-jwt"})]) + server = TestServer.start([{302, [{"location", elsewhere.url <> "/token"}], ""}]) + configure(server) + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + assert message =~ "302" + + ref = elsewhere.ref + refute_receive {:request, ^ref, _request} + end + + test "a connection failure is an error that does not carry the request token" do + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + # Port 1 on loopback refuses connections. + System.put_env(@url_env, String.replace(server.url, ~r/:\d+$/, ":1") <> "/token") + System.put_env(@token_env, "SECRET-REQUEST-TOKEN") + + assert {:error, %Error{message: message} = error} = GitHubActions.github_actions(@audience).() + assert message =~ "could not be reached" + refute inspect(error) =~ "SECRET-REQUEST-TOKEN" + end + + test "the audience is required" do + assert_raise FunctionClauseError, fn -> GitHubActions.github_actions("") end + end +end From 36a76342e0a5ad7cd3d06f476929299fcd5590cb Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 07:49:55 -0800 Subject: [PATCH 02/15] ci(release): keep provider-only commits out of SDK releases release-please gives the root package every commit in the repo, so a fix that only touches a provider package would also open an SDK release PR and appear in the SDK changelog. `exclude-paths` on the root entry drops a commit from the SDK release when every file it touches is under one of the three provider directories. A commit that touches a provider and anything outside it still counts toward the SDK. Spec: docs/ideation/wif-backend-sdks/spec-phase-8.md --- release-please-config.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/release-please-config.json b/release-please-config.json index d48540c6..34d0075d 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -4,7 +4,12 @@ ".": { "release-type": "elixir", "bump-minor-pre-major": true, - "bump-patch-for-minor-pre-major": true + "bump-patch-for-minor-pre-major": true, + "exclude-paths": [ + "workload_identity_github_actions", + "workload_identity_gcp", + "workload_identity_aws" + ] }, "workload_identity_github_actions": { "release-type": "elixir", From 737f69c0f54827e2678661a5c0ba48431a84530d Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 11:42:54 -0800 Subject: [PATCH 03/15] fix(workload-identity): send the GCP metadata request without a proxy The Google Cloud provider made its request on the default :httpc profile, which is shared with the application. When the application had given :httpc a proxy with :httpc.set_options/1, the request for an identity token went to that proxy. The metadata server exists only inside the workload's own VM or container, so a proxy cannot reach it: the request failed, or the provider returned whatever the proxy answered as the token. The provider now starts an :httpc profile of its own on first use and sends the request through it. Nothing sets a proxy on that profile. A test gives the default profile a proxy and checks that it is never contacted. Spec: docs/ideation/wif-backend-sdks/spec-phase-8.md --- workload_identity_gcp/README.md | 2 +- .../lib/workos/workload_identity/gcp.ex | 39 ++++++++++++++++--- .../workos/workload_identity/gcp_test.exs | 31 +++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) diff --git a/workload_identity_gcp/README.md b/workload_identity_gcp/README.md index b5286f1f..555086db 100644 --- a/workload_identity_gcp/README.md +++ b/workload_identity_gcp/README.md @@ -32,4 +32,4 @@ end client = WorkOS.Client.new(credentials: credentials) ``` -`gcp_metadata/1` takes the audience and returns a zero-arity function. Each call makes one GET to the metadata server with a 10-second timeout, follows no redirect, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.GCP.Error{}}`. +`gcp_metadata/1` takes the audience and returns a zero-arity function. Each call makes one GET to the metadata server with a 10-second timeout, follows no redirect, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.GCP.Error{}}`. The request never goes through a proxy, even when the application has given `:httpc` one: the metadata server exists only inside the workload's own VM or container, so a proxy cannot reach it. diff --git a/workload_identity_gcp/lib/workos/workload_identity/gcp.ex b/workload_identity_gcp/lib/workos/workload_identity/gcp.ex index 3be5c496..d72c7640 100644 --- a/workload_identity_gcp/lib/workos/workload_identity/gcp.ex +++ b/workload_identity_gcp/lib/workos/workload_identity/gcp.ex @@ -25,6 +25,9 @@ defmodule WorkOS.WorkloadIdentity.GCP do The provider holds no cache and does not retry; the WorkOS SDK retries it as part of the token exchange. The token is never logged and never placed in an error. + + The request to the metadata server never goes through a proxy, even when + the application has given `:httpc` one with `:httpc.set_options/1`. """ defmodule Error do @@ -41,6 +44,14 @@ defmodule WorkOS.WorkloadIdentity.GCP do @identity_path "/computeMetadata/v1/instance/service-accounts/default/identity" @timeout_ms 10_000 + # The provider's own `:httpc` profile. The default profile is shared with + # the application, which may have given it a proxy (`:httpc.set_options/1`). + # 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. Nothing ever sets a proxy on this + # profile, so the request always goes direct. + @httpc_profile :workos_workload_identity_gcp + @type provider :: (-> {:ok, String.t()} | {:error, Error.t()}) @doc """ @@ -68,12 +79,17 @@ defmodule WorkOS.WorkloadIdentity.GCP do headers = [{~c"metadata-flavor", ~c"Google"}] http_options = [timeout: @timeout_ms, connect_timeout: @timeout_ms, autoredirect: false] - case :httpc.request(:get, {String.to_charlist(url), headers}, http_options, - body_format: :binary - ) do - {:ok, {{_version, 200, _reason}, _headers, body}} -> - token(body) - + with :ok <- ensure_profile(), + {:ok, {{_version, 200, _reason}, _headers, body}} <- + :httpc.request( + :get, + {String.to_charlist(url), headers}, + http_options, + [body_format: :binary], + @httpc_profile + ) do + token(body) + else {:ok, {{_version, status, _reason}, _headers, _body}} -> error("The Google Cloud metadata server returned HTTP #{status}.") @@ -82,6 +98,16 @@ defmodule WorkOS.WorkloadIdentity.GCP do end end + # Starts the profile on first use. It runs under `:inets`, so it outlives + # the calling process; later calls find it already started. + defp ensure_profile do + case :inets.start(:httpc, profile: @httpc_profile) do + {:ok, _pid} -> :ok + {:error, {:already_started, _pid}} -> :ok + {:error, _reason} -> {:error, :profile_not_started} + end + end + defp token(body) do case String.trim(body) do "" -> error("The Google Cloud metadata server returned an empty identity token.") @@ -99,6 +125,7 @@ defmodule WorkOS.WorkloadIdentity.GCP do end end + defp describe(:profile_not_started), do: "the HTTP client did not start" defp describe(_reason), do: "request failed" defp error(message), do: {:error, %Error{message: message}} diff --git a/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs index af6f2fdb..726d177a 100644 --- a/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs +++ b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs @@ -77,6 +77,37 @@ defmodule WorkOS.WorkloadIdentity.GCPTest do assert message =~ "could not be reached" end + test "the request never goes through a proxy the application gave :httpc" do + # The default :httpc profile is shared with the application. Give it a + # proxy: a listener that reports any connection and closes it. + {:ok, proxy} = :gen_tcp.listen(0, [:binary, active: false, ip: {127, 0, 0, 1}]) + {:ok, proxy_port} = :inet.port(proxy) + test = self() + + spawn_link(fn -> + with {:ok, socket} <- :gen_tcp.accept(proxy) do + send(test, :proxy_contacted) + :gen_tcp.close(socket) + end + end) + + :ok = :httpc.set_options(proxy: {{~c"127.0.0.1", proxy_port}, []}) + + # `:httpc` cannot take a proxy off a profile again, so restart the profile. + on_exit(fn -> + :ok = :inets.stop(:httpc, :default) + {:ok, _pid} = :inets.start(:httpc, profile: :default) + end) + + server = TestServer.start([{200, [], "gcp-jwt"}]) + + assert provider(server).() == {:ok, "gcp-jwt"} + + ref = server.ref + assert_receive {:request, ^ref, _request} + refute_receive :proxy_contacted + end + test "the audience is required" do assert_raise FunctionClauseError, fn -> GCP.gcp_metadata("") end end From 83c21736db6177aef95a2e1f645cafd578458c44 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 12:42:37 -0800 Subject: [PATCH 04/15] test(workload-identity): name the GCP proxy test for WIF-GCP-03 The rule that the GCP metadata request never goes through a proxy is now conformance case WIF-GCP-03. The conformance check reads case IDs from test names, so the existing test for the rule now carries the ID. No behavior changes. Spec: docs/ideation/wif-backend-sdks/spec-phase-8.md --- .../test/workos/workload_identity/gcp_test.exs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs index 726d177a..43026a7a 100644 --- a/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs +++ b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs @@ -77,7 +77,7 @@ defmodule WorkOS.WorkloadIdentity.GCPTest do assert message =~ "could not be reached" end - test "the request never goes through a proxy the application gave :httpc" do + test "WIF-GCP-03 the request never goes through a proxy the application gave :httpc" do # The default :httpc profile is shared with the application. Give it a # proxy: a listener that reports any connection and closes it. {:ok, proxy} = :gen_tcp.listen(0, [:binary, active: false, ip: {127, 0, 0, 1}]) From 9c4b765d2df6efb01e82b6543f1c9f39becbd4f6 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Fri, 13 Nov 2026 13:48:56 -0800 Subject: [PATCH 05/15] fix(workload-identity): make environment ID optional and align error hints with the server A reading of the server code on 2026-11-13 showed three things the SDK had slightly wrong. The server binds a workload identity client to exactly one environment and takes the environment from that binding, so the `x-url-environment-id` header selects nothing. `:environment_id` is now optional: starting credentials without it (and without `WORKOS_ENVIRONMENT_ID`) is no longer an `invalid_configuration` error, and the header is sent only when an environment ID is set. An empty string counts as not set. `WORKOS_ENVIRONMENT_ID` still fills the option when it is omitted, and an explicit value still wins. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. The hints for `invalid_grant`, `invalid_target`, `invalid_client` and `unauthorized_client` are reworded to match what the server returns each code for. The other hints are unchanged. The tests use the real scope name, `orgs:write`. WIF-02 gains part (b): with no environment ID the API request carries the access token and no environment header. The README says that the server accepts an identity token for one exchange, and what that means for `token_file/1` and `token_env/1`. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 6, 7, 8) --- README.md | 4 +++ lib/workos/workload_identity/credentials.ex | 24 +++++++++---- lib/workos/workload_identity_error.ex | 18 +++++----- test/workos/workload_identity_test.exs | 37 ++++++++++++++++++--- 4 files changed, 63 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index bcd7725f..cc565b84 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,8 @@ client = WorkOS.Client.new(credentials: credentials) `:client_id`, `:token_url`, `:environment_id` and `:scope` fall back to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL`, `WORKOS_ENVIRONMENT_ID` and `WORKOS_WIF_SCOPE` environment variables. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. +`:environment_id` is optional. The server binds a workload identity client to exactly one environment, so the `x-url-environment-id` header selects nothing, and the SDK sends it only when an environment ID is set. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. + In an application, supervise the process under a name of your choosing and build clients from the name: ```elixir @@ -108,6 +110,8 @@ provider = WorkOS.WorkloadIdentity.token_env("MY_IDENTITY_TOKEN") provider = fn -> MyApp.Identity.fetch_token() end ``` +The server accepts an identity token for one exchange. `token_file/1` and `token_env/1` return whatever the file or variable holds, and the SDK exchanges again about every four minutes. If the file or variable still holds the same token at the next exchange, that exchange fails with `invalid_grant`. So use these two for a source that something rewrites before each exchange, or for a job shorter than five minutes. The platform providers (GitHub Actions, GCP, AWS) fetch a new token every time. + When the exchange fails, API functions return `{:error, %WorkOS.WorkloadIdentityError{}}`. Its `:code` is the OAuth error code from the token endpoint (for example `"invalid_grant"`), and its `:hint` says what to check. ## SDK Versioning diff --git a/lib/workos/workload_identity/credentials.ex b/lib/workos/workload_identity/credentials.ex index aadc7575..abddf19d 100644 --- a/lib/workos/workload_identity/credentials.ex +++ b/lib/workos/workload_identity/credentials.ex @@ -39,8 +39,13 @@ defmodule WorkOS.WorkloadIdentity.Credentials do `WORKOS_CLIENT_ID` environment variable. * `:token_url` — the exchange endpoint. Falls back to `WORKOS_WIF_TOKEN_URL`. There is no built-in default. - * `:environment_id` — sent as the `x-url-environment-id` header on every - API request. Falls back to `WORKOS_ENVIRONMENT_ID`. + * `:environment_id` — optional. Falls back to `WORKOS_ENVIRONMENT_ID`. + When set, it is sent as the `x-url-environment-id` header on every API + request; when not set, the header is not sent. An empty string counts + as not set. The server binds a workload identity client to exactly one + environment, so the header selects nothing. Setting it is a safety + check: a value that names a different environment gets + `403 environment_mismatch`. * `:resource` — the `resource` form field. Defaults to `https://api.workos.com`. * `:scope` — the `scope` form field. Falls back to `WORKOS_WIF_SCOPE`; @@ -108,7 +113,7 @@ defmodule WorkOS.WorkloadIdentity.Credentials do @doc """ Returns the snapshot to send one HTTP attempt with: the access token as a - bearer header, plus the environment header. + bearer header, plus the environment header when an environment ID is set. Waits for a token exchange when no fresh token is cached, for at most `timeout` milliseconds. Giving up does not stop the exchange. @@ -164,13 +169,14 @@ defmodule WorkOS.WorkloadIdentity.Credentials do with {:ok, client_id} <- required(opts, :client_id, @client_id_env), {:ok, token_url} <- required(opts, :token_url, @token_url_env), - {:ok, environment_id} <- required(opts, :environment_id, @environment_id_env), {:ok, provider} <- provider(opts[:identity_token_provider]) do {:ok, %{ client_id: client_id, token_url: token_url, - environment_id: environment_id, + # Optional: nil when neither the option nor the variable is set. + environment_id: + present(opts[:environment_id]) || present(System.get_env(@environment_id_env)), resource: present(opts[:resource]) || @default_resource, scope: present(opts[:scope]) || present(System.get_env(@scope_env)), identity_token_provider: provider, @@ -297,14 +303,18 @@ defmodule WorkOS.WorkloadIdentity.Credentials do defp snapshot(state) do %CredentialSnapshot{ headers: [ - {"authorization", "Bearer " <> state.token.()}, - {@environment_header, state.config.environment_id} + {"authorization", "Bearer " <> state.token.()} + | environment_headers(state.config.environment_id) ], generation: state.generation, recoverable: true } end + # The environment header is sent only when an environment ID is set. + defp environment_headers(nil), do: [] + defp environment_headers(environment_id), do: [{@environment_header, environment_id}] + # -- shared exchange ---------------------------------------------------------- defp join_or_start_exchange(%{inflight: nil, config: config} = state) do diff --git a/lib/workos/workload_identity_error.ex b/lib/workos/workload_identity_error.ex index cfc1818c..d104aa36 100644 --- a/lib/workos/workload_identity_error.ex +++ b/lib/workos/workload_identity_error.ex @@ -33,17 +33,19 @@ defmodule WorkOS.WorkloadIdentityError do # codes, so change it here and nowhere else. @hints %{ "invalid_grant" => - "The identity token did not match a trust rule for this application, or the token has " <> - "expired. Check the issuer, audience and subject claims against the trust rule.", + "The identity token was not accepted. Check its issuer, audience and subject claims " <> + "against the trust rule, and that it has not expired. A token that was already " <> + "exchanged is also refused: each exchange needs a new identity token.", "invalid_target" => - "The resource or audience is wrong. The trust rule's audience must match the audience " <> - "the identity token was requested with, and the resource must be registered for the " <> - "environment.", + "The resource is not one the token endpoint accepts. Leave the resource unset to use " <> + "the default, https://api.workos.com.", "invalid_client" => - "Check that the client ID is the M2M application that has the trust rule.", + "The client ID is unknown, or the application has no enabled trust rule. Check that " <> + "the client ID is the M2M application that has the trust rule.", "unauthorized_client" => - "This application is not allowed to use workload identity federation. Check that the " <> - "feature is enabled for the environment and that the application has a trust rule.", + "This application cannot use workload identity federation. Check that the feature is " <> + "enabled for your team and that the application is bound to a non-production " <> + "environment.", "invalid_scope" => "The requested scope is not allowed for this application. Fix the scope or leave it unset.", "invalid_request" => diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index d27f42c1..aa7c2916 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -264,15 +264,15 @@ defmodule WorkOS.WorkloadIdentityTest do scoped = token_endpoint() assert {:ok, _} = - scoped |> start_credentials(scope: "organizations:write") |> client(api()) |> get() + scoped |> start_credentials(scope: "orgs:write") |> client(api()) |> get() assert [exchange] = requests(scoped) - assert exchange.form["scope"] == "organizations:write" + assert exchange.form["scope"] == "orgs:write" refute Map.has_key?(exchange.form, "client_secret") assert exchange.authorization == nil end - test "WIF-02 the API request carries the access token and the environment header" do + test "WIF-02 (a) the API request carries the access token and the environment header" do api = api() assert {:ok, _} = token_endpoint() |> start_credentials() |> client(api) |> get() @@ -281,6 +281,34 @@ defmodule WorkOS.WorkloadIdentityTest do assert request.environment_id == "environment_wif_test" end + test "WIF-02 (b) with no environment ID the API request carries no environment header" do + # The setup removed WORKOS_ENVIRONMENT_ID and puts it back afterwards. + assert System.get_env("WORKOS_ENVIRONMENT_ID") == nil + + api = api() + options = token_endpoint() |> credentials_options([]) |> Keyword.delete(:environment_id) + + assert {:ok, credentials} = Credentials.start_link(options) + assert {:ok, _} = credentials |> client(api) |> get() + + assert [request] = requests(api) + assert request.authorization == "Bearer access-1" + # nil means the header was absent, not present and empty. + assert request.environment_id == nil + end + + test "WIF-02 an empty environment ID counts as not set" do + System.put_env("WORKOS_ENVIRONMENT_ID", "") + api = api() + + assert {:ok, _} = + token_endpoint() |> start_credentials(environment_id: "") |> client(api) |> get() + + assert [request] = requests(api) + assert request.authorization == "Bearer access-1" + assert request.environment_id == nil + end + # -- cache and refresh -------------------------------------------------------- test "WIF-03 a second request within the token lifetime reuses the cached token" do @@ -941,8 +969,7 @@ defmodule WorkOS.WorkloadIdentityTest do test "WIF-20 every required option is checked when the credentials are constructed" do for {key, variable} <- [ client_id: "WORKOS_CLIENT_ID", - token_url: "WORKOS_WIF_TOKEN_URL", - environment_id: "WORKOS_ENVIRONMENT_ID" + token_url: "WORKOS_WIF_TOKEN_URL" ] do options = token_endpoint() |> credentials_options([]) |> Keyword.delete(key) From 46809b7eb4327e81d2b09c859d8b288a2717bd2e Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sat, 14 Nov 2026 11:19:49 -0800 Subject: [PATCH 06/15] fix(workload-identity): stop reading WORKOS_ENVIRONMENT_ID and correct the README examples `:environment_id` now comes only from the caller's code. The SDK no longer reads `WORKOS_ENVIRONMENT_ID`: left out, `nil` or an empty string all mean "not set", so no `x-url-environment-id` header is sent and nothing is an error. The header is an optional safety check, and a variable left in the environment could turn it into a `403 environment_mismatch` with no line of code to point at. The variable was never on `main`, so removing it breaks no one. `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` are unchanged. WIF-02 (b) now sets the variable and checks that the API request still carries no environment header. WIF-22 (c) and (d) no longer involve the environment ID. The README and the module docs are corrected: - The `token_file/1` examples no longer use a Kubernetes service account token path, which the server refuses. They name a file that another process writes, such as a sidecar or an earlier CI step. - `token_file/1` and `token_env/1` suit a job shorter than four minutes, not five: the SDK exchanges again at four. - The environment ID is described as optional and set in code. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 9, 10) --- README.md | 9 ++++--- lib/workos/workload_identity.ex | 8 +++--- lib/workos/workload_identity/credentials.ex | 22 ++++++++-------- test/workos/workload_identity_test.exs | 28 ++++++++++----------- 4 files changed, 34 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index cc565b84..c677eab3 100644 --- a/README.md +++ b/README.md @@ -63,9 +63,9 @@ Start a credentials process and pass it to the client: client = WorkOS.Client.new(credentials: credentials) ``` -`:client_id`, `:token_url`, `:environment_id` and `:scope` fall back to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL`, `WORKOS_ENVIRONMENT_ID` and `WORKOS_WIF_SCOPE` environment variables. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. +`:client_id`, `:token_url` and `:scope` fall back to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` environment variables. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. -`:environment_id` is optional. The server binds a workload identity client to exactly one environment, so the `x-url-environment-id` header selects nothing, and the SDK sends it only when an environment ID is set. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. +`:environment_id` is optional, and it is set only in code: the SDK reads no environment variable for it. The server binds a workload identity client to exactly one environment, so the `x-url-environment-id` header selects nothing, and the SDK sends it only when an environment ID is set. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. In an application, supervise the process under a name of your choosing and build clients from the name: @@ -105,12 +105,13 @@ The argument is the audience the identity token is requested for. No package is needed when the token is already in a file or an environment variable, or when you fetch it yourself. A provider is any zero-arity function (or `{module, function, args}` tuple) that returns `{:ok, token}` or `{:error, reason}`: ```elixir -provider = WorkOS.WorkloadIdentity.token_file("/var/run/secrets/tokens/workos") +# A file that another process writes, such as a sidecar or an earlier CI step that fetches a new token. +provider = WorkOS.WorkloadIdentity.token_file("/run/workos/identity-token") provider = WorkOS.WorkloadIdentity.token_env("MY_IDENTITY_TOKEN") provider = fn -> MyApp.Identity.fetch_token() end ``` -The server accepts an identity token for one exchange. `token_file/1` and `token_env/1` return whatever the file or variable holds, and the SDK exchanges again about every four minutes. If the file or variable still holds the same token at the next exchange, that exchange fails with `invalid_grant`. So use these two for a source that something rewrites before each exchange, or for a job shorter than five minutes. The platform providers (GitHub Actions, GCP, AWS) fetch a new token every time. +The server accepts an identity token for one exchange. `token_file/1` and `token_env/1` return whatever the file or variable holds, and the SDK exchanges again about every four minutes. If the file or variable still holds the same token at the next exchange, that exchange fails with `invalid_grant`. So use these two for a source that something rewrites before each exchange, or for a job shorter than four minutes. The platform providers (GitHub Actions, GCP, AWS) fetch a new token every time. When the exchange fails, API functions return `{:error, %WorkOS.WorkloadIdentityError{}}`. Its `:code` is the OAuth error code from the token endpoint (for example `"invalid_grant"`), and its `:hint` says what to check. diff --git a/lib/workos/workload_identity.ex b/lib/workos/workload_identity.ex index f07f8b26..eda84644 100644 --- a/lib/workos/workload_identity.ex +++ b/lib/workos/workload_identity.ex @@ -15,7 +15,7 @@ defmodule WorkOS.WorkloadIdentity do that returns `{:ok, token}` or `{:error, reason}`. It is called again for every exchange attempt, so it needs no cache and no retries of its own. - This module has the two providers that read a token the platform has + This module has the two providers that read a token another process has already written somewhere: `token_file/1` and `token_env/1`. Any function of the same shape works as a custom provider: @@ -33,12 +33,14 @@ defmodule WorkOS.WorkloadIdentity do (-> {:ok, String.t()} | {:error, term()}) | {module(), atom(), [term()]} @doc """ - Returns a provider that reads the token from a file. + Returns a provider that reads the token from a file: one that another + process writes, such as a sidecar or an earlier CI step that fetches a new + token. The file is read again on every call, so a rotated token is picked up. Surrounding whitespace is trimmed. A missing or empty file is an error. - WorkOS.WorkloadIdentity.token_file("/var/run/secrets/tokens/workos") + WorkOS.WorkloadIdentity.token_file("/run/workos/identity-token") """ @spec token_file(Path.t()) :: (-> {:ok, String.t()} | {:error, String.t()}) def token_file(path) when is_binary(path), do: fn -> read_file(path) end diff --git a/lib/workos/workload_identity/credentials.ex b/lib/workos/workload_identity/credentials.ex index abddf19d..ff1982f7 100644 --- a/lib/workos/workload_identity/credentials.ex +++ b/lib/workos/workload_identity/credentials.ex @@ -14,7 +14,7 @@ defmodule WorkOS.WorkloadIdentity.Credentials do client_id: "client_...", environment_id: "environment_...", token_url: "https://.../oauth2/token", - identity_token_provider: WorkOS.WorkloadIdentity.token_file("/var/run/secrets/token") + identity_token_provider: WorkOS.WorkloadIdentity.token_file("/run/workos/identity-token") ) client = WorkOS.Client.new(credentials: credentials) @@ -39,13 +39,13 @@ defmodule WorkOS.WorkloadIdentity.Credentials do `WORKOS_CLIENT_ID` environment variable. * `:token_url` — the exchange endpoint. Falls back to `WORKOS_WIF_TOKEN_URL`. There is no built-in default. - * `:environment_id` — optional. Falls back to `WORKOS_ENVIRONMENT_ID`. - When set, it is sent as the `x-url-environment-id` header on every API - request; when not set, the header is not sent. An empty string counts - as not set. The server binds a workload identity client to exactly one - environment, so the header selects nothing. Setting it is a safety - check: a value that names a different environment gets - `403 environment_mismatch`. + * `:environment_id` — optional, and set only here: no environment + variable is read for it. When set, it is sent as the + `x-url-environment-id` header on every API request. When it is left + out, `nil` or an empty string, the header is not sent. The server binds + a workload identity client to exactly one environment, so the header + selects nothing. Setting it is a safety check: a value that names a + different environment gets `403 environment_mismatch`. * `:resource` — the `resource` form field. Defaults to `https://api.workos.com`. * `:scope` — the `scope` form field. Falls back to `WORKOS_WIF_SCOPE`; @@ -94,7 +94,6 @@ defmodule WorkOS.WorkloadIdentity.Credentials do @client_id_env "WORKOS_CLIENT_ID" @token_url_env "WORKOS_WIF_TOKEN_URL" @scope_env "WORKOS_WIF_SCOPE" - @environment_id_env "WORKOS_ENVIRONMENT_ID" # -- public API ------------------------------------------------------------- @@ -174,9 +173,8 @@ defmodule WorkOS.WorkloadIdentity.Credentials do %{ client_id: client_id, token_url: token_url, - # Optional: nil when neither the option nor the variable is set. - environment_id: - present(opts[:environment_id]) || present(System.get_env(@environment_id_env)), + # Optional, and only from the caller: no environment variable is read. + environment_id: present(opts[:environment_id]), resource: present(opts[:resource]) || @default_resource, scope: present(opts[:scope]) || present(System.get_env(@scope_env)), identity_token_provider: provider, diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index aa7c2916..14f66319 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -282,8 +282,8 @@ defmodule WorkOS.WorkloadIdentityTest do end test "WIF-02 (b) with no environment ID the API request carries no environment header" do - # The setup removed WORKOS_ENVIRONMENT_ID and puts it back afterwards. - assert System.get_env("WORKOS_ENVIRONMENT_ID") == nil + # The SDK does not read this variable. The setup puts it back afterwards. + System.put_env("WORKOS_ENVIRONMENT_ID", "environment_env") api = api() options = token_endpoint() |> credentials_options([]) |> Keyword.delete(:environment_id) @@ -297,16 +297,20 @@ defmodule WorkOS.WorkloadIdentityTest do assert request.environment_id == nil end - test "WIF-02 an empty environment ID counts as not set" do - System.put_env("WORKOS_ENVIRONMENT_ID", "") - api = api() + test "WIF-02 a nil or empty environment ID counts as not set" do + for environment_id <- [nil, ""] do + api = api() - assert {:ok, _} = - token_endpoint() |> start_credentials(environment_id: "") |> client(api) |> get() + assert {:ok, _} = + token_endpoint() + |> start_credentials(environment_id: environment_id) + |> client(api) + |> get() - assert [request] = requests(api) - assert request.authorization == "Bearer access-1" - assert request.environment_id == nil + assert [request] = requests(api) + assert request.authorization == "Bearer access-1" + assert request.environment_id == nil + end end # -- cache and refresh -------------------------------------------------------- @@ -1110,7 +1114,6 @@ defmodule WorkOS.WorkloadIdentityTest do System.put_env("WORKOS_CLIENT_ID", "client_env") System.put_env("WORKOS_WIF_TOKEN_URL", "https://env.wif.test/oauth2/token") System.put_env("WORKOS_WIF_SCOPE", "scope_env") - System.put_env("WORKOS_ENVIRONMENT_ID", "environment_env") provider = fn -> {:ok, "assertion-1"} end @@ -1131,7 +1134,6 @@ defmodule WorkOS.WorkloadIdentityTest do assert exchange.path == "/oauth2/token" assert exchange.form["client_id"] == "client_env" assert exchange.form["scope"] == "scope_env" - assert [%{environment_id: "environment_env"}] = requests(api) # (d) The same environment, with explicit values. token_endpoint = token_endpoint() @@ -1142,7 +1144,6 @@ defmodule WorkOS.WorkloadIdentityTest do identity_token_provider: provider, client_id: "client_explicit", scope: "scope_explicit", - environment_id: "environment_explicit", req_options: [plug: token_plug(token_endpoint)] ) @@ -1151,7 +1152,6 @@ defmodule WorkOS.WorkloadIdentityTest do assert [exchange] = requests(token_endpoint) assert exchange.form["client_id"] == "client_explicit" assert exchange.form["scope"] == "scope_explicit" - assert [%{environment_id: "environment_explicit"}] = requests(api) end # -- redirects ---------------------------------------------------------------------- From 0942657614485ad5d1cfc4b7a894643408537bdb Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sat, 14 Nov 2026 11:27:18 -0800 Subject: [PATCH 07/15] fix(workload-identity): stop reading WORKOS_WIF_TOKEN_URL and WORKOS_WIF_SCOPE `WORKOS_CLIENT_ID` is now the only environment variable the credentials read. `:token_url` is required and comes only from the caller's code. Left out, `nil` or an empty string is an `invalid_configuration` error when the credentials start, with the description `token_url is required`. `WORKOS_WIF_TOKEN_URL` in the environment is ignored. `:scope` is optional and comes only from the caller's code. Not set, `nil` or an empty string means no `scope` field in the exchange. `WORKOS_WIF_SCOPE` is ignored. With no scope the token carries every scope the application holds, so a variable left in the environment would change permissions with no line of code to point at. `:client_id` is unchanged: it still defaults from `WORKOS_CLIENT_ID`, and its error still names that variable. Neither variable was ever on `main`, so removing them breaks no one. WIF-22 now sets all three variables and checks that only the client ID is taken from the environment, that an explicit client ID wins, and that a missing token URL is an error. The README and the module docs name `WORKOS_CLIENT_ID` as the only variable, and the supervised examples pass the token URL in code. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decision 11) --- README.md | 7 ++- lib/workos/workload_identity/credentials.ex | 30 ++++++---- test/workos/workload_identity_test.exs | 61 ++++++++++++++++----- 3 files changed, 71 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index c677eab3..6f66cc59 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ Start a credentials process and pass it to the client: client = WorkOS.Client.new(credentials: credentials) ``` -`:client_id`, `:token_url` and `:scope` fall back to the `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` environment variables. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. +`:client_id` falls back to the `WORKOS_CLIENT_ID` environment variable. That is the only variable the credentials read: `:token_url` (required) and `:scope` (optional) are set only in code. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. `:environment_id` is optional, and it is set only in code: the SDK reads no environment variable for it. The server binds a workload identity client to exactly one environment, so the `x-url-environment-id` header selects nothing, and the SDK sends it only when an environment ID is set. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. @@ -71,7 +71,10 @@ In an application, supervise the process under a name of your choosing and build ```elixir children = [ - {WorkOS.WorkloadIdentity.Credentials, name: MyApp.WorkOSCredentials, identity_token_provider: provider} + {WorkOS.WorkloadIdentity.Credentials, + name: MyApp.WorkOSCredentials, + token_url: "https://.../oauth2/token", + identity_token_provider: provider} ] client = WorkOS.Client.new(credentials: MyApp.WorkOSCredentials) diff --git a/lib/workos/workload_identity/credentials.ex b/lib/workos/workload_identity/credentials.ex index ff1982f7..0df8e1fa 100644 --- a/lib/workos/workload_identity/credentials.ex +++ b/lib/workos/workload_identity/credentials.ex @@ -25,6 +25,7 @@ defmodule WorkOS.WorkloadIdentity.Credentials do children = [ {WorkOS.WorkloadIdentity.Credentials, name: MyApp.WorkOSCredentials, + token_url: "https://.../oauth2/token", identity_token_provider: WorkOS.WorkloadIdentity.token_env("MY_IDENTITY_TOKEN")} ] @@ -37,8 +38,8 @@ defmodule WorkOS.WorkloadIdentity.Credentials do `{:error, reason}`. See `WorkOS.WorkloadIdentity`. * `:client_id` — the M2M application's client ID. Falls back to the `WORKOS_CLIENT_ID` environment variable. - * `:token_url` — the exchange endpoint. Falls back to - `WORKOS_WIF_TOKEN_URL`. There is no built-in default. + * `:token_url` — required. The exchange endpoint. There is no built-in + default, and no environment variable is read for it. * `:environment_id` — optional, and set only here: no environment variable is read for it. When set, it is sent as the `x-url-environment-id` header on every API request. When it is left @@ -48,17 +49,18 @@ defmodule WorkOS.WorkloadIdentity.Credentials do different environment gets `403 environment_mismatch`. * `:resource` — the `resource` form field. Defaults to `https://api.workos.com`. - * `:scope` — the `scope` form field. Falls back to `WORKOS_WIF_SCOPE`; - left out of the exchange when unset. + * `:scope` — optional. The `scope` form field. It is left out of the + exchange when it is not set, `nil` or an empty string. No environment + variable is read for it. * `:name` — registers the process, as in `GenServer.start_link/3`. * `:req_options` — extra `Req` options merged into the exchange request (advanced; used by tests to inject `plug:`). The exchange never retries through Req, never follows a redirect and never sends an `Authorization` header, whatever is passed here. - An explicit option always wins over its environment variable. The - environment variables only fill in omitted options; they never turn - workload identity on by themselves. Configuration is fixed once the process + `WORKOS_CLIENT_ID` is the only environment variable the credentials read. + An explicit `:client_id` always wins over it, and the variable never turns + workload identity on by itself. Configuration is fixed once the process starts. A missing required option makes `start_link/1` return `{:error, %WorkOS.WorkloadIdentityError{code: "invalid_configuration"}}`. @@ -91,9 +93,8 @@ defmodule WorkOS.WorkloadIdentity.Credentials do @refresh_threshold_ms 60_000 @refresh_lifetime_divisor 5 + # The only environment variable the credentials read. @client_id_env "WORKOS_CLIENT_ID" - @token_url_env "WORKOS_WIF_TOKEN_URL" - @scope_env "WORKOS_WIF_SCOPE" # -- public API ------------------------------------------------------------- @@ -167,7 +168,7 @@ defmodule WorkOS.WorkloadIdentity.Credentials do ]) with {:ok, client_id} <- required(opts, :client_id, @client_id_env), - {:ok, token_url} <- required(opts, :token_url, @token_url_env), + {:ok, token_url} <- required(opts, :token_url), {:ok, provider} <- provider(opts[:identity_token_provider]) do {:ok, %{ @@ -176,7 +177,7 @@ defmodule WorkOS.WorkloadIdentity.Credentials do # Optional, and only from the caller: no environment variable is read. environment_id: present(opts[:environment_id]), resource: present(opts[:resource]) || @default_resource, - scope: present(opts[:scope]) || present(System.get_env(@scope_env)), + scope: present(opts[:scope]), identity_token_provider: provider, req_options: opts[:req_options], clock: opts[:clock], @@ -193,6 +194,13 @@ defmodule WorkOS.WorkloadIdentity.Credentials do end end + defp required(opts, key) do + case present(opts[key]) do + nil -> invalid_configuration("#{key} is required") + value -> {:ok, value} + end + end + defp provider(provider) when is_function(provider, 0), do: {:ok, provider} defp provider({module, function, args} = provider) diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index 14f66319..4866ca9f 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -272,6 +272,18 @@ defmodule WorkOS.WorkloadIdentityTest do assert exchange.authorization == nil end + test "WIF-01 a nil or empty scope leaves the scope field out of the form" do + for scope <- [nil, ""] do + token_endpoint = token_endpoint() + + assert {:ok, _} = + token_endpoint |> start_credentials(scope: scope) |> client(api()) |> get() + + assert [exchange] = requests(token_endpoint) + refute Map.has_key?(exchange.form, "scope") + end + end + test "WIF-02 (a) the API request carries the access token and the environment header" do api = api() assert {:ok, _} = token_endpoint() |> start_credentials() |> client(api) |> get() @@ -952,13 +964,13 @@ defmodule WorkOS.WorkloadIdentityTest do assert client.api_key == nil assert {:ok, _} = get(client) - # (b) No token URL, explicitly or in the environment. + # (b) No token URL. options = token_endpoint() |> credentials_options([]) |> Keyword.delete(:token_url) assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = Credentials.start_link(options) - assert error.description == "token_url is required (or set WORKOS_WIF_TOKEN_URL)" + assert error.description == "token_url is required" # (c) Valid credentials whose exchange fails. failing = token_endpoint([{:oauth_error, "invalid_client", "Unknown client."}]) @@ -971,19 +983,30 @@ defmodule WorkOS.WorkloadIdentityTest do end test "WIF-20 every required option is checked when the credentials are constructed" do - for {key, variable} <- [ - client_id: "WORKOS_CLIENT_ID", - token_url: "WORKOS_WIF_TOKEN_URL" + # Only client_id has an environment variable to name. + for {key, description} <- [ + client_id: "client_id is required (or set WORKOS_CLIENT_ID)", + token_url: "token_url is required" ] do options = token_endpoint() |> credentials_options([]) |> Keyword.delete(key) assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = Credentials.start_link(options) - assert error.description == "#{key} is required (or set #{variable})" + assert error.description == description assert Exception.message(error) =~ "missing a required setting" end + # A nil or empty token URL is a missing one. + for token_url <- [nil, ""] do + options = credentials_options(token_endpoint(), token_url: token_url) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = + Credentials.start_link(options) + + assert error.description == "token_url is required" + end + options = token_endpoint() |> credentials_options([]) |> Keyword.delete(:identity_token_provider) @@ -1110,32 +1133,34 @@ defmodule WorkOS.WorkloadIdentityTest do end end - test "WIF-22 omitted fields default from the environment, and explicit values win" do + test "WIF-22 only client_id defaults from the environment, and an explicit value wins" do System.put_env("WORKOS_CLIENT_ID", "client_env") - System.put_env("WORKOS_WIF_TOKEN_URL", "https://env.wif.test/oauth2/token") + System.put_env("WORKOS_WIF_TOKEN_URL", "https://ignored.example.test/oauth2/token") System.put_env("WORKOS_WIF_SCOPE", "scope_env") provider = fn -> {:ok, "assertion-1"} end - # (c) Only a provider is passed. + # (c) A provider and the token URL, and nothing else. The SDK reads + # neither WORKOS_WIF_TOKEN_URL nor WORKOS_WIF_SCOPE. token_endpoint = token_endpoint() api = api() assert {:ok, credentials} = Credentials.start_link( identity_token_provider: provider, + token_url: @token_url, req_options: [plug: token_plug(token_endpoint)] ) assert {:ok, _} = credentials |> client(api) |> get() assert [exchange] = requests(token_endpoint) - assert exchange.host == "env.wif.test" + assert exchange.host == "auth.wif.test" assert exchange.path == "/oauth2/token" assert exchange.form["client_id"] == "client_env" - assert exchange.form["scope"] == "scope_env" + refute Map.has_key?(exchange.form, "scope") - # (d) The same environment, with explicit values. + # (d) The same environment, with an explicit client ID. token_endpoint = token_endpoint() api = api() @@ -1143,7 +1168,7 @@ defmodule WorkOS.WorkloadIdentityTest do Credentials.start_link( identity_token_provider: provider, client_id: "client_explicit", - scope: "scope_explicit", + token_url: @token_url, req_options: [plug: token_plug(token_endpoint)] ) @@ -1151,7 +1176,15 @@ defmodule WorkOS.WorkloadIdentityTest do assert [exchange] = requests(token_endpoint) assert exchange.form["client_id"] == "client_explicit" - assert exchange.form["scope"] == "scope_explicit" + + # (e) The same environment, with no token URL. + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = + Credentials.start_link( + identity_token_provider: provider, + req_options: [plug: token_plug(token_endpoint())] + ) + + assert error.description == "token_url is required" end # -- redirects ---------------------------------------------------------------------- From 0516efc5a4e5a8f3f00e9ba350f03679f99ad851 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 16 Nov 2026 15:25:34 -0500 Subject: [PATCH 08/15] fix(workload-identity): resolve credentials before every attempt on Req 0.7 With Req 0.7.x installed, every request raised `FunctionClauseError` in `WorkOS.Client.run_adapter/2`, for API-key clients as well. `mix.exs` allows `{:req, "~> 0.5"}`, which a new install resolves to 0.7.5, while `mix.lock` pinned 0.6.3, so the SDK's own tests passed. The client resolves the credentials before every HTTP attempt: the first try, each transport retry, each redirect and the 401 recovery. Up to Req 0.6 the only thing Req runs again for the later attempts is the adapter, a function, so the `workos_credentials` request step wrapped it. Req 0.7.0 changed both halves of that: - The adapter is a module (`Req.Finch`, `Req.Plug`), called as `mod.run/1`. The wrapper accepted only a function or an MFA tuple. A function adapter still works on 0.7 but warns on every request. - `current_request_steps` is gone: every request step runs again for each attempt. The step now picks one of two ways, by whether the request still has `:current_request_steps`: - Req 0.7 and later: the step authorizes the attempt itself and leaves the adapter alone, so the SDK sets no function adapter and causes no deprecation warning. - Req 0.5 and 0.6: the step wraps the adapter, as before. Both share one function that resolves the credentials and sets the headers, or removes them for a redirect to another origin. The origin of the first attempt moved from the wrapper's closure into the request's private data. On Req 0.7 the step runs again after a redirect, and reading the origin there would take the redirect target for it. `mix.lock` now pins Req 0.7.5, the version a new install gets, so CI tests it. Only the `req` entry changed. New tests in `test/workos/client_adapter_test.exs` send requests through the adapters Req itself provides: the default adapter against a loopback server (`WorkOS.TestServer`) and the plug adapter. They check that an API-key request works with no adapter chosen, that the credentials are resolved exactly once per attempt across a retry, a 401 recovery and a redirect, that a redirect to another origin gets no credential header, and that Req prints no warning. Until now every test used a plug, and none counted resolves. The suite passes on Req 0.5.13, 0.5.17, 0.5.18, 0.6.0, 0.6.3, 0.7.0 and 0.7.5. --- lib/workos/client.ex | 77 ++++++---- mix.lock | 2 +- test/support/test_server.ex | 103 +++++++++++++ test/workos/client_adapter_test.exs | 218 ++++++++++++++++++++++++++++ 4 files changed, 373 insertions(+), 27 deletions(-) create mode 100644 test/support/test_server.ex create mode 100644 test/workos/client_adapter_test.exs diff --git a/lib/workos/client.ex b/lib/workos/client.ex index ed9fd5c1..9d5a9763 100644 --- a/lib/workos/client.ex +++ b/lib/workos/client.ex @@ -75,9 +75,11 @@ defmodule WorkOS.Client do @request_id_header "x-request-id" # Req private keys. Private data survives Req's own retries and redirects, - # so the one 401 recovery a logical request is allowed cannot be reset. + # so the one 401 recovery a logical request is allowed cannot be reset, and + # the origin the request was first sent to is still known after a redirect. @snapshot_key :workos_credential_snapshot @recovery_used_key :workos_credential_recovery_used + @origin_key :workos_credential_origin @doc """ Builds a new client. See the module documentation for options. @@ -216,37 +218,59 @@ defmodule WorkOS.Client do "WorkOS.WorkloadIdentity.Credentials process." end - # Request step. Req runs request steps once per `Req.request/1`, but calls - # the adapter for every HTTP attempt: the first one, each transport retry, - # each redirect and the 401 recovery. Wrapping the adapter is therefore what - # resolves the credentials before every attempt, so a retry never sends an - # expired token. It runs last, after Req has chosen the adapter. - defp put_credentials(%Req.Request{} = request, credentials, timeout) do - adapter = request.adapter - origin = origin(request.url) - - %{request | adapter: &send_attempt(&1, adapter, credentials, timeout, origin)} + # Request step, appended last. Credentials are resolved before every HTTP + # attempt: the first one, each transport retry, each redirect and the 401 + # recovery, so a retry never sends an expired token. What Req runs again for + # the later attempts depends on its version: + # + # * Req 0.7 and later run every request step again, so this step + # authorizes each attempt itself. The adapter (a module there) is left + # alone. + # * Req 0.5 and 0.6 run the request steps once per `Req.request/1` and + # call only the adapter (a function there) for the later attempts, so + # this step wraps the adapter. It runs last, after Req has chosen it. + # + # The origin of the first attempt is kept in the request's private data, so + # a redirect is always compared with where the request was first sent. + defp put_credentials(%Req.Request{adapter: adapter} = request, credentials, timeout) do + # Set by the first run only; a later run keeps it. + request = Req.Request.update_private(request, @origin_key, origin(request.url), & &1) + + if request_steps_run_once?(request) do + %{request | adapter: &send_attempt(&1, adapter, credentials, timeout)} + else + authorize_attempt(request, credentials, timeout) + end end - defp send_attempt(request, adapter, credentials, timeout, origin) do - if origin(request.url) == origin or request.options[:redirect_trusted] == true do - send_with_credentials(request, adapter, credentials, timeout) - else - # A redirect to another origin. Req has already removed the - # Authorization header; keep every credential header off the request. - run_adapter(adapter, drop_credentials(request)) + # Up to Req 0.6 a request tracks the request steps it has not run yet in + # `:current_request_steps`, and a retry or a redirect resumes from that + # (empty) list. Req 0.7 removed the field: every run starts from the first + # step. + defp request_steps_run_once?(request), do: is_map_key(request, :current_request_steps) + + defp send_attempt(request, adapter, credentials, timeout) do + case authorize_attempt(request, credentials, timeout) do + %Req.Request{} = request -> run_adapter(adapter, request) + {request, exception} -> {request, exception} end end - defp send_with_credentials(request, adapter, credentials, timeout) do - case WorkOS.Credentials.resolve(credentials, timeout) do - {:ok, %WorkOS.CredentialSnapshot{} = snapshot} -> - run_adapter(adapter, put_snapshot(request, snapshot)) + # Returns the request to send, or `{request, exception}` when the + # credentials cannot be resolved. That is terminal for the request: + # `retryable?/2` only retries Req's own transport errors. + defp authorize_attempt(request, credentials, timeout) do + same_origin? = origin(request.url) == Req.Request.get_private(request, @origin_key) - {:error, exception} -> - # Terminal for the request: `retryable?/2` only retries Req's own - # transport errors. - {request, exception} + if same_origin? or request.options[:redirect_trusted] == true do + case WorkOS.Credentials.resolve(credentials, timeout) do + {:ok, %WorkOS.CredentialSnapshot{} = snapshot} -> put_snapshot(request, snapshot) + {:error, exception} -> {request, exception} + end + else + # A redirect to another origin. Req has already removed the + # Authorization header; keep every credential header off the request. + drop_credentials(request) end end @@ -261,6 +285,7 @@ defmodule WorkOS.Client do |> Req.Request.put_private(@snapshot_key, snapshot) end + # The adapter shapes Req 0.5 and 0.6 accept. defp run_adapter(adapter, request) when is_function(adapter, 1), do: adapter.(request) defp run_adapter({module, function, args}, request), diff --git a/mix.lock b/mix.lock index a610dfe6..323a627e 100644 --- a/mix.lock +++ b/mix.lock @@ -20,6 +20,6 @@ "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"}, "plug": {:hex, :plug, "1.20.3", "56c480c633ec2ce10140e236e15233bf576e1d323887d7c96711bd02ab5160db", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "be266aee1b8536ef6409d58cf39a3121319f0ec47cfa1b24024485aa0e76ad76"}, "plug_crypto": {:hex, :plug_crypto, "2.1.1", "19bda8184399cb24afa10be734f84a16ea0a2bc65054e23a62bb10f06bc89491", [:mix], [], "hexpm", "6470bce6ffe41c8bd497612ffde1a7e4af67f36a15eea5f921af71cf3e11247c"}, - "req": {:hex, :req, "0.6.3", "7fe5e68792ff0546e45d5919104fa1764a13694cfe3e48c8a0f32ad051ae77e4", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "e85b5c6c990e6c3f52bbba68e6f099118f2b8252825f96c7c3636b97a3de307d"}, + "req": {:hex, :req, "0.7.5", "0c3293cbf7717aba20b1b1b3ea13fe8d3fdf6f1557490f390c3f1ef6dd9db955", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "576853c4bf403faa3c1fa5d093e0759227083b78f8a6864c67d62c0a9c45514d"}, "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"}, } diff --git a/test/support/test_server.ex b/test/support/test_server.ex new file mode 100644 index 00000000..1f47454d --- /dev/null +++ b/test/support/test_server.ex @@ -0,0 +1,103 @@ +# @oagen-ignore-file + +defmodule WorkOS.TestServer do + @moduledoc false + + # A minimal HTTP/1.1 server on a loopback port, for the tests that must go + # through Req's own default adapter instead of a plug. It answers each + # connection with the next canned response (the last one repeats) and sends + # every request it reads to the test process, as + # `{:request, ref, %{method: _, target: _, headers: _, body: _}}`. + # + # It runs under the test's supervisor, so it stops when the test ends. + + @type response :: {pos_integer(), [{String.t(), String.t()}], String.t()} + + @spec start([response(), ...]) :: %{url: String.t(), ref: reference()} + def start([_ | _] = responses) do + owner = self() + ref = make_ref() + + _pid = + ExUnit.Callbacks.start_supervised!( + {Task, fn -> listen(responses, owner, ref) end}, + id: {__MODULE__, ref} + ) + + receive do + {:listening, ^ref, port} -> %{url: "http://127.0.0.1:#{port}", ref: ref} + after + 5_000 -> raise "test server did not start" + end + end + + defp listen(responses, owner, ref) do + {:ok, listener} = + :gen_tcp.listen(0, [ + :binary, + packet: :http_bin, + active: false, + reuseaddr: true, + ip: {127, 0, 0, 1} + ]) + + {:ok, port} = :inet.port(listener) + send(owner, {:listening, ref, port}) + accept(listener, responses, owner, ref) + end + + defp accept(listener, responses, owner, ref) do + {:ok, socket} = :gen_tcp.accept(listener) + send(owner, {:request, ref, read_request(socket)}) + + {response, rest} = next(responses) + :ok = :gen_tcp.send(socket, encode(response)) + :ok = :gen_tcp.close(socket) + + accept(listener, rest, owner, ref) + end + + defp next([response]), do: {response, [response]} + defp next([response | rest]), do: {response, rest} + + defp read_request(socket) do + {:ok, {:http_request, method, {:abs_path, target}, _version}} = + :gen_tcp.recv(socket, 0, 5_000) + + headers = read_headers(socket, %{}) + length = headers |> Map.get("content-length", "0") |> String.to_integer() + + %{ + method: to_string(method), + target: target, + headers: headers, + body: read_body(socket, length) + } + end + + defp read_headers(socket, headers) do + case :gen_tcp.recv(socket, 0, 5_000) do + {:ok, {:http_header, _, name, _, value}} -> + read_headers(socket, Map.put(headers, name |> to_string() |> String.downcase(), value)) + + {:ok, :http_eoh} -> + headers + end + end + + defp read_body(_socket, 0), do: "" + + defp read_body(socket, length) do + :ok = :inet.setopts(socket, packet: :raw) + {:ok, body} = :gen_tcp.recv(socket, length, 5_000) + body + end + + defp encode({status, headers, body}) do + head = + [{"content-length", Integer.to_string(byte_size(body))}, {"connection", "close"} | headers] + |> Enum.map(fn {name, value} -> [name, ": ", value, "\r\n"] end) + + ["HTTP/1.1 ", Integer.to_string(status), " Mock\r\n", head, "\r\n", body] + end +end diff --git a/test/workos/client_adapter_test.exs b/test/workos/client_adapter_test.exs new file mode 100644 index 00000000..672f5999 --- /dev/null +++ b/test/workos/client_adapter_test.exs @@ -0,0 +1,218 @@ +# @oagen-ignore-file + +defmodule WorkOS.ClientAdapterTest do + # `WorkOS.Client` resolves the credentials before every HTTP attempt, and + # how it gets to run before each attempt depends on the Req version (see the + # comment on `put_credentials/3` in the client). So these tests send + # requests through the adapters Req itself ships, in whatever shape the + # installed Req gives them, and never through a stub adapter: the default + # adapter against a loopback server, and the plug adapter. + # + # Not async: one test captures standard error. + use ExUnit.Case, async: false + + import ExUnit.CaptureIO + import ExUnit.CaptureLog + + alias WorkOS.TestServer + + defmodule CountingCredentials do + @moduledoc false + + # Credentials whose every resolve returns a new token ("token-1", + # "token-2", ...). The token an attempt carries therefore says how many + # times the credentials had been resolved when that attempt was sent. + + @behaviour WorkOS.Credentials + + def start do + ExUnit.Callbacks.start_supervised!({Agent, fn -> %{resolved: 0, invalidated: []} end}) + end + + @impl WorkOS.Credentials + def resolve(agent, _timeout) do + count = Agent.get_and_update(agent, &{&1.resolved + 1, %{&1 | resolved: &1.resolved + 1}}) + + {:ok, + %WorkOS.CredentialSnapshot{ + headers: [ + {"authorization", "Bearer token-#{count}"}, + {"x-url-environment-id", "environment_test"} + ], + generation: count, + recoverable: true + }} + end + + @impl WorkOS.Credentials + def invalidate(agent, generation), + do: Agent.update(agent, &%{&1 | invalidated: &1.invalidated ++ [generation]}) + end + + @ok {200, [{"content-type", "application/json"}], ~s({"ok":true})} + + # -- servers ------------------------------------------------------------------ + # + # Both kinds answer each request with the next canned response and send the + # test `{:request, ref, %{method: _, target: _, headers: _}}`. The loopback + # server adds the request `:body`. + + # Req's default adapter: no `:adapter` and no `:plug` option is set. + defp start(:default, responses) do + responses |> TestServer.start() |> Map.put(:req_options, []) + end + + # Req's plug adapter. + defp start(:plug, responses) do + test = self() + ref = make_ref() + script = start_supervised!({Agent, fn -> responses end}, id: ref) + + plug = fn conn -> + send( + test, + {:request, ref, + %{ + method: conn.method, + target: request_target(conn), + headers: Map.new(conn.req_headers) + }} + ) + + {status, headers, body} = + Agent.get_and_update(script, fn + [response] -> {response, [response]} + [response | rest] -> {response, rest} + end) + + headers + |> Enum.reduce(conn, fn {name, value}, conn -> + Plug.Conn.put_resp_header(conn, name, value) + end) + |> Plug.Conn.send_resp(status, body) + end + + %{url: "https://api.workos.test", ref: ref, req_options: [plug: plug]} + end + + defp request_target(%Plug.Conn{query_string: ""} = conn), do: conn.request_path + defp request_target(%Plug.Conn{} = conn), do: conn.request_path <> "?" <> conn.query_string + + # The requests a server has received so far, oldest first. + defp received(%{ref: ref} = server) do + receive do + {:request, ^ref, request} -> [request | received(server)] + after + 0 -> [] + end + end + + # A client that authenticates with `CountingCredentials`. Retries do not + # wait. + defp counting_client(credentials, server) do + client = + WorkOS.Client.new( + api_key: "sk_test_replaced_below", + base_url: server.url, + req_options: [retry_delay: fn _retries -> 0 end] ++ server.req_options + ) + + %{client | api_key: nil, credentials: {CountingCredentials, credentials}} + end + + # -- tests -------------------------------------------------------------------- + + test "an API-key request goes through Req's default adapter" do + server = start(:default, [@ok]) + client = WorkOS.Client.new(api_key: "sk_test_default_adapter", base_url: server.url) + + # Nothing chooses an adapter: this is the client an application builds. + assert client.req_options == [] + + assert {:ok, %{"ok" => true}} = + WorkOS.Client.request(client, :post, "/adapter-check", %{name: "Acme"}) + + assert [request] = received(server) + assert request.method == "POST" + assert request.target == "/adapter-check" + assert request.headers["authorization"] == "Bearer sk_test_default_adapter" + assert request.headers["content-type"] == "application/json" + assert JSON.decode!(request.body) == %{"name" => "Acme"} + end + + for adapter <- [:default, :plug] do + test "credentials are resolved once before every attempt through Req's #{adapter} adapter: " <> + "first try, retry, 401 recovery and redirect" do + server = + start(unquote(adapter), [ + {503, [], ""}, + {401, [], ""}, + {302, [{"location", "/landed"}], ""}, + @ok + ]) + + credentials = CountingCredentials.start() + client = counting_client(credentials, server) + + capture_log(fn -> + assert {:ok, %{"ok" => true}} = WorkOS.Client.request(client, :get, "/attempts") + end) + + requests = received(server) + assert Enum.map(requests, & &1.target) == ~w(/attempts /attempts /attempts /landed) + + assert Enum.map(requests, & &1.headers["authorization"]) == + ["Bearer token-1", "Bearer token-2", "Bearer token-3", "Bearer token-4"] + + assert Enum.all?(requests, &(&1.headers["x-url-environment-id"] == "environment_test")) + + # One resolve per attempt, and the 401 invalidated the credential that + # attempt was sent with. + assert Agent.get(credentials, & &1) == %{resolved: 4, invalidated: [2]} + end + + test "the client makes Req print no warning through Req's #{adapter} adapter" do + server = start(unquote(adapter), [@ok]) + + client = + WorkOS.Client.new( + api_key: "sk_test_quiet", + base_url: server.url, + req_options: server.req_options + ) + + # Req warns on standard error about deprecated usage, such as an adapter + # given as a function on Req 0.7. + warnings = + capture_io(:stderr, fn -> + assert {:ok, %{"ok" => true}} = WorkOS.Client.request(client, :get, "/quiet") + end) + + assert warnings == "" + end + end + + test "a redirect to another origin through Req's default adapter gets no credential header " <> + "and does not resolve the credentials" do + elsewhere = start(:default, [@ok]) + server = start(:default, [{302, [{"location", elsewhere.url <> "/landed"}], ""}]) + + credentials = CountingCredentials.start() + client = counting_client(credentials, server) + + capture_log(fn -> + assert {:ok, %{"ok" => true}} = WorkOS.Client.request(client, :get, "/redirect") + end) + + assert [first] = received(server) + assert first.headers["authorization"] == "Bearer token-1" + assert first.headers["x-url-environment-id"] == "environment_test" + + assert [redirected] = received(elsewhere) + assert redirected.target == "/landed" + refute Map.has_key?(redirected.headers, "authorization") + refute Map.has_key?(redirected.headers, "x-url-environment-id") + + assert Agent.get(credentials, & &1.resolved) == 1 + end +end From 97a9e453dfb4e04f93400be9416c8acf5086c297 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 16 Nov 2026 15:31:51 -0500 Subject: [PATCH 09/15] fix(workload-identity): require an https token URL `:token_url` must now be an absolute URL with the scheme `https` and a host. The request to it carries the workload's identity token and the response carries the access token. Until now the credentials checked only that the option was present. Anything else is refused when the credentials are started, with `invalid_configuration` and the description `token_url must be an absolute https URL`: an `http://` URL, a URL with no scheme or no host, any other scheme. The scheme is compared without regard to case, so `HTTPS://` is accepted. There is no exception for `localhost` or loopback addresses, and nothing turns the check off: no option, no application config, no environment variable. workos-php already has the same rule. The exchange also sets the URL again after the caller's `:req_options`. A `:url` among them used to replace the token URL, which would have let a documented option send the identity token somewhere the check never saw. No test needed the check relaxed. The tests reach the token endpoint through a plug behind an https URL and never open a socket, and the provider packages do not start credentials at all. New tests cover the refused forms (http, http to localhost and to loopback addresses, no host, no scheme, other schemes, malformed URLs), upper-case `HTTPS://`, Req options that try to get around the check, and Req options that try to move the exchange. The README and the module docs say the token URL has to be https. --- README.md | 2 + lib/workos/workload_identity.ex | 3 + lib/workos/workload_identity/credentials.ex | 36 ++++++-- lib/workos/workload_identity/exchange.ex | 6 +- test/workos/workload_identity_test.exs | 92 +++++++++++++++++++++ 5 files changed, 132 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 6f66cc59..5d1be985 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,8 @@ client = WorkOS.Client.new(credentials: credentials) `:client_id` falls back to the `WORKOS_CLIENT_ID` environment variable. That is the only variable the credentials read: `:token_url` (required) and `:scope` (optional) are set only in code. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. +`:token_url` must be an absolute `https` URL with a host. The request to it carries the workload's identity token and the response carries the access token, so anything else is refused when the credentials start: an `http://` URL, a URL with no scheme or no host, any other scheme. There is no exception for `localhost` or loopback addresses, and no option or environment variable turns the check off. `start_link/1` then returns `{:error, %WorkOS.WorkloadIdentityError{code: "invalid_configuration"}}` with the description `token_url must be an absolute https URL`. + `:environment_id` is optional, and it is set only in code: the SDK reads no environment variable for it. The server binds a workload identity client to exactly one environment, so the `x-url-environment-id` header selects nothing, and the SDK sends it only when an environment ID is set. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. In an application, supervise the process under a name of your choosing and build clients from the name: diff --git a/lib/workos/workload_identity.ex b/lib/workos/workload_identity.ex index eda84644..ef22b6d0 100644 --- a/lib/workos/workload_identity.ex +++ b/lib/workos/workload_identity.ex @@ -9,6 +9,9 @@ defmodule WorkOS.WorkloadIdentity do for a short-lived WorkOS access token, caches the token, and refreshes it before it expires. See `WorkOS.WorkloadIdentity.Credentials` to set it up. + The exchange endpoint (`:token_url`) must be an `https` URL: the request + carries the identity token and the response carries the access token. + ## Identity token providers A provider is a zero-arity function, or a `{module, function, args}` tuple, diff --git a/lib/workos/workload_identity/credentials.ex b/lib/workos/workload_identity/credentials.ex index 0df8e1fa..842f68ec 100644 --- a/lib/workos/workload_identity/credentials.ex +++ b/lib/workos/workload_identity/credentials.ex @@ -38,8 +38,13 @@ defmodule WorkOS.WorkloadIdentity.Credentials do `{:error, reason}`. See `WorkOS.WorkloadIdentity`. * `:client_id` — the M2M application's client ID. Falls back to the `WORKOS_CLIENT_ID` environment variable. - * `:token_url` — required. The exchange endpoint. There is no built-in - default, and no environment variable is read for it. + * `:token_url` — required. The exchange endpoint. It must be an absolute + `https` URL with a host, because the request carries the workload's + identity token and the response carries the access token. Anything + else is refused when the credentials are started: an `http://` URL + (`localhost` and loopback addresses included), a URL with no scheme or + no host, any other scheme. Nothing turns the check off. There is no + built-in default, and no environment variable is read for it. * `:environment_id` — optional, and set only here: no environment variable is read for it. When set, it is sent as the `x-url-environment-id` header on every API request. When it is left @@ -54,15 +59,19 @@ defmodule WorkOS.WorkloadIdentity.Credentials do variable is read for it. * `:name` — registers the process, as in `GenServer.start_link/3`. * `:req_options` — extra `Req` options merged into the exchange request - (advanced; used by tests to inject `plug:`). The exchange never - retries through Req, never follows a redirect and never sends an - `Authorization` header, whatever is passed here. + (advanced; used by tests to inject `plug:`). The exchange is always + sent to `:token_url`, never retries through Req, never follows a + redirect and never sends an `Authorization` header, whatever is passed + here. `WORKOS_CLIENT_ID` is the only environment variable the credentials read. An explicit `:client_id` always wins over it, and the variable never turns workload identity on by itself. Configuration is fixed once the process - starts. A missing required option makes `start_link/1` return + starts. A missing required option, or a token URL that is not an absolute + `https` URL, makes `start_link/1` return `{:error, %WorkOS.WorkloadIdentityError{code: "invalid_configuration"}}`. + Its `:description` says which: for example `token_url is required`, or + `token_url must be an absolute https URL`. ## Behavior @@ -169,6 +178,7 @@ defmodule WorkOS.WorkloadIdentity.Credentials do with {:ok, client_id} <- required(opts, :client_id, @client_id_env), {:ok, token_url} <- required(opts, :token_url), + {:ok, token_url} <- https_url(token_url), {:ok, provider} <- provider(opts[:identity_token_provider]) do {:ok, %{ @@ -201,6 +211,20 @@ defmodule WorkOS.WorkloadIdentity.Credentials do end end + # https only: the exchange POST carries the workload's identity token and + # the response carries the access token. `localhost` and loopback addresses + # get no exception, and nothing turns the check off: no option, no + # application config, no environment variable. `URI.new/1` also refuses + # what is not a URL at all, such as one with a space in it. + defp https_url(token_url) do + with {:ok, %URI{scheme: scheme, host: host}} when is_binary(scheme) <- URI.new(token_url), + true <- String.downcase(scheme) == "https" and is_binary(host) and host != "" do + {:ok, token_url} + else + _not_https -> invalid_configuration("token_url must be an absolute https URL") + end + end + defp provider(provider) when is_function(provider, 0), do: {:ok, provider} defp provider({module, function, args} = provider) diff --git a/lib/workos/workload_identity/exchange.ex b/lib/workos/workload_identity/exchange.ex index 891e92a5..1509e9ef 100644 --- a/lib/workos/workload_identity/exchange.ex +++ b/lib/workos/workload_identity/exchange.ex @@ -24,6 +24,10 @@ defmodule WorkOS.WorkloadIdentity.Exchange do # `:follow_redirects` option, which Req reads ahead of `:redirect`, and adds # a last request step that removes any `authorization` header, so it does # not matter which option or step put one there. + # + # `post/2` sets the URL again after the caller's options too. The token URL + # was checked to be https when the credentials were started, and a `:url` + # among the Req options must not send the identity token anywhere else. @fixed_options [retry: false, redirect: false, decode_body: false, auth: nil] @redacted "[REDACTED]" @@ -113,7 +117,7 @@ defmodule WorkOS.WorkloadIdentity.Exchange do ] |> Req.new() |> Req.merge(config.req_options) - |> Req.merge(@fixed_options) + |> Req.merge([url: config.token_url] ++ @fixed_options) |> Req.Request.delete_option(:follow_redirects) |> Req.Request.append_request_steps( workos_no_authorization: &Req.Request.delete_header(&1, "authorization") diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index 4866ca9f..765e0ab4 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -1017,6 +1017,98 @@ defmodule WorkOS.WorkloadIdentityTest do Credentials.start_link(Keyword.put(options, :identity_token_provider, "a string")) end + # -- the token URL must be https -------------------------------------------------- + # + # The exchange POST carries the identity token and the response carries the + # access token. The tests in this file never open a socket: the token + # endpoint is a plug behind an https URL, so nothing here needs the check + # relaxed, and nothing relaxes it. + + for {token_url, why} <- [ + {"http://example.com/oauth2/token", "an http URL"}, + {"http://localhost:4000/oauth2/token", "http to localhost"}, + {"http://127.0.0.1/oauth2/token", "http to a loopback address"}, + {"http://[::1]:4000/oauth2/token", "http to the IPv6 loopback address"}, + {"https:///oauth2/token", "an https URL with no host"}, + {"https://", "an https URL with nothing after the scheme"}, + {"https:auth.wif.test/oauth2/token", "an https URL with no authority"}, + {"auth.wif.test/oauth2/token", "a URL with no scheme"}, + {"//auth.wif.test/oauth2/token", "a scheme-relative URL"}, + {"/oauth2/token", "a path"}, + {"ftp://auth.wif.test/oauth2/token", "another scheme"}, + {"httpss://auth.wif.test/oauth2/token", "a scheme that only starts with https"}, + {" https://auth.wif.test/oauth2/token", "a URL with a leading space"}, + {"https://auth.wif test/oauth2/token", "a URL with a space in the host"} + ] do + test "the token URL must be an absolute https URL: #{why} is refused (#{inspect(token_url)})" do + token_endpoint = token_endpoint() + options = credentials_options(token_endpoint, token_url: unquote(token_url)) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = + Credentials.start_link(options) + + assert error.description == "token_url must be an absolute https URL" + assert requests(token_endpoint) == [] + end + end + + test "the token URL scheme is not case-sensitive: HTTPS:// is accepted and used" do + token_endpoint = token_endpoint() + + credentials = + start_credentials(token_endpoint, token_url: "HTTPS://auth.wif.test/oauth2/token") + + assert {:ok, _} = credentials |> client(api()) |> get() + + assert [%{method: "POST", host: "auth.wif.test", path: "/oauth2/token"}] = + requests(token_endpoint) + end + + test "Req options do not reach the https check" do + token_endpoint = token_endpoint() + + options = + credentials_options(token_endpoint, + token_url: "http://localhost:4000/oauth2/token", + req_options: [ + plug: token_plug(token_endpoint), + url: @token_url, + base_url: "https://auth.wif.test" + ] + ) + + assert {:error, %WorkloadIdentityError{code: "invalid_configuration"} = error} = + Credentials.start_link(options) + + assert error.description == "token_url must be an absolute https URL" + assert requests(token_endpoint) == [] + end + + test "no Req option sends the exchange anywhere but the token URL" do + token_endpoint = token_endpoint() + test = self() + + plug = fn conn -> + send(test, {:exchange_sent_to, conn.scheme, conn.host, conn.request_path}) + token_plug(token_endpoint).(conn) + end + + req_options = [ + plug: plug, + url: "http://elsewhere.wif.test/collect", + base_url: "http://elsewhere.wif.test" + ] + + assert {:ok, _} = + token_endpoint + |> start_credentials(req_options: req_options) + |> client(api()) + |> get() + + assert_received {:exchange_sent_to, :https, "auth.wif.test", "/oauth2/token"} + refute_received {:exchange_sent_to, _scheme, _host, _path} + end + test "the credentials option must name a process" do assert_raise WorkOS.ConfigurationError, ~r/credentials/, fn -> WorkOS.Client.new(credentials: "not a process") From 9fcbd77026f02cda85be89d4e9737c8e34a2fd9b Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sun, 22 Nov 2026 23:27:08 -0500 Subject: [PATCH 10/15] fix(workload-identity): say why the token endpoint could not be reached When the exchange POST got no answer, the error was the standard sentence for `exchange_failed` and nothing else: exchange_failed: The token endpoint could not be reached or kept failing. Check the token URL and try again. A reader could not tell a host name that does not resolve from a refused connection, a timeout or a TLS failure. The exchange kept the transport error in `:reason` but built the error with an empty description, and the message is made of the code, the hint and the description only. The description now says where the request went and why it failed: the request to auth.example.com:443 failed: the host name could not be resolved (nxdomain) the request to auth.example.com:443 failed: the connection was refused (econnrefused) the request to auth.example.com:443 failed: it timed out (timeout) Any other transport error, a TLS alert for example, is put in Req's own words on one line. An exception that is not a transport error is named by its module, which is all that `:reason` keeps of it as well. Of the token URL, only the host and port are named, never the userinfo, the path or the query. A transport error holds the socket's reason and nothing from the request, so no token can get into the text. Only the description changed. The hint, the code, `:reason`, the retry count and the return shapes are as before. New tests cover name resolution, a refused connection, a timeout and a TLS alert, a token URL with userinfo, a port and a query, and a Req error that is not a transport error. --- lib/workos/workload_identity/exchange.ex | 36 +++++++++-- test/workos/workload_identity_test.exs | 76 ++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 4 deletions(-) diff --git a/lib/workos/workload_identity/exchange.ex b/lib/workos/workload_identity/exchange.ex index 1509e9ef..704c3260 100644 --- a/lib/workos/workload_identity/exchange.ex +++ b/lib/workos/workload_identity/exchange.ex @@ -128,8 +128,12 @@ defmodule WorkOS.WorkloadIdentity.Exchange do {:ok, response} {:error, exception} -> - {:retry, WorkloadIdentityError.new("exchange_failed", "", transport_reason(exception)), - nil} + {:retry, + WorkloadIdentityError.new( + "exchange_failed", + transport_description(exception, config.token_url), + transport_reason(exception) + ), nil} end end @@ -225,11 +229,35 @@ defmodule WorkOS.WorkloadIdentity.Exchange do defp retry_after(_response), do: nil - # Req's own transport errors carry a reason atom and nothing from the - # request. Any other exception is reduced to its module name. + # Req's own transport errors carry the socket's reason, an atom or a TLS + # alert, and nothing from the request. Any other exception is reduced to + # its module name. defp transport_reason(%Req.TransportError{} = exception), do: exception defp transport_reason(%{__struct__: module}), do: module + # The same failure in words, so that a host name that does not resolve + # reads differently from a refused connection, a timeout and a TLS failure. + # Of the token URL, only the host and port are named. The usual reasons get + # a phrase of their own. Any other transport error is put in Req's words, + # on one line; Req inspects a reason it does not know. + defp transport_description(exception, token_url) do + %URI{host: host, port: port} = URI.parse(token_url) + "the request to #{host}:#{port} failed: #{transport_phrase(exception)}" + end + + defp transport_phrase(%Req.TransportError{reason: :nxdomain}), + do: "the host name could not be resolved (nxdomain)" + + defp transport_phrase(%Req.TransportError{reason: :econnrefused}), + do: "the connection was refused (econnrefused)" + + defp transport_phrase(%Req.TransportError{reason: :timeout}), do: "it timed out (timeout)" + + defp transport_phrase(%Req.TransportError{} = exception), + do: exception |> Exception.message() |> String.replace(~r/\s+/, " ") |> String.trim() + + defp transport_phrase(%{__struct__: module}), do: inspect(module) + defp unexpected(what) do WorkloadIdentityError.new( "exchange_failed", diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index 765e0ab4..e9405555 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -935,6 +935,82 @@ defmodule WorkOS.WorkloadIdentityTest do end end + test "an exchange that gets no answer says why: name resolution, refused connection, timeout, TLS" do + tls_alert = + {:tls_alert, + {:bad_certificate, + ~c"TLS client: In state certify generated CLIENT ALERT: Fatal - Bad Certificate\n selfsigned_peer"}} + + for {reason, why} <- [ + {:nxdomain, "the host name could not be resolved (nxdomain)"}, + {:econnrefused, "the connection was refused (econnrefused)"}, + {:timeout, "it timed out (timeout)"}, + # Any other reason is put in Req's words, on one line. + {tls_alert, + "TLS client: In state certify generated CLIENT ALERT: Fatal - Bad Certificate selfsigned_peer"} + ] do + token_endpoint = mock({:transport_error, reason}, []) + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"} = error} = + token_endpoint + |> start_credentials( + identity_token_provider: fn -> {:ok, "SECRET-ASSERTION-VALUE"} end + ) + |> client(api()) + |> get() + + assert error.description == "the request to auth.wif.test:443 failed: " <> why + + assert Exception.message(error) == + "exchange_failed: The token endpoint could not be reached or kept failing. " <> + "Check the token URL and try again. " <> error.description + + # The transport error is still on the struct, and it was retried as before. + assert error.reason == %Req.TransportError{reason: reason} + assert length(requests(token_endpoint)) == WorkOS.Client.default_max_retries() + 1 + refute inspect(error) =~ "SECRET-ASSERTION-VALUE" + end + end + + test "the reason an exchange got no answer takes only the host and port from the token URL" do + token_endpoint = mock({:transport_error, :econnrefused}, []) + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"} = error} = + token_endpoint + |> start_credentials( + token_url: + "https://user:SECRET-USERINFO@auth.wif.test:8443/oauth2/token?k=SECRET-QUERY" + ) + |> client(api()) + |> get() + + assert error.description == + "the request to auth.wif.test:8443 failed: the connection was refused (econnrefused)" + end + + test "an exchange that fails with another Req error names the error's module and nothing from it" do + token_endpoint = token_endpoint() + + # A response checksum that cannot match makes Req return an exception + # that is not a transport error. + req_options = [ + plug: token_plug(token_endpoint), + checksum: "sha256:" <> String.duplicate("0", 64) + ] + + assert {:error, %WorkloadIdentityError{code: "exchange_failed"} = error} = + token_endpoint + |> start_credentials(req_options: req_options) + |> client(api()) + |> get() + + assert error.description == + "the request to auth.wif.test:443 failed: Req.ChecksumMismatchError" + + assert error.reason == Req.ChecksumMismatchError + assert length(requests(token_endpoint)) == WorkOS.Client.default_max_retries() + 1 + end + # -- authentication precedence --------------------------------------------------- test "WIF-19 passing both an API key and credentials is a configuration error" do From 350d4893a7b6f29a7766e29b27b464466ef2b70f Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 00:01:27 -0500 Subject: [PATCH 11/15] fix(workload-identity): say why GitHub's OIDC endpoint was not reached The GitHub Actions provider gave a reason for a failed request only when `:httpc` reported it as a bare atom on the connection attempt. A TLS failure arrives as `{:tls_alert, {alert, text}}`, so an untrusted, expired or wrong-host certificate all read the same: The GitHub Actions OIDC token endpoint could not be reached: connection failed. A server that closed the connection read `request failed`. The message now names the host and port and says what went wrong, in the wording the token exchange uses: The GitHub Actions OIDC token endpoint at example.com:443 could not be reached: the server's certificate is not from a trusted certificate authority (unknown_ca). - TLS: a certificate from an authority that is not trusted, one that has expired or is not valid yet, one for another host name, a self-signed one, and `the TLS handshake failed ()` for any other alert. - Connection: the host name could not be resolved, the connection was refused, the request timed out, the server closed the connection. Any other socket reason stays `the connection failed ()`. Nothing raw is put in the message. The words are fixed; the only terms printed are the socket's reason when it is an atom, the name of a TLS alert, and the host and port of the request URL. A TLS alert's text is searched for `hostname_check_failed` and `selfsigned_peer`, because OTP reports both under a general alert that differs by release (a wrong host name is `handshake_failure` on OTP 25 and 26 and `bad_certificate` from OTP 27). The text is never copied. OTP 25 gives no word for a self-signed certificate, so there it reads `the TLS handshake failed (bad_certificate)`. The provider also refuses a request token that is not visible ASCII (0x21 to 0x7E) before it makes any request, with a message that names `ACTIONS_ID_TOKEN_REQUEST_TOKEN` and not its value. The token goes into the `Authorization` header as it is, and `:httpc` sends a line break in a header value unchanged, on OTP 25 through 29: a trailing newline sent a broken header, and a line break followed by text sent a header of its own. Nothing is stripped, since a token that needs repair is not the runner's token. The token did not appear in an error before either, but only because the raw reason was dropped: for a non-ASCII value `:httpc` returns the whole header in the reason from OTP 26, and on OTP 25 its handler crashes and the request waits out the timeout. `__describe__/1` is a test seam for the wording, like `__provider__` in the other provider packages, because a timeout and a name that does not resolve cannot be produced on a loopback port. The tests start a TLS listener on a loopback port with certificates made at test time by `:public_key.pkix_test_data/1`, and make the test root the trust store with `:public_key.cacerts_load/1`. They cover a trusted certificate, an untrusted authority, another host name, an expired and a not-yet-valid certificate, a self-signed certificate, a refused connection and a server that closes without answering. A table covers every phrase, with a secret in the raw reason that must not come out. Other tests check that only the host and port of the URL are named, that tokens with a line break, a space, a control character or a non-ASCII character reach no server, and that every visible ASCII character is sent unchanged. --- .../workload_identity/github_actions.ex | 113 +++++- .../workload_identity/github_actions_test.exs | 337 +++++++++++++++++- 2 files changed, 436 insertions(+), 14 deletions(-) diff --git a/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex b/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex index cac22a7b..fe499fec 100644 --- a/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex +++ b/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex @@ -42,6 +42,10 @@ defmodule WorkOS.WorkloadIdentity.GitHubActions do @missing_env_message "GitHub Actions did not provide an OIDC token endpoint. " <> "Add `permissions: id-token: write` to the workflow or job." + @unsendable_token_message "#{@token_env} contains a character that is not allowed in an " <> + "HTTP header, such as a line break. GitHub Actions sets this " <> + "variable; pass it to the program unchanged." + @type provider :: (-> {:ok, String.t()} | {:error, Error.t()}) @doc """ @@ -49,7 +53,9 @@ defmodule WorkOS.WorkloadIdentity.GitHubActions do The audience is required. The conventional value is `https://api.workos.com`. `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` are read - on every call of the provider, not when it is built. + on every call of the provider, not when it is built. A request token with a + space, a line break, any other control character or a character outside + ASCII is refused before any request is made. """ @spec github_actions(String.t()) :: provider() def github_actions(audience) when is_binary(audience) and audience != "" do @@ -67,13 +73,20 @@ defmodule WorkOS.WorkloadIdentity.GitHubActions do url = System.get_env(@url_env) request_token = System.get_env(@token_env) - if url in [nil, ""] or request_token in [nil, ""] do - error(@missing_env_message) - else - {:ok, url, request_token} + cond do + url in [nil, ""] or request_token in [nil, ""] -> error(@missing_env_message) + not visible_ascii?(request_token) -> error(@unsendable_token_message) + true -> {:ok, url, request_token} end end + # The request token goes into a header as it is, and `:httpc` sends a line + # break or any other control character in a header value unchanged: a + # trailing newline breaks the header, and a line break followed by text adds + # a header of its own. So only visible ASCII, 0x21 to 0x7E, is accepted. + # Nothing is stripped: a token that needs repair is not the runner's token. + defp visible_ascii?(request_token), do: request_token =~ ~r/\A[\x21-\x7E]+\z/ + # The runner's URL already has a query string; the audience is added to it. defp with_audience(url, audience) do url @@ -102,7 +115,22 @@ defmodule WorkOS.WorkloadIdentity.GitHubActions do error("The GitHub Actions OIDC token endpoint returned HTTP #{status}.") {:error, reason} -> - error("The GitHub Actions OIDC token endpoint could not be reached: #{describe(reason)}.") + error( + "The GitHub Actions OIDC token endpoint#{at(url)} could not be reached: " <> + "#{describe(reason)}." + ) + end + end + + # Where the request went, as " at host:port". No other part of the URL is + # named, and nothing is added when the URL has no host or no known port. + defp at(url) do + case URI.parse(url) do + %URI{host: host, port: port} when is_binary(host) and host != "" and is_integer(port) -> + " at #{host}:#{port}" + + _no_host_or_port -> + "" end end @@ -135,18 +163,77 @@ defmodule WorkOS.WorkloadIdentity.GitHubActions do end end - # Only the failure kind is reported. The raw reason is never interpolated, - # so nothing from the request can end up in the message. - defp describe(:timeout), do: "timeout" - + # The wording of a failed request is a test seam: most of these failures + # cannot be produced on a loopback port. It is not a public function. + @doc false + @spec __describe__(term()) :: String.t() + def __describe__(reason), do: describe(reason) + + # Only the failure kind is reported, in fixed words. Nothing raw is + # interpolated: not the reason, not a TLS alert's text, not a header, and no + # part of the URL other than its host and port. So nothing from the request + # can end up in the message. The only terms printed are an atom the socket + # gave as the reason and the name of a TLS alert. defp describe({:failed_connect, info}) when is_list(info) do case List.keyfind(info, :inet, 0) || List.keyfind(info, :inet6, 0) do - {_family, _options, reason} when is_atom(reason) -> "connection failed (#{reason})" - _other -> "connection failed" + {_family, _options, reason} -> known_failure(reason) || connection_failed(reason) + _other -> "the connection failed" end end - defp describe(_reason), do: "request failed" + defp describe(reason), do: known_failure(reason) || "the request failed" + + defp connection_failed(reason) when is_atom(reason), do: "the connection failed (#{reason})" + defp connection_failed(_reason), do: "the connection failed" + + # The failures that get words of their own, or `nil`. A timeout and a closed + # connection can come from the connection attempt or from the request. + defp known_failure(:nxdomain), do: "the host name could not be resolved (nxdomain)" + defp known_failure(:econnrefused), do: "the connection was refused (econnrefused)" + + defp known_failure(reason) when reason in [:timeout, :etimedout], + do: "the request timed out (#{reason})" + + defp known_failure(reason) when reason in [:closed, :socket_closed_remotely], + do: "the server closed the connection (#{reason})" + + defp known_failure({:tls_alert, {alert, text}}), do: tls_failure(alert, text) + defp known_failure({:tls_alert, _other}), do: "the TLS handshake failed" + defp known_failure(_reason), do: nil + + # A certificate for another host name and a self-signed certificate arrive + # under a general alert, and which alert depends on the OTP release. They + # are told apart by the fixed word OTP puts in the alert's text. The text is + # only searched; it is never copied into the message. + defp tls_failure(alert, text) do + cond do + mentions?(text, "hostname_check_failed") -> + "the server's certificate is for another host name (hostname_check_failed)" + + mentions?(text, "selfsigned_peer") -> + "the server's certificate is self-signed (selfsigned_peer)" + + alert == :unknown_ca -> + "the server's certificate is not from a trusted certificate authority (unknown_ca)" + + alert == :certificate_expired -> + "the server's certificate has expired or is not valid yet (certificate_expired)" + + is_atom(alert) -> + "the TLS handshake failed (#{alert})" + + true -> + "the TLS handshake failed" + end + end + + defp mentions?(text, word) when is_list(text) or is_binary(text) do + text |> IO.chardata_to_string() |> String.contains?(word) + rescue + _not_text -> false + end + + defp mentions?(_text, _word), do: false defp error(message), do: {:error, %Error{message: message}} end diff --git a/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs b/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs index d6d04c5d..a5cc318f 100644 --- a/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs +++ b/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs @@ -35,6 +35,149 @@ defmodule WorkOS.WorkloadIdentity.GitHubActionsTest do System.put_env(@token_env, token) end + # "The GitHub Actions OIDC token endpoint at host:port", for the server. + defp endpoint(server) do + %URI{host: host, port: port} = URI.parse(server.url) + "The GitHub Actions OIDC token endpoint at #{host}:#{port}" + end + + # A loopback port that accepts each connection, reads what was sent and + # closes without answering. It is linked to the test process. + defp closing_server do + {:ok, listener} = + :gen_tcp.listen(0, [:binary, active: false, reuseaddr: true, ip: {127, 0, 0, 1}]) + + {:ok, port} = :inet.port(listener) + spawn_link(fn -> close_each(listener) end) + %{url: "http://127.0.0.1:#{port}"} + end + + defp close_each(listener) do + with {:ok, socket} <- :gen_tcp.accept(listener) do + _request = :gen_tcp.recv(socket, 0, 5_000) + :ok = :gen_tcp.close(socket) + close_each(listener) + end + end + + # -- TLS ---------------------------------------------------------------------- + # + # Certificates are made for each test. No key or certificate is stored in + # the repository, and no host other than this one is contacted. + + defp key, do: :public_key.generate_key({:namedCurve, :secp256r1}) + + # A server certificate with its key, and the root it was issued under. + # Options: `:host`, the DNS name in the certificate (default `localhost`), + # and `:validity`, a `{from, to}` pair of dates (default: valid now). + defp chain(opts \\ []) do + host = opts |> Keyword.get(:host, "localhost") |> String.to_charlist() + subject_alt_name = {:Extension, {2, 5, 29, 17}, false, [dNSName: host]} + + data = + :public_key.pkix_test_data(%{ + server_chain: %{ + root: [key: key(), digest: :sha256], + intermediates: [], + peer: + [key: key(), digest: :sha256, extensions: [subject_alt_name]] ++ + Keyword.take(opts, [:validity]) + }, + client_chain: %{root: [key: key()], intermediates: [], peer: [key: key()]} + }) + + %{ + cert: data.server_config[:cert], + key: data.server_config[:key], + roots: data.client_config[:cacerts] + } + end + + defp self_signed do + key = key() + %{cert: cert} = :public_key.pkix_test_root_cert(~c"self-signed", key: key, digest: :sha256) + %{cert: cert, key: {:ECPrivateKey, :public_key.der_encode(:ECPrivateKey, key)}} + end + + # Makes `roots` the only trusted roots until the test ends. The provider + # verifies against the operating system's trust store, which `:public_key` + # keeps for the whole VM once it is loaded, so it is cleared afterwards. + defp trust(roots) do + path = + Path.join(System.tmp_dir!(), "workos-gha-roots-#{System.unique_integer([:positive])}.pem") + + File.write!( + path, + :public_key.pem_encode(Enum.map(roots, &{:Certificate, &1, :not_encrypted})) + ) + + on_exit(fn -> :public_key.cacerts_clear() end) + + try do + :ok = :public_key.cacerts_load(String.to_charlist(path)) + after + File.rm(path) + end + end + + # An HTTPS server on a loopback port with the given certificate. After a + # completed handshake it reads the request, sends it to the test as + # `{:tls_request, ref, request}` and answers with a token. A handshake the + # client gives up on is skipped. It is linked to the test process. + defp tls_server(%{cert: cert, key: key}) do + test = self() + ref = make_ref() + + {:ok, listener} = + :ssl.listen(0, [ + :binary, + cert: cert, + key: key, + active: false, + reuseaddr: true, + ip: {127, 0, 0, 1}, + log_level: :none + ]) + + {:ok, {_address, port}} = :ssl.sockname(listener) + spawn_link(fn -> tls_accept(listener, test, ref) end) + %{url: "https://localhost:#{port}", ref: ref} + end + + defp tls_accept(listener, test, ref) do + with {:ok, socket} <- :ssl.transport_accept(listener) do + with {:ok, tls} <- :ssl.handshake(socket, 5_000), + {:ok, request} <- :ssl.recv(tls, 0, 5_000) do + send(test, {:tls_request, ref, request}) + body = JSON.encode!(%{"value" => "gha-jwt"}) + + :ok = + :ssl.send(tls, [ + "HTTP/1.1 200 OK\r\ncontent-length: #{byte_size(body)}\r\n", + "connection: close\r\n\r\n", + body + ]) + + :ssl.close(tls) + end + + tls_accept(listener, test, ref) + end + end + + # Calls the provider against an HTTPS server that must be refused, and + # returns the error. The request token never leaves the client. + defp refused_by_tls(server) do + configure(server, "SECRET-REQUEST-TOKEN") + + assert {:error, %Error{} = error} = GitHubActions.github_actions(@audience).() + refute inspect(error) =~ "SECRET-REQUEST-TOKEN" + + ref = server.ref + refute_receive {:tls_request, ^ref, _request} + error + end + test "WIF-GHA-01 GETs the request URL with the encoded audience appended and returns .value" do server = TestServer.start([json(%{"value" => "gha-jwt"})]) configure(server) @@ -139,10 +282,202 @@ defmodule WorkOS.WorkloadIdentity.GitHubActionsTest do System.put_env(@token_env, "SECRET-REQUEST-TOKEN") assert {:error, %Error{message: message} = error} = GitHubActions.github_actions(@audience).() - assert message =~ "could not be reached" + + assert message == + "The GitHub Actions OIDC token endpoint at 127.0.0.1:1 could not be reached: " <> + "the connection was refused (econnrefused)." + refute inspect(error) =~ "SECRET-REQUEST-TOKEN" end + test "a server that closes the connection without answering is named as that" do + server = closing_server() + configure(server) + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + + assert message == + endpoint(server) <> + " could not be reached: the server closed the connection (socket_closed_remotely)." + end + + test "a request URL with no host gets no host in the message" do + System.put_env(@url_env, "not-a-url") + System.put_env(@token_env, "gha-request-token") + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + + assert message == + "The GitHub Actions OIDC token endpoint could not be reached: the request failed." + end + + test "only the host and port of the request URL are named" do + System.put_env(@url_env, "http://user:SECRET-USERINFO@127.0.0.1:1/SECRET-PATH?k=SECRET-QUERY") + System.put_env(@token_env, "gha-request-token") + + assert {:error, %Error{message: message}} = GitHubActions.github_actions(@audience).() + + assert message == + "The GitHub Actions OIDC token endpoint at 127.0.0.1:1 could not be reached: " <> + "the connection was refused (econnrefused)." + end + + describe "an https endpoint" do + # The TLS client logs each alert it sends. + @describetag :capture_log + + test "with a certificate from a trusted authority, for its host name, gets the token" do + chain = chain() + trust(chain.roots) + server = tls_server(chain) + configure(server) + + assert GitHubActions.github_actions(@audience).() == {:ok, "gha-jwt"} + + ref = server.ref + assert_receive {:tls_request, ^ref, request} + assert request =~ "authorization: Bearer gha-request-token\r\n" + end + + test "with a certificate from an authority that is not trusted is refused, and says so" do + trust(chain().roots) + server = tls_server(chain()) + + assert refused_by_tls(server).message == + endpoint(server) <> + " could not be reached: the server's certificate is not from a trusted " <> + "certificate authority (unknown_ca)." + end + + test "with a certificate for another host name is refused, and says so" do + chain = chain(host: "elsewhere.test") + trust(chain.roots) + server = tls_server(chain) + + assert refused_by_tls(server).message == + endpoint(server) <> + " could not be reached: the server's certificate is for another host name " <> + "(hostname_check_failed)." + end + + test "with a certificate that has expired, or is not valid yet, is refused, and says so" do + # OTP sends the same alert for both. + for validity <- [{{2000, 1, 1}, {2000, 1, 2}}, {{3000, 1, 1}, {3000, 1, 2}}] do + chain = chain(validity: validity) + trust(chain.roots) + server = tls_server(chain) + + assert refused_by_tls(server).message == + endpoint(server) <> + " could not be reached: the server's certificate has expired or is not " <> + "valid yet (certificate_expired)." + end + end + + test "with a self-signed certificate is refused, and says so" do + trust(chain().roots) + server = tls_server(self_signed()) + + # OTP 25 sends this alert with no word for the cause. + why = + if System.otp_release() == "25", + do: "the TLS handshake failed (bad_certificate)", + else: "the server's certificate is self-signed (selfsigned_peer)" + + assert refused_by_tls(server).message == + endpoint(server) <> " could not be reached: " <> why <> "." + end + end + + test "every kind of failure gets fixed words, and nothing of the raw reason is copied" do + connect = fn reason -> + {:failed_connect, [{:to_address, {~c"host.test", 443}}, {:inet, [:inet], reason}]} + end + + alert = fn name, text -> connect.({:tls_alert, {name, String.to_charlist(text)}}) end + + for {reason, words} <- [ + {connect.(:nxdomain), "the host name could not be resolved (nxdomain)"}, + {{:failed_connect, [{:inet6, [:inet6], :nxdomain}]}, + "the host name could not be resolved (nxdomain)"}, + {connect.(:econnrefused), "the connection was refused (econnrefused)"}, + {:timeout, "the request timed out (timeout)"}, + {connect.(:timeout), "the request timed out (timeout)"}, + {connect.(:etimedout), "the request timed out (etimedout)"}, + {:socket_closed_remotely, "the server closed the connection (socket_closed_remotely)"}, + {connect.(:closed), "the server closed the connection (closed)"}, + {connect.(:ehostunreach), "the connection failed (ehostunreach)"}, + {alert.(:unknown_ca, "TLS client: generated CLIENT ALERT: Fatal - Unknown CA\n"), + "the server's certificate is not from a trusted certificate authority (unknown_ca)"}, + {alert.(:certificate_expired, "TLS client: Fatal - Certificate Expired\n"), + "the server's certificate has expired or is not valid yet (certificate_expired)"}, + # A host name mismatch comes under either alert, by OTP release. + {alert.( + :handshake_failure, + "Fatal - Handshake Failure\n {bad_cert,hostname_check_failed}" + ), "the server's certificate is for another host name (hostname_check_failed)"}, + {alert.( + :bad_certificate, + "Fatal - Bad Certificate\n {bad_cert,{hostname_check_failed,{requested,\"SECRET\"}}}" + ), "the server's certificate is for another host name (hostname_check_failed)"}, + {alert.(:bad_certificate, "Fatal - Bad Certificate\n selfsigned_peer"), + "the server's certificate is self-signed (selfsigned_peer)"}, + {alert.(:protocol_version, "SECRET"), "the TLS handshake failed (protocol_version)"}, + {connect.({:tls_alert, ~c"an alert in another form, SECRET"}), + "the TLS handshake failed"}, + {connect.({:options, {:cacertfile, ~c"SECRET"}}), "the connection failed"}, + {{:failed_connect, [{:to_address, {~c"host.test", 443}}]}, "the connection failed"}, + # What :httpc returns for a header value it cannot encode. + {{:invalid_header, {~c"authorization", ~c"Bearer SECRET"}}, "the request failed"}, + {:invalid_uri, "the request failed"} + ] do + assert GitHubActions.__describe__(reason) == words + end + end + + test "a request token that is not visible ASCII is refused before any request is made" do + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + + for token <- [ + "SECRET-REQUEST-TOKEN\n", + "SECRET-REQUEST-TOKEN\r\n", + "SECRET-REQUEST-TOKEN\r\nx-injected: yes", + "SECRET-REQUEST-TOKEN\nx-injected: yes", + "SECRET-REQUEST\tTOKEN", + "SECRET-REQUEST TOKEN", + " SECRET-REQUEST-TOKEN", + "SECRET-REQUEST-TOKEN\x7F", + "SECRET-REQUEST-TÖKEN" + ] do + configure(server, token) + + assert {:error, %Error{message: message} = error} = + GitHubActions.github_actions(@audience).() + + assert message == + "ACTIONS_ID_TOKEN_REQUEST_TOKEN contains a character that is not allowed in an " <> + "HTTP header, such as a line break. GitHub Actions sets this variable; pass " <> + "it to the program unchanged." + + refute inspect(error) =~ "SECRET" + end + + ref = server.ref + refute_receive {:request, ^ref, _request} + end + + test "a request token of visible ASCII is sent as it is" do + token = for byte <- 0x21..0x7E, into: "", do: <> + server = TestServer.start([json(%{"value" => "gha-jwt"})]) + configure(server, token) + + assert GitHubActions.github_actions(@audience).() == {:ok, "gha-jwt"} + + ref = server.ref + assert_receive {:request, ^ref, request} + assert request.headers["authorization"] == "Bearer " <> token + end + test "the audience is required" do assert_raise FunctionClauseError, fn -> GitHubActions.github_actions("") end end From 18bf9932ac3ce9913a543b400e86514d16198df7 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 14:11:56 -0500 Subject: [PATCH 12/15] feat(workload-identity): add the client secret accessor for sign-in calls The sign-in calls on /user_management/authenticate and the SSO token exchange on /sso/token send the API key as `client_secret`. A client built with `credentials:` has no API key, so such a call sends the request without one. `WorkOS.Client.put_client_secret/3` is the one place that decides what those requests carry: - a client with an API key: the key, as before - a public client (`WorkOS.PublicClient`): what it got before - a client that authenticates with workload identity and has no key: `WorkOS.ConfigurationError`, raised before any request is sent and before the credentials are asked for a token, naming the function that was called A `client_secret` the caller passes is kept in every case. The generated functions still read the key themselves. They call this function once they are regenerated; it is added first so that the regenerated code finds it. The README names the calls that need a client built with an API key. --- README.md | 2 + lib/workos/client.ex | 27 +++++ test/workos/client_secret_test.exs | 185 +++++++++++++++++++++++++++++ 3 files changed, 214 insertions(+) create mode 100644 test/workos/client_secret_test.exs diff --git a/README.md b/README.md index 5d1be985..99ccdaca 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,8 @@ client = WorkOS.Client.new(credentials: credentials) `:client_id` falls back to the `WORKOS_CLIENT_ID` environment variable. That is the only variable the credentials read: `:token_url` (required) and `:scope` (optional) are set only in code. Passing both `api_key:` and `credentials:` raises `WorkOS.ConfigurationError`. With `credentials:`, `WORKOS_API_KEY` is ignored. +A client built with `credentials:` has no API key, so use a client built with `api_key:` for the calls that send the key as the client secret: `WorkOS.SSO.get_profile_and_token/3`, the `WorkOS.UserManagement.authenticate_with_*` functions other than `authenticate_with_device_code/3`, and the helpers that call them (`WorkOS.AuthKit.pkce_code_exchange/3`, `WorkOS.SSO.PKCE.code_exchange/3`, `WorkOS.Session.refresh/2` and `WorkOS.Session.refresh_session/4`). + `:token_url` must be an absolute `https` URL with a host. The request to it carries the workload's identity token and the response carries the access token, so anything else is refused when the credentials start: an `http://` URL, a URL with no scheme or no host, any other scheme. There is no exception for `localhost` or loopback addresses, and no option or environment variable turns the check off. `start_link/1` then returns `{:error, %WorkOS.WorkloadIdentityError{code: "invalid_configuration"}}` with the description `token_url must be an absolute https URL`. `:environment_id` is optional, and it is set only in code: the SDK reads no environment variable for it. The server binds a workload identity client to exactly one environment, so the `x-url-environment-id` header selects nothing, and the SDK sends it only when an environment ID is set. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. diff --git a/lib/workos/client.ex b/lib/workos/client.ex index 9d5a9763..4cb95662 100644 --- a/lib/workos/client.ex +++ b/lib/workos/client.ex @@ -390,6 +390,33 @@ defmodule WorkOS.Client do def put_inferred(params, _key, nil), do: params def put_inferred(params, key, value), do: Map.put_new(params, key, value) + # Fills `client_secret` for a request that sends the API key as the client + # secret: the sign-in calls and the SSO token exchange. `function` is the + # name of the calling function, for the error message. `params` has string + # keys by now (`merge_defaults/2`). + # + # A `client_secret` the caller passed is kept. A client that authenticates + # with workload identity credentials has no API key to send, so the call is + # refused here, before any request is sent and before the credentials are + # asked for a token. Every other client is handled as before: a key is + # filled in, and a client with no credentials and no key + # (`WorkOS.PublicClient`) gets what it got before. + @doc false + @spec put_client_secret(map(), t(), String.t()) :: map() + def put_client_secret(%{"client_secret" => _passed} = params, _client, _function), do: params + + def put_client_secret(_params, %__MODULE__{api_key: key, credentials: credentials}, function) + when not is_nil(credentials) and key in [nil, ""] do + raise WorkOS.ConfigurationError, + message: + "#{function} 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." + end + + def put_client_secret(params, %__MODULE__{api_key: api_key}, _function), + do: put_inferred(params, "client_secret", api_key) + # nil query values are omitted rather than sent as `key=`, matching build_url/3. defp put_query(req_options, query) do case Enum.reject(query, fn {_k, v} -> is_nil(v) end) do diff --git a/test/workos/client_secret_test.exs b/test/workos/client_secret_test.exs new file mode 100644 index 00000000..f7c240ba --- /dev/null +++ b/test/workos/client_secret_test.exs @@ -0,0 +1,185 @@ +# @oagen-ignore-file + +defmodule WorkOS.ClientSecretTest do + # `WorkOS.Client.put_client_secret/3`: what a request that sends the API key + # as the client secret gets from each kind of client. No test touches the + # network: the token endpoint and the API are function plugs that tell the + # test when they are reached. + use ExUnit.Case, async: true + + alias WorkOS.SSO.PKCE + alias WorkOS.WorkloadIdentity.Credentials + + @workload_identity_message "authenticate_with_password 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." + + defp key_client, do: WorkOS.Client.new(api_key: "sk_test_key", client_id: "client_123") + + # The client a `WorkOS.PublicClient` wraps, with the API replaced by a plug + # that hands each request to the test. + defp public_client(responses \\ %{}) do + %WorkOS.Client{ + WorkOS.PublicClient.new("client_123").client + | req_options: [plug: api_plug(responses)] + } + end + + # A client that authenticates with workload identity credentials, and the + # credentials process behind it. The provider, the token endpoint and the + # API each tell the test when they are reached. + defp workload_identity_client do + test = self() + + {:ok, credentials} = + Credentials.start_link( + client_id: "client_wif_test", + token_url: "https://auth.wif.test/oauth2/token", + identity_token_provider: fn -> + send(test, :provider_invoked) + {:ok, "assertion-1"} + end, + req_options: [ + plug: fn conn -> + send(test, :exchange_requested) + Req.Test.json(conn, %{"access_token" => "access-1", "expires_in" => 300}) + end + ] + ) + + client = + WorkOS.Client.new( + credentials: credentials, + client_id: "client_wif_test", + req_options: [plug: api_plug()] + ) + + {client, credentials} + end + + # Answers with the body registered for the request path, or `{}`. + defp api_plug(responses \\ %{}) do + test = self() + + fn conn -> + {:ok, body, conn} = Plug.Conn.read_body(conn) + send(test, {:api_requested, conn.request_path, body}) + Req.Test.json(conn, Map.get(responses, conn.request_path, %{})) + end + end + + defp put_client_secret(params, client, function \\ "authenticate_with_password"), + do: WorkOS.Client.put_client_secret(params, client, function) + + describe "put_client_secret/3" do + test "a client with an API key sends the key as the client secret" do + assert put_client_secret(%{"code" => "code_123"}, key_client()) == + %{"code" => "code_123", "client_secret" => "sk_test_key"} + end + + test "a client_secret the caller passed is kept, whatever the client" do + params = %{"code" => "code_123", "client_secret" => "sk_passed"} + {workload_identity_client, _credentials} = workload_identity_client() + + assert put_client_secret(params, key_client()) == params + assert put_client_secret(params, public_client()) == params + assert put_client_secret(params, workload_identity_client) == params + end + + test "a public client gets what it got before" do + params = %{"code" => "code_123"} + public_client = public_client() + + # A public client's key is the empty string, and that is what the + # request has always carried. + assert put_client_secret(params, public_client) == + WorkOS.Client.put_inferred(params, "client_secret", public_client.api_key) + + assert put_client_secret(params, public_client) == + %{"code" => "code_123", "client_secret" => ""} + end + + test "a client with no key and no credentials leaves the field out" do + client = %WorkOS.Client{public_client() | api_key: nil} + + assert put_client_secret(%{"code" => "code_123"}, client) == %{"code" => "code_123"} + end + + test "a workload identity client is refused before any request or token exchange" do + {client, credentials} = workload_identity_client() + + assert_raise WorkOS.ConfigurationError, @workload_identity_message, fn -> + put_client_secret(%{"email" => "user@example.com", "password" => "pw"}, client) + end + + # Nothing was asked of the credentials: no provider call, no exchange, + # no cached token. Nothing was sent to the API either. + assert %{token: nil, generation: 0, inflight: nil} = :sys.get_state(credentials) + refute_received :provider_invoked + refute_received :exchange_requested + refute_received {:api_requested, _path, _body} + + # The same client does exchange and send for an ordinary request, so + # the silence above is the refusal and not a client that cannot work. + assert {:ok, _body} = WorkOS.Client.request(client, :get, "/organizations") + assert_received :provider_invoked + assert_received :exchange_requested + assert_received {:api_requested, "/organizations", _body} + end + + test "a workload identity client with an empty key is refused too" do + {client, _credentials} = workload_identity_client() + + assert_raise WorkOS.ConfigurationError, @workload_identity_message, fn -> + put_client_secret(%{}, %WorkOS.Client{client | api_key: ""}) + end + end + + test "the error names the calling function" do + {client, _credentials} = workload_identity_client() + + error = + assert_raise WorkOS.ConfigurationError, fn -> + put_client_secret(%{}, client, "get_profile_and_token") + end + + assert error.message == + String.replace( + @workload_identity_message, + "authenticate_with_password", + "get_profile_and_token" + ) + end + end + + describe "a public client's PKCE code exchange" do + test "is still sent, for AuthKit and for SSO" do + client = + public_client(%{ + "/user_management/authenticate" => + WorkOS.TestFixtures.fixture("user_management/authenticate_with_code"), + "/sso/token" => WorkOS.TestFixtures.fixture("sso/get_profile_and_token") + }) + + params = %{code: "code_123", code_verifier: "verifier_123"} + + assert {:ok, %WorkOS.AuthenticateResponse{}} = + WorkOS.AuthKit.pkce_code_exchange(client, params) + + assert {:ok, %WorkOS.SSOTokenResponse{}} = PKCE.code_exchange(client, params) + + for path <- ["/user_management/authenticate", "/sso/token"] do + assert_received {:api_requested, ^path, body} + + assert JSON.decode!(body) == %{ + "grant_type" => "authorization_code", + "code" => "code_123", + "code_verifier" => "verifier_123", + "client_id" => "client_123", + "client_secret" => "" + } + end + end + end +end From 434f5e9f6cf8a16f891cbf1e65c9416f67c10a9b Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:11:52 -0500 Subject: [PATCH 13/15] fix(workload-identity): report a raised provider exception by name only When an identity token provider raised, the exchange copied the exception's message into the error's description and kept the exception as its reason. Some exceptions print the value they failed on. A provider that matches on the response it fetched raises a `MatchError` when the match fails, and its message is the whole response: no match of right hand side value: %{"value" => ""} So the identity token could end up in the message of the `WorkOS.WorkloadIdentityError` and in its inspected form, which is where an application logs it from. An exception the provider raises is now reported by its module name alone: the description is `the provider raised MatchError` and the reason is `MatchError`. Neither the message nor the exception is kept. A reason the provider returns in `{:error, reason}` is unchanged: it is the provider's own choice of words, and it is how the platform providers say what to fix. The documentation now says that a provider must not put the token in it. --- lib/workos/workload_identity.ex | 8 +++ lib/workos/workload_identity/exchange.ex | 16 +++++- lib/workos/workload_identity_error.ex | 5 +- test/workos/workload_identity_test.exs | 70 ++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/lib/workos/workload_identity.ex b/lib/workos/workload_identity.ex index ef22b6d0..6313ae2f 100644 --- a/lib/workos/workload_identity.ex +++ b/lib/workos/workload_identity.ex @@ -18,6 +18,14 @@ defmodule WorkOS.WorkloadIdentity do that returns `{:ok, token}` or `{:error, reason}`. It is called again for every exchange attempt, so it needs no cache and no retries of its own. + The `reason` a provider returns ends up in the + `WorkOS.WorkloadIdentityError`: as its `:reason`, and in its message when + it is a string, an atom or an exception. So a provider never puts the token + in it. An exception a provider raises is reported by its module name only, + because the message of an exception such as `MatchError` prints the value + that failed to match, and that value can be the response that holds the + token. + This module has the two providers that read a token another process has already written somewhere: `token_file/1` and `token_env/1`. Any function of the same shape works as a custom provider: diff --git a/lib/workos/workload_identity/exchange.ex b/lib/workos/workload_identity/exchange.ex index 704c3260..c740b83b 100644 --- a/lib/workos/workload_identity/exchange.ex +++ b/lib/workos/workload_identity/exchange.ex @@ -87,7 +87,7 @@ defmodule WorkOS.WorkloadIdentity.Exchange do ) end rescue - exception -> provider_failed(Exception.message(exception), exception) + exception -> provider_raised(exception) catch kind, _value -> provider_failed("the provider stopped with a #{kind}", kind) end @@ -98,8 +98,18 @@ defmodule WorkOS.WorkloadIdentity.Exchange do defp provider_failed(description, reason), do: {:retry, WorkloadIdentityError.new("provider_failed", description, reason), nil} - # A provider's error is described only when it is already text. Other terms - # are kept in `:reason` and never interpolated. + # An exception the provider raises is reported by its module name alone: + # neither its message nor the exception itself is kept. Both can hold the + # token. A provider that matches on the response it fetched raises a + # `MatchError` when the match fails, and that error prints the whole + # response. A provider that wants its own words in the error returns + # `{:error, reason}`. + defp provider_raised(%{__struct__: module}), + do: provider_failed("the provider raised #{inspect(module)}", module) + + # The reason a provider returns is its own choice of words, so it is shown. + # It is described only when it is already text. Other terms are kept in + # `:reason` and never interpolated. defp describe(%{__exception__: true} = exception), do: Exception.message(exception) defp describe(reason) when is_binary(reason), do: reason defp describe(reason) when is_atom(reason), do: Atom.to_string(reason) diff --git a/lib/workos/workload_identity_error.ex b/lib/workos/workload_identity_error.ex index d104aa36..a39867eb 100644 --- a/lib/workos/workload_identity_error.ex +++ b/lib/workos/workload_identity_error.ex @@ -11,8 +11,9 @@ defmodule WorkOS.WorkloadIdentityError do * `:description` — the token endpoint's `error_description`, cut to 500 characters, or a short detail for an SDK code; `""` when there is none * `:hint` — one sentence on what to check; never empty - * `:reason` — the underlying error when there is one (the provider's - error, or the transport exception), otherwise `nil` + * `:reason` — the underlying error when there is one, otherwise `nil`: + the reason the provider returned, the name of the exception the + provider raised, or the transport exception The message is `: `, followed by the description when there is one. Neither the identity token nor the access token ever appears in it. diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index e9405555..5793fd12 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -846,6 +846,76 @@ defmodule WorkOS.WorkloadIdentityTest do refute inspect(error) =~ "SECRET-ASSERTION-VALUE" end + # What a token source answers with, as a term the compiler knows nothing + # about, so that a failed match on it is a runtime error. + defp identity_response(token), do: JSON.decode!(JSON.encode!(%{"value" => token})) + + test "WIF-17 a token inside an exception the provider raises stays out of the error" do + secret = "SECRET-ASSERTION-VALUE" + + raising_providers = [ + # A failed match: the message of a MatchError prints the whole term. + {MatchError, + fn -> + %{"token" => token} = identity_response(secret) + {:ok, token} + end}, + # A missing key: the message of a KeyError prints the whole map. + {KeyError, fn -> {:ok, Map.fetch!(identity_response(secret), "token")} end}, + # An exception of the provider's own, with the response in its message. + {ArgumentError, fn -> raise ArgumentError, "unexpected response: #{secret}" end} + ] + + for {exception, provider} <- raising_providers do + token_endpoint = token_endpoint() + + {result, log} = + with_log([level: :debug], fn -> + token_endpoint + |> start_credentials(identity_token_provider: provider) + |> client(api()) + |> get() + end) + + assert {:error, %WorkloadIdentityError{code: "provider_failed"} = error} = result + assert requests(token_endpoint) == [] + + # Only the exception's name is kept: not its message, not its fields. + assert error.description == "the provider raised #{inspect(exception)}" + assert error.reason == exception + + for text <- [ + log, + Exception.message(error), + inspect(error), + inspect(error, structs: false, limit: :infinity, printable_limit: :infinity) + ] do + refute text =~ secret + end + end + end + + test "WIF-17 a reason the provider returns is still described in the provider's words" do + reasons = [ + {"the vault is sealed", "the vault is sealed"}, + {:vault_sealed, "vault_sealed"}, + {%RuntimeError{message: "the vault is sealed"}, "the vault is sealed"}, + # A term that is not text is kept, and never interpolated. + {{:vault, :sealed}, ""} + ] + + for {reason, description} <- reasons do + assert {:error, %WorkloadIdentityError{code: "provider_failed"} = error} = + token_endpoint() + |> start_credentials(identity_token_provider: fn -> {:error, reason} end) + |> client(api()) + |> get() + + assert error.description == description + assert error.reason == reason + end + end + test "WIF-18 the exchange request does not follow redirects" do elsewhere = token_endpoint() From b4baab9721712aece9bab5d47bf48e4587da82d0 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:26:12 -0500 Subject: [PATCH 14/15] fix(workload-identity): mark an assertion the token endpoint repeats as [redacted] A token endpoint may repeat the assertion it was sent in the `error` or `error_description` of its answer. The exchange already replaced it before the error kept either string, but with `[REDACTED]`. The marker is now `[redacted]`, the same text in every WorkOS SDK, so a log search or an alert written for one SDK matches them all. The rule, as the tests now pin it: - every occurrence is replaced, in `error` and in `error_description` - for a final error (a 400) and for a retried one (a 503 until retries run out) - before the description is cut to 500 characters, so a cut cannot leave the start of a token behind The identity token then appears in no message, no inspected form of the error and no log line. --- lib/workos/workload_identity/exchange.ex | 11 +++- lib/workos/workload_identity_error.ex | 4 +- test/workos/workload_identity_test.exs | 84 ++++++++++++++++++++---- 3 files changed, 83 insertions(+), 16 deletions(-) diff --git a/lib/workos/workload_identity/exchange.ex b/lib/workos/workload_identity/exchange.ex index c740b83b..b16ff56d 100644 --- a/lib/workos/workload_identity/exchange.ex +++ b/lib/workos/workload_identity/exchange.ex @@ -30,7 +30,7 @@ defmodule WorkOS.WorkloadIdentity.Exchange do # among the Req options must not send the identity token anywhere else. @fixed_options [retry: false, redirect: false, decode_body: false, auth: nil] - @redacted "[REDACTED]" + @redacted "[redacted]" @type result :: {:ok, access_token :: String.t(), lifetime_ms :: pos_integer()} @@ -216,8 +216,13 @@ defmodule WorkOS.WorkloadIdentity.Exchange do defp decode(_response), do: nil - # The endpoint's own text goes into the error, so an endpoint that echoes - # the assertion back must not be able to put it there. + # The endpoint's own text goes into the error, and an endpoint may repeat + # the assertion it was sent in `error` or in `error_description`. Every + # occurrence is replaced before the error keeps either string, for a final + # error and for a retried one alike. The description is cut to its limit + # after that (`WorkloadIdentityError.new/3`), so a cut cannot leave the + # start of a token behind. The assertion is never empty here: an empty + # token is a provider failure, and nothing is sent. defp oauth_error(%{"error" => code} = body, assertion) when is_binary(code) and code != "", do: {scrub(code, assertion), scrub(body["error_description"], assertion)} diff --git a/lib/workos/workload_identity_error.ex b/lib/workos/workload_identity_error.ex index a39867eb..7eea87a2 100644 --- a/lib/workos/workload_identity_error.ex +++ b/lib/workos/workload_identity_error.ex @@ -9,7 +9,9 @@ defmodule WorkOS.WorkloadIdentityError do `"invalid_grant"`), or one of the SDK's own codes: `"exchange_failed"`, `"invalid_response"`, `"provider_failed"`, `"invalid_configuration"` * `:description` — the token endpoint's `error_description`, cut to 500 - characters, or a short detail for an SDK code; `""` when there is none + characters, or a short detail for an SDK code; `""` when there is none. + If the endpoint repeats the identity token in its `error` or + `error_description`, the token is replaced with `[redacted]` first * `:hint` — one sentence on what to check; never empty * `:reason` — the underlying error when there is one, otherwise `nil`: the reason the provider returned, the name of the exception the diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs index 5793fd12..7069c576 100644 --- a/test/workos/workload_identity_test.exs +++ b/test/workos/workload_identity_test.exs @@ -827,23 +827,83 @@ defmodule WorkOS.WorkloadIdentityTest do refute log =~ "SECRET-ACCESS-VALUE" end - test "WIF-17 an assertion echoed back by the token endpoint is removed from the error" do - token_endpoint = - token_endpoint([ - {:oauth_error, "invalid_grant", "Rejected assertion SECRET-ASSERTION-VALUE."} - ]) + test "WIF-17 an assertion the token endpoint repeats is replaced before the error keeps it" do + secret = "SECRET-ASSERTION-VALUE" + + body = + JSON.encode!(%{ + "error" => "invalid_grant", + "error_description" => "JWT #{secret} failed validation" + }) + + scenarios = [ + # A terminal OAuth error. + {token_endpoint([{:status, 400, [], body}]), 1}, + # A failure that is retried until retries run out: the last one is kept. + {mock({:status, 503, [], body}, []), WorkOS.Client.default_max_retries() + 1} + ] + + for {token_endpoint, exchanges} <- scenarios do + {result, log} = + with_log([level: :debug], fn -> + token_endpoint + |> start_credentials(identity_token_provider: fn -> {:ok, secret} end) + |> client(api()) + |> get() + end) + + assert {:error, %WorkloadIdentityError{code: "invalid_grant"} = error} = result + assert error.description == "JWT [redacted] failed validation" + assert length(requests(token_endpoint)) == exchanges + + for text <- [ + log, + Exception.message(error), + inspect(error), + inspect(error, structs: false, limit: :infinity, printable_limit: :infinity) + ] do + refute text =~ secret + end + end + end + + test "WIF-17 a repeated assertion is replaced in the error code too, and each time it occurs" do + secret = "SECRET-ASSERTION-VALUE" + + body = + JSON.encode!(%{ + "error" => "rejected_#{secret}", + "error_description" => "#{secret} is not valid: #{secret}" + }) + + assert {:error, %WorkloadIdentityError{} = error} = + token_endpoint([{:status, 400, [], body}]) + |> start_credentials(identity_token_provider: fn -> {:ok, secret} end) + |> client(api()) + |> get() + + assert error.code == "rejected_[redacted]" + assert error.description == "[redacted] is not valid: [redacted]" + refute Exception.message(error) =~ secret + refute inspect(error) =~ secret + end + + test "WIF-17 a repeated assertion is replaced before the description is cut" do + secret = "SECRET-ASSERTION-VALUE" + + # The assertion starts 10 characters before the limit. Cutting first would + # leave its first 10 characters at the end of the description. + description = String.duplicate("x", 490) <> secret <> " failed validation" + body = JSON.encode!(%{"error" => "invalid_grant", "error_description" => description}) assert {:error, %WorkloadIdentityError{code: "invalid_grant"} = error} = - token_endpoint - |> start_credentials( - identity_token_provider: fn -> {:ok, "SECRET-ASSERTION-VALUE"} end - ) + token_endpoint([{:status, 400, [], body}]) + |> start_credentials(identity_token_provider: fn -> {:ok, secret} end) |> client(api()) |> get() - assert error.description == "Rejected assertion [REDACTED]." - refute Exception.message(error) =~ "SECRET-ASSERTION-VALUE" - refute inspect(error) =~ "SECRET-ASSERTION-VALUE" + assert error.description == String.duplicate("x", 490) <> "[redacted]" + refute error.description =~ String.slice(secret, 0, 6) end # What a token source answers with, as a term the compiler knows nothing From b1927496514cd228267bc80e7f76f2c3649b2944 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:26:12 -0500 Subject: [PATCH 15/15] refactor(workload-identity): turn the AWS client's retries off in code One call of the AWS provider has to be one request to STS: the token exchange calls the provider again when it fails, so a retry inside the provider multiplies the requests. That was already so, because `aws` sends a request again only when `enable_retries?` is set and the provider did not set it. With the option on, one provider call made 11 requests to an STS that answered 429, 500 or 503. The provider now passes `enable_retries?: false` itself, so the rule does not depend on the default of a dependency. Tests, against a local server that stands in for STS: - one provider call is one request when STS answers with a throttling error, 429, 500 or 503 - a request that gets no answer fails at the time limit - the limit is 10 seconds, for connecting and for the request, the same as in the GitHub Actions and Google Cloud providers The `:httpc` adapter reads the limit from its options so that a test can shorten it. The provider sets no options. --- workload_identity_aws/README.md | 2 +- .../lib/workos/workload_identity/aws.ex | 18 ++++- .../workload_identity/aws/http_client.ex | 12 +++- .../workos/workload_identity/aws_test.exs | 71 ++++++++++++++++++- 4 files changed, 96 insertions(+), 7 deletions(-) diff --git a/workload_identity_aws/README.md b/workload_identity_aws/README.md index c2abbabc..a470f157 100644 --- a/workload_identity_aws/README.md +++ b/workload_identity_aws/README.md @@ -33,6 +33,6 @@ end client = WorkOS.Client.new(credentials: credentials) ``` -`aws_sts/2` takes the audience and an optional region, and returns a zero-arity function. Without a region argument it uses `AWS_REGION`, then `AWS_DEFAULT_REGION`, then the region the credential chain reports; it raises `ArgumentError` when none is found. Each call makes one signed request to the regional STS endpoint, asks for an `RS256` token, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.AWS.Error{}}`. +`aws_sts/2` takes the audience and an optional region, and returns a zero-arity function. Without a region argument it uses `AWS_REGION`, then `AWS_DEFAULT_REGION`, then the region the credential chain reports; it raises `ArgumentError` when none is found. Each call makes one signed request to the regional STS endpoint, asks for an `RS256` token, and returns `{:ok, token}` or `{:error, %WorkOS.WorkloadIdentity.AWS.Error{}}`. The request is not sent again when STS throttles the caller or answers with a server error, because the WorkOS SDK calls the provider again as part of the token exchange, and it has 10 seconds to connect and 10 seconds to be answered. AWS credentials come from the `aws_credentials` application's default chain: environment variables, shared credential files, ECS task roles, EKS Pod Identity, IAM roles for service accounts, and EC2 instance profiles. See its documentation to change the chain. diff --git a/workload_identity_aws/lib/workos/workload_identity/aws.ex b/workload_identity_aws/lib/workos/workload_identity/aws.ex index 03222b86..3be7811b 100644 --- a/workload_identity_aws/lib/workos/workload_identity/aws.ex +++ b/workload_identity_aws/lib/workos/workload_identity/aws.ex @@ -29,8 +29,10 @@ defmodule WorkOS.WorkloadIdentity.AWS do ) The provider holds no cache and does not retry; the WorkOS SDK retries it as - part of the token exchange. The token is never logged and never placed in - an error. + part of the token exchange. One call of the provider is one request to STS, + also when STS throttles the caller or answers with a server error, and the + request has 10 seconds to connect and 10 seconds to be answered. The token + is never logged and never placed in an error. """ alias WorkOS.WorkloadIdentity.AWS.HTTPClient @@ -113,13 +115,23 @@ defmodule WorkOS.WorkloadIdentity.AWS do defp get_web_identity_token(region, input) do case credentials() do %{access_key_id: _, secret_access_key: _} = credentials -> - credentials |> __client__(region) |> AWS.STS.get_web_identity_token(input) + credentials |> __client__(region) |> __get_web_identity_token__(input) _none -> {:error, :no_credentials} end end + # The one STS request of a provider call. `aws` sends a request again only + # when it is asked to, and here it is told not to: the WorkOS SDK calls the + # provider again as part of the token exchange, so a retry in here would + # multiply the requests. + @doc false + @spec __get_web_identity_token__(AWS.Client.t(), map()) :: + {:ok, map() | nil, term()} | {:error, term()} + def __get_web_identity_token__(%AWS.Client{} = client, input), + do: AWS.STS.get_web_identity_token(client, input, enable_retries?: false) + # An `aws` client for the regional STS endpoint, from one set of credentials # out of the chain. Building it is a struct literal: it holds no connection, # so it is rebuilt per call to pick up rotated credentials. diff --git a/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex b/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex index e9b96459..d59385e4 100644 --- a/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex +++ b/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex @@ -9,18 +9,26 @@ defmodule WorkOS.WorkloadIdentity.AWS.HTTPClient do @behaviour AWS.HTTPClient + # The limit on connecting and the limit on the request, each. It is the + # limit the GitHub Actions and Google Cloud providers use. @timeout_ms 10_000 + @spec timeout_ms() :: pos_integer() + def timeout_ms, do: @timeout_ms + + # `:timeout_ms` among the options is a test seam. The provider sets no + # options, so its requests always get the limit above. @impl AWS.HTTPClient - def request(method, url, body, headers, _options) do + def request(method, url, body, headers, options) do {content_type, headers} = pop_content_type(headers) + timeout_ms = Keyword.get(options, :timeout_ms, @timeout_ms) request = {String.to_charlist(url), Enum.map(headers, &to_charlists/1), content_type, IO.iodata_to_binary(body)} http_options = - [timeout: @timeout_ms, connect_timeout: @timeout_ms, autoredirect: false] ++ + [timeout: timeout_ms, connect_timeout: timeout_ms, autoredirect: false] ++ ssl_options(url) case :httpc.request(method, request, http_options, body_format: :binary) do diff --git a/workload_identity_aws/test/workos/workload_identity/aws_test.exs b/workload_identity_aws/test/workos/workload_identity/aws_test.exs index 869e023a..06b39188 100644 --- a/workload_identity_aws/test/workos/workload_identity/aws_test.exs +++ b/workload_identity_aws/test/workos/workload_identity/aws_test.exs @@ -84,7 +84,27 @@ defmodule WorkOS.WorkloadIdentity.AWSTest do |> Provider.__client__("us-east-1") |> AWS.Client.put_http_client({StubHTTPClient, [test: self(), response: response]}) - fn "us-east-1", input -> AWS.STS.get_web_identity_token(client, input) end + fn "us-east-1", input -> Provider.__get_web_identity_token__(client, input) end + end + + # The `aws` client the provider builds, its `:httpc` adapter and the call + # the provider makes, sent to a local server instead of STS. Only the + # address differs. `http_options` can shorten the adapter's time limit. + defp local_sts(url, http_options \\ []) do + %URI{host: host, port: port} = URI.parse(url) + + client = + %{access_key_id: "AKIDEXAMPLE", secret_access_key: "secret", token: "session-token"} + |> Provider.__client__("us-east-1") + |> Map.merge(%{proto: "http", endpoint: host, port: port}) + |> AWS.Client.put_http_client({HTTPClient, http_options}) + + fn "us-east-1", input -> Provider.__get_web_identity_token__(client, input) end + end + + defp error_xml(code) do + "Sender#{code}" <> + "mock" end test "WIF-AWS-01 calls STS GetWebIdentityToken with the audience and RS256 in the given region" do @@ -196,6 +216,55 @@ defmodule WorkOS.WorkloadIdentity.AWSTest do refute inspect(error) =~ "SECRET-TOKEN-VALUE" end + test "one provider call is one STS request, also when STS throttles the caller or fails" do + failures = [ + {400, "Throttling"}, + {429, "Throttling"}, + {500, "InternalFailure"}, + {503, "ServiceUnavailable"} + ] + + for {status, code} <- failures do + server = TestServer.start([{status, [], error_xml(code)}]) + provider = Provider.__provider__(@audience, "us-east-1", local_sts(server.url)) + + assert {:error, %Error{message: message}} = provider.() + assert message =~ "sts:GetWebIdentityToken failed: STS returned #{code} (HTTP #{status})" + + # A retry would have been sent before the provider returned. + ref = server.ref + assert_received {:request, ^ref, %{method: "POST", target: "/"}} + refute_received {:request, ^ref, _second_request} + end + end + + test "an STS request that gets no answer fails at the time limit" do + # A socket that completes the connection and never answers. + {:ok, listener} = + :gen_tcp.listen(0, [:binary, active: false, reuseaddr: true, ip: {127, 0, 0, 1}]) + + {:ok, port} = :inet.port(listener) + sts = local_sts("http://127.0.0.1:#{port}", timeout_ms: 200) + + {microseconds, result} = + :timer.tc(fn -> Provider.__provider__(@audience, "us-east-1", sts).() end) + + assert {:error, %Error{message: message}} = result + assert message =~ "sts:GetWebIdentityToken failed: timeout" + + # It waited for the limit it was given, not for the 10 seconds it has + # when nothing shortens it. + assert microseconds >= 200_000 + assert microseconds < 5_000_000 + end + + test "the time limit is 10 seconds, and the provider's client does not change it" do + assert HTTPClient.timeout_ms() == 10_000 + + credentials = %{access_key_id: "AKIDEXAMPLE", secret_access_key: "secret"} + assert Provider.__client__(credentials, "us-east-1").http_client == {HTTPClient, []} + end + test "a response with no token is an error" do for result <- [issued(""), {:ok, %{}, %{status_code: 200}}, {:ok, nil, %{status_code: 200}}] do provider = Provider.__provider__(@audience, "us-east-1", sts_stub(result))