diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3739dd0..eb161c6 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 feae866..30f746a 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 eb216db..df8c920 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 c36ca2c..ea53266 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 ada7355..8c8c3a1 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 beb6bbc..99ccdac 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,83 @@ 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` 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`. + +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, + token_url: "https://.../oauth2/token", + 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 +# 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 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. + ## 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 b1b2a07..4cb9566 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,23 @@ 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, 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. """ @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 +129,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 +147,198 @@ 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, 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 + + # 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 + + # 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) + + 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 + + # 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 + + # 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), + 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}} @@ -185,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 @@ -241,7 +473,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 +489,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 0000000..614fa57 --- /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 0000000..aa89100 --- /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 0000000..46215fe --- /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 5b25435..7530574 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 0000000..6313ae2 --- /dev/null +++ b/lib/workos/workload_identity.ex @@ -0,0 +1,86 @@ +# @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. + + 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, + 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: + + 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: 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("/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 + + @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 0000000..842f68e --- /dev/null +++ b/lib/workos/workload_identity/credentials.ex @@ -0,0 +1,386 @@ +# @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("/run/workos/identity-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, + token_url: "https://.../oauth2/token", + 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` — 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 + 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` — 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 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, 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 + + * 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 + + # The only environment variable the credentials read. + @client_id_env "WORKOS_CLIENT_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 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. + """ + @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), + {:ok, token_url} <- https_url(token_url), + {:ok, provider} <- provider(opts[:identity_token_provider]) do + {:ok, + %{ + client_id: client_id, + token_url: token_url, + # 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]), + 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 required(opts, key) do + case present(opts[key]) do + nil -> invalid_configuration("#{key} is required") + value -> {:ok, value} + 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) + 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_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 + 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 0000000..b16ff56 --- /dev/null +++ b/lib/workos/workload_identity/exchange.ex @@ -0,0 +1,282 @@ +# @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. + # + # `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]" + + @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_raised(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} + + # 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) + 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([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") + ) + + case Req.request(request) do + {:ok, response} -> + {:ok, response} + + {:error, exception} -> + {:retry, + WorkloadIdentityError.new( + "exchange_failed", + transport_description(exception, config.token_url), + 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, 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)} + + 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 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", + "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 0000000..7eea87a --- /dev/null +++ b/lib/workos/workload_identity_error.ex @@ -0,0 +1,90 @@ +# @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. + 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 + 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. + """ + + 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 was not accepted. Check its issuer, audience and subject claims " <> + "against the trust rule, and that it has not expired. A token that was already " <> + "exchanged is also refused: each exchange needs a new identity token.", + "invalid_target" => + "The resource is not one the token endpoint accepts. Leave the resource unset to use " <> + "the default, https://api.workos.com.", + "invalid_client" => + "The client ID is unknown, or the application has no enabled trust rule. Check that " <> + "the client ID is the M2M application that has the trust rule.", + "unauthorized_client" => + "This application cannot use workload identity federation. Check that the feature is " <> + "enabled for your team and that the application is bound to a non-production " <> + "environment.", + "invalid_scope" => + "The requested scope is not allowed for this application. Fix the scope or leave it unset.", + "invalid_request" => + "The token request was malformed. Check that the token URL points at the " <> + "`/oauth2/token` endpoint.", + "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/mix.lock b/mix.lock index a610dfe..323a627 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/release-please-config.json b/release-please-config.json index 5877d92..34d0075 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,9 +1,39 @@ { + "separate-pull-requests": true, "packages": { ".": { "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", + "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 1850a60..a90f914 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/support/test_server.ex b/test/support/test_server.ex new file mode 100644 index 0000000..1f47454 --- /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 0000000..672f599 --- /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 diff --git a/test/workos/client_secret_test.exs b/test/workos/client_secret_test.exs new file mode 100644 index 0000000..f7c240b --- /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 diff --git a/test/workos/workload_identity_test.exs b/test/workos/workload_identity_test.exs new file mode 100644 index 0000000..7069c57 --- /dev/null +++ b/test/workos/workload_identity_test.exs @@ -0,0 +1,1505 @@ +# @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: "orgs:write") |> client(api()) |> get() + + assert [exchange] = requests(scoped) + assert exchange.form["scope"] == "orgs:write" + refute Map.has_key?(exchange.form, "client_secret") + 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() + + assert [request] = requests(api) + assert request.authorization == "Bearer access-1" + 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 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) + + 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 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: environment_id) + |> client(api) + |> get() + + assert [request] = requests(api) + assert request.authorization == "Bearer access-1" + assert request.environment_id == nil + end + 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 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([{:status, 400, [], body}]) + |> start_credentials(identity_token_provider: fn -> {:ok, secret} end) + |> client(api()) + |> get() + + 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 + # 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() + + 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 + + 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 + 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. + 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" + + # (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 + # 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 == 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) + + 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 + + # -- 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") + 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 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://ignored.example.test/oauth2/token") + System.put_env("WORKOS_WIF_SCOPE", "scope_env") + + provider = fn -> {:ok, "assertion-1"} end + + # (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 == "auth.wif.test" + assert exchange.path == "/oauth2/token" + assert exchange.form["client_id"] == "client_env" + refute Map.has_key?(exchange.form, "scope") + + # (d) The same environment, with an explicit client ID. + token_endpoint = token_endpoint() + api = api() + + assert {:ok, credentials} = + Credentials.start_link( + identity_token_provider: provider, + client_id: "client_explicit", + token_url: @token_url, + 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" + + # (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 ---------------------------------------------------------------------- + + 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 0000000..682fc6c --- /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 0000000..5f62cf7 --- /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 0000000..825c32f --- /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 0000000..9f65770 --- /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 0000000..a470f15 --- /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{}}`. 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/config/config.exs b/workload_identity_aws/config/config.exs new file mode 100644 index 0000000..a9b609d --- /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 0000000..3be7811 --- /dev/null +++ b/workload_identity_aws/lib/workos/workload_identity/aws.ex @@ -0,0 +1,202 @@ +# @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. 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 + + 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) |> __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. + @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 0000000..d59385e --- /dev/null +++ b/workload_identity_aws/lib/workos/workload_identity/aws/http_client.ex @@ -0,0 +1,74 @@ +# @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 + + # 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 + {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] ++ + 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 0000000..7df9c08 --- /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 0000000..dd1ac69 --- /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 0000000..bdd8091 --- /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 0000000..1a71fff --- /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 0000000..3416380 --- /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 0000000..06b3918 --- /dev/null +++ b/workload_identity_aws/test/workos/workload_identity/aws_test.exs @@ -0,0 +1,338 @@ +# @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 -> 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 + 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 "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)) + + 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 0000000..682fc6c --- /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 0000000..5f62cf7 --- /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 0000000..825c32f --- /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 0000000..9f65770 --- /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 0000000..555086d --- /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{}}`. 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 new file mode 100644 index 0000000..d72c764 --- /dev/null +++ b/workload_identity_gcp/lib/workos/workload_identity/gcp.ex @@ -0,0 +1,132 @@ +# @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. + + 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 + @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 + + # 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 """ + 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] + + 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}.") + + {:error, reason} -> + error("The Google Cloud metadata server could not be reached: #{describe(reason)}.") + 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.") + 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(:profile_not_started), do: "the HTTP client did not start" + 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 0000000..62fc2cd --- /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 0000000..b859807 --- /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 0000000..1a71fff --- /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 0000000..3416380 --- /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 0000000..43026a7 --- /dev/null +++ b/workload_identity_gcp/test/workos/workload_identity/gcp_test.exs @@ -0,0 +1,118 @@ +# @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 "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}]) + {: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 + + 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 0000000..682fc6c --- /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 0000000..5f62cf7 --- /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 0000000..825c32f --- /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 0000000..9f65770 --- /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 0000000..95cc10e --- /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 0000000..fe499fe --- /dev/null +++ b/workload_identity_github_actions/lib/workos/workload_identity/github_actions.ex @@ -0,0 +1,239 @@ +# @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." + + @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 """ + 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. 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 + 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) + + 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 + |> 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#{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 + + # 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 + + # 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} -> known_failure(reason) || connection_failed(reason) + _other -> "the connection failed" + end + end + + 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/mix.exs b/workload_identity_github_actions/mix.exs new file mode 100644 index 0000000..150fdbf --- /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 0000000..b859807 --- /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 0000000..1a71fff --- /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 0000000..3416380 --- /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 0000000..a5cc318 --- /dev/null +++ b/workload_identity_github_actions/test/workos/workload_identity/github_actions_test.exs @@ -0,0 +1,484 @@ +# @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 + + # "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) + + 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 == + "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 +end