Skip to content

feat(workload-identity): Add workload identity federation - #584

Draft
gjtorikian wants to merge 21 commits into
mainfrom
feat/workload-identity
Draft

gjtorikian wants to merge 21 commits into
mainfrom
feat/workload-identity

Conversation

@gjtorikian

Copy link
Copy Markdown
Contributor

Summary

  • Adds workload identity federation as a second way to authenticate, next to an API key. Pass credentials: WorkOS::WorkloadIdentity::Credentials.new(...) to WorkOS::Client.new, or set config.credentials. The SDK exchanges the identity token that the workload's platform issues for a short-lived WorkOS access token, keeps it in memory and renews it before it expires. A CI job or a cloud workload then needs no stored API key.
  • Adds three provider gems that fetch the identity token on their platform: workos-workload-identity-github-actions, workos-workload-identity-gcp and workos-workload-identity-aws. A callback, a token file or an environment variable covers any other platform. The workos gem gains no dependency: aws-sdk-sts is a dependency of the AWS gem only.
  • The exchange follows one design shared by all nine backend SDKs: the token URL must be https, a failed exchange is retried like an API request, a 401 on an exchanged token is recovered once per request, and no token appears in an error or a log.
  • Releases: the repository becomes a release-please manifest with one entry per package, so the SDK and each provider get their own release pull request and publish job.
  • Tested with the 31 conformance cases that all nine SDKs share, and end to end with real identity tokens from GitHub Actions, Google Cloud and AWS.

Let the SDK authenticate with a short-lived token from the platform it
runs on, in place of a stored API key.

- WorkOS::Client.new(credentials:) and WorkOS.configure accept a
  credentials object. WorkOS::WorkloadIdentity::Credentials exchanges an
  identity token (jwt-bearer) for an access token, caches it on the
  instance, refreshes it once less than min(60s, 20% of its lifetime)
  remains, shares one in-flight exchange between concurrent callers, and
  retries the exchange on transport failures, 429 and 5xx with the SDK's
  existing backoff.
- The HTTP runtime resolves credentials before every attempt. On a 401
  it invalidates the token generation that was sent and resends once per
  request, with the same body and Idempotency-Key. API-key clients
  behave as before.
- Three provider gems live under gems/, each released on its own and
  none depending on this gem: workos-workload-identity-github-actions,
  workos-workload-identity-gcp and workos-workload-identity-aws.
  token_file, token_env and any callable cover other platforms.
- release-please becomes a four-package manifest with separate release
  PRs. release.yml publishes each gem from its own tag: vX.Y.Z for the
  SDK, <gem name>/vX.Y.Z for a provider.

No generated file is changed. Nothing here is released until the server
side launches; the branch is pushed without a pull request.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed on cycle 2 of 3.
A package listed at 0.0.0 in the release-please manifest is treated as
never released, and its first release is `initial-version`, which
defaults to 1.0.0. Set it to 0.1.0 on the three provider gems so their
first release is 0.1.0, as intended.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed on cycle 3 of 3.
release-please gives the root package every commit, whatever paths it
touches, so a fix to a provider gem would have reached the SDK changelog
and bumped the workos gem. Exclude gems/ from the root package: a commit
whose files are all under gems/ now counts only for that provider. A
commit that touches both still counts for both.

Do not force an SDK version with an empty Release-As commit from now on:
an empty commit is dropped from the root and applied to every provider.
Use "release-as" on the package's entry in release-please-config.json.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed, follow-up cycle 1.
…credentials

Passing both api_key and credentials to the client is a mistake in the
call, not a failed exchange, so it raises ArgumentError like the other
argument check in the constructor. WorkloadIdentityError with code
invalid_configuration remains for the credentials' own missing settings.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed, follow-up cycle 1.
Sorbet signatures for the workload identity classes in the SDK
(CredentialSnapshot, StaticKeyCredentials, WorkloadIdentity,
WorkloadIdentity::Credentials, WorkloadIdentityError) and for each
provider gem, which now packages its own rbi/ directory.

These files are hand-maintained and marked @oagen-ignore-file. oagen
writes the rest of rbi/ from the OpenAPI spec and cannot derive
signatures for hand-maintained Ruby; they sit outside
.oagen-manifest.json, like session_manager.rbi. No generated file is
changed. BaseClient and Configuration have no RBI, so their new
credentials option has no signature.

Sorbet is not a dependency of this repo, so CI does not type-check
them. They were checked with sorbet-static 0.6.13672 and compared with
the loaded code in both directions.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed, follow-up cycle 1.
BaseClient had no signatures, so WorkOS::Client.new, which inherits its
constructor, was untyped, including the new credentials option. This
adds them for the whole public class: the constants, the readers, the
constructor, the request builders, request, execute_request and
shutdown.

The file is hand-maintained and marked @oagen-ignore-file, like the
other workload identity signatures. oagen only generates RBI for the
files it controls.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed, follow-up cycle 2.
script/ci and the Lint workflow now run `srb tc`. Until now nothing
checked the signatures under rbi/: the repo had no Sorbet dependency.

Sorbet reads lib/ and rbi/ of the SDK and of each provider gem. It
fails when a constant does not resolve or when a signature's parameters
or superclass differ from the code it describes. sorbet/usage/ holds a
strictly typed caller of the hand-maintained signatures, so their types
are checked as well; it is never run. sorbet/rbi/ declares the few
constants of other gems that the code names. sorbet/ is left out of the
packaged gem.

The check found 111 errors in generated files, which cannot be fixed
here. sorbet/config leaves them out, each with its reason: 106 alias
models that are a constant assignment in lib/ and a class in rbi/, two
Authorization signatures that lack the body_slug keyword, and three
classes in session_manager.rbi declared as T::Struct. From now on a
regeneration whose signatures disagree with its Ruby fails Lint.

It also found one mistake in the new snapshot signatures: a Data class
takes its members by position or keyword, so the keyword-only
initialize is removed and to_s is declared as the alias it is.

sorbet-static has no generic build, so Bundler replaced the `ruby`
platform in Gemfile.lock with x86_64-linux and aarch64-linux.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
Review: passed, follow-up cycle 2.
rbi/workos/session_manager.rbi declared AuthError, RefreshSuccess and
RefreshError as T::Struct. In lib/ they are Struct.new(...,
keyword_init: true), so Sorbet rejected the file, and RefreshError had
no sealed_session member although the code sets one when a refresh
fails after the token was rotated. The three classes are now declared
as lib/ defines them: a reader and a writer per member, and every member
an optional keyword of new.

The file carried the oagen header, but nothing generates it: it is not
in .oagen-manifest.json and the Ruby emitter does not write it. It
describes a hand-maintained class, so it is now marked
@oagen-ignore-file like the other hand-maintained signatures.

sorbet/usage/session_manager.rb is a strictly typed caller of these
signatures, so the type check covers their types as well.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
sorbet/config left out three groups of known errors. The one in
session_manager.rbi is fixed in this repo. The other two are in
generated files and are fixed in the generator
(workos/oagen-emitters#309), so their exclusions go too.

Until the SDK is regenerated with that fix, `srb tc` reports 108 errors,
all in generated files: 106 alias models declared as a class in rbi/ and
as a constant assignment in lib/, and two Authorization signatures that
lack the body_slug keyword. script/ci stops at that step, and the Lint
workflow fails on it. The tests are unaffected.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
The rule that the GCP metadata request never goes through a proxy is now
conformance case WIF-GCP-03. The conformance check reads case IDs from
test names, so the existing test for the rule now carries the ID. No
behavior changes.

Spec: docs/ideation/wif-backend-sdks/spec-phase-5.md
…hints with the server

A reading of the server code on 2026-11-13 showed three things the SDK
had slightly wrong.

The environment ID is optional. The server binds a workload identity
client to exactly one environment and takes the environment from that
binding, so the x-url-environment-id header selects nothing. Credentials
no longer fail without an environment ID, and the header is sent only
when one is set (passed explicitly, or from WORKOS_ENVIRONMENT_ID; an
empty string counts as not set). Setting it is a safety check: a value
that names a different environment gets 403 environment_mismatch. The
environment_id reader, and its RBI signature, can now return nil.

Four hints are reworded to say what the server returns each code for:
invalid_grant (also a token that was already exchanged), invalid_target
(only about the resource), invalid_client (also an application with no
enabled trust rule) and unauthorized_client (the feature is off for the
team, or the application is not bound to a non-production environment).

The README says that the server accepts an identity token for one
exchange, and what that means for token_file and token_env.

Tests: WIF-02 gains part (b), a request with no environment ID carries
the access token and no environment header. The scope in WIF-01 is
orgs:write, the real scope name.

Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 6, 7 and 8)
…t the README examples

The environment ID now comes only from the caller's code. The SDK no
longer reads WORKOS_ENVIRONMENT_ID: the header it filled is an optional
safety check, and a variable left in the environment could turn that
check into a 403 environment_mismatch with no line of code to point at.
Left out, nil or an empty string all mean not set: no
x-url-environment-id header and no error. WORKOS_CLIENT_ID,
WORKOS_WIF_TOKEN_URL and WORKOS_WIF_SCOPE are read as before.

The README no longer names the variable. Its token_file example is a
file that another process writes, such as a sidecar or an earlier CI
step, and not a Kubernetes service account token. It says a job shorter
than four minutes, not five: the SDK exchanges again at four minutes,
when a 300-second token reaches its 60-second refresh threshold.

Tests: WIF-02 (b) sets the variable and asserts that no environment
header is sent. WIF-22 (c) and (d) no longer cover the environment ID.

Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 9 and 10)
…WIF_SCOPE

WORKOS_CLIENT_ID is now the only environment variable the workload
identity credentials read. The token URL and the scope are set in code.

token_url is required and comes only from the caller. Missing, nil or
empty is a configuration error at construction, with the description
"token_url is required". scope is optional: not set, nil or empty means
the exchange carries no scope field. With no scope the token carries
every scope the application holds, so a variable left in the environment
would change permissions with no line of code to point at. client_id
still defaults from WORKOS_CLIENT_ID, and its error still names that
variable.

The README and the doc comments say so, every example passes the token
URL in code, and the example token file path is /run/workos/identity-token
in place of a Kubernetes secrets path.

Tests: WIF-22 (c) sets both variables and asserts that neither is read,
(d) covers an explicit client ID, and (e) asserts that a missing token
URL is an error even with the variable set.

Spec: docs/ideation/wif-backend-sdks/shared-design.md (decision 11)
On main the Ruby SDK reads nothing from the environment: the caller
reads its own variables and passes the values in. The workload identity
credentials added the SDK's first environment read, a WORKOS_CLIENT_ID
default for client_id. Workload identity now follows the rest of the
SDK, and the client ID is passed in code only.

client_id is required. Missing, nil or empty is a configuration error at
construction, with the description "client_id is required". The
credentials read no environment variable for their configuration.
token_env still reads the variable the caller names, and the platform
providers still read their platform's own variables.

The README and the doc comments say so, and every workload identity
example passes the client ID in code.

Tests: WIF-22 (c) sets WORKOS_CLIENT_ID and asserts that an explicit
client ID is sent, (d) asserts that a missing client ID is an error even
with the variable set, and (e) is unchanged.

Spec: docs/ideation/wif-backend-sdks/shared-design.md, decision 12
The POST to the token URL carries the workload's identity token and the
response carries the access token. The credentials accepted an http
token URL as well as an https one. They now accept https only, as
workos-php already does.

token_url must be an absolute URL whose scheme is https (in any case)
and that has a host. Anything else is a configuration error at
construction: an http URL, a URL with no scheme or no host, or another
scheme. The code is invalid_configuration and the description is
"token_url must be an absolute https URL". localhost and loopback
addresses get no exception, and no option or environment variable
relaxes the rule. The exchange now always turns TLS on, instead of
deriving that from the scheme.

The README and the doc comments say so.

Tests: an http URL for example.com, for localhost and for 127.0.0.1 and
[::1] is refused, as is a URL with no host, with no scheme or with
another scheme. HTTPS:// in upper case is accepted and the exchange
goes out over https. The existing tests stub the token endpoint with
WebMock at an https URL and open no socket, so they needed no test-only
switch.
Conflicts: .release-please-manifest.json (the root package takes main's version, 10.7.0, and the three provider entries stay), Gemfile.lock (the Sorbet entries stay, with main's newer standard), and rbi/workos/session_manager.rbi (main's version, which is the corrected one from #582). A comment in sorbet/usage/session_manager.rb is corrected to match it: only authenticated is required.
…the lint

The provider gem jobs install each gem's bundle into the gem's own
directory (gems/<gem>/vendor/bundle), then run standardrb there. Standard
resolves its default `vendor/**/*` ignore against the directory that
holds .standard.yml, which is the repository root, so the installed
bundle was not ignored. On Ruby 3.4, the one version that runs the lint
step, standardrb linted about 2,000 files of third-party gems, ran for
several minutes and failed on their offenses. The test and build steps
were then skipped.

The root .standard.yml now ignores gems/*/vendor/**/*. That covers a run
from a gem's directory and a run from the root. The files that are
linted in the repository itself are unchanged.
The sign-in methods on user_management and sso.get_profile_and_token
send the API key in the request body as client_secret. A client built
with credentials has no API key. Today those methods leave the field
out for such a client, exchange a token and send the request without a
client secret.

BaseClient#client_secret(method_name) is now the one place that answers
what the client secret for a call is:

- a client with an API key gets the key;
- a client with no key and no credentials (a public client running a
  PKCE flow) gets nil, which leaves the field out, as before;
- a client with credentials is refused with an ArgumentError that names
  the method, before any request is built and before the credentials
  are resolved, so no token exchange happens.

The method is marked @api private and has a signature in the
hand-maintained RBI. Nothing calls it yet: the methods that send the key
are generated, and they call it once they are regenerated. Until then
they behave as before. No hand-written code sends the key as
client_secret: the PKCE helpers send no secret, and Session#refresh
authenticates with the Authorization header.

The README names the calls that need a client built with an API key.

Tests: the accessor returns the key for a key client, nil for a public
client and the exact error for a workload identity client, with no
exchange and no request. Any other credentials object is refused
without being resolved. A public client's PKCE flow sends no
client_secret and no Authorization header, through the PKCE helpers and
through the generated methods.
@gjtorikian

Copy link
Copy Markdown
Contributor Author

@greptileai review this draft

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge, with the earlier non-blocking sign-in error issue still outstanding.

Findings

  1. P2 Sign-in skips the helpful error ▶
Fix with agent prompt
### Issue 1
lib/workos/base_client.rb:175-180
The sign-in methods never call `client_secret`. `authenticate_with_password` and `get_profile_and_token` still read `@client.api_key` directly. With workload credentials, they drop the nil `client_secret`, exchange a workload token, and send an unsupported request instead of raising the helpful local error.

Wire this helper into those callers, preserving per-request overrides. Test a real sign-in call rather than calling the helper directly.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds workload identity federation alongside API-key authentication.

  • Ruby clients can authenticate API requests with workload identity credentials.
  • GitHub Actions workloads can provide identity tokens to the Ruby SDK.
  • Google Cloud workloads can provide identity tokens to the Ruby SDK.
  • AWS workloads can provide identity tokens to the Ruby SDK.
  • The SDK and three provider gems get separate release and check paths.

Diagram

sequenceDiagram
  participant App
  participant Client
  participant Credentials
  participant Provider
  participant TokenEndpoint
  participant WorkOSAPI
  App->>Client: API call
  Client->>Credentials: Resolve credentials
  opt Cached token needs refresh
    Credentials->>Provider: Request identity token
    Provider-->>Credentials: Identity token
    Credentials->>TokenEndpoint: Exchange identity token
    TokenEndpoint-->>Credentials: Access token
  end
  Credentials-->>Client: Request headers and generation
  Client->>WorkOSAPI: Send request
  opt First recoverable 401
    Client->>Credentials: Invalidate sent generation and resolve again
    Credentials-->>Client: Fresh request headers
    Client->>WorkOSAPI: Resend request once
  end
Loading

Reviews (2) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread lib/workos/base_client.rb
Comment on lines +122 to +127
def client_secret(method_name)
return @api_key if @api_key && !@api_key.empty?
return @api_key if @credentials.is_a?(StaticKeyCredentials)

raise ArgumentError, "#{method_name} 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."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Sign-in skips the helpful error

The sign-in methods never call client_secret. authenticate_with_password and get_profile_and_token still read @client.api_key directly. With workload credentials, they drop the nil client_secret, exchange a workload token, and send an unsupported request instead of raising the helpful local error.

Wire this helper into those callers, preserving per-request overrides. Test a real sign-in call rather than calling the helper directly.

Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/workos/base_client.rb
Line: 122-127

Comment:
**Sign-in skips the helpful error**

The sign-in methods never call `client_secret`. `authenticate_with_password` and `get_profile_and_token` still read `@client.api_key` directly. With workload credentials, they drop the nil `client_secret`, exchange a workload token, and send an unsupported request instead of raising the helpful local error.

Wire this helper into those callers, preserving per-request overrides. Test a real sign-in call rather than calling the helper directly.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

A token endpoint may repeat the assertion it was sent in its error or
error_description. The credentials already took every occurrence out of
both strings before keeping them, for a final error and for the last
failure when retries run out, and before the description is cut to 500
characters. The marker they put in its place was "[REDACTED]". The
design all the SDKs share fixes the marker as "[redacted]", so the same
server answer reads the same in every SDK. Only the marker changes.

Tests: WIF-17 gains the two cases where the server repeats the
assertion, a 400 and a 503 until retries run out, and checks that the
description is exactly "JWT [redacted] failed validation" and that the
assertion is in no message, inspect output, full message or cause. A new
test covers what those two cannot: the assertion differs per attempt and
the one sent in that attempt is the one taken out, every occurrence
goes, the error code is cleaned too, and the replacement happens before
the cut, so a cut cannot leave the start of a token behind.
…conds

The provider built its STS client with the AWS SDK's default timeouts:
15 seconds to connect and 60 seconds to read. Against an STS endpoint
that accepted the connection and never answered, one provider call took
60 seconds to fail, which is longer than the 30 seconds the SDK allows
for a whole token exchange. The GitHub Actions and GCP providers allow
their one request 10 seconds.

The STS client now gets the same limit for connecting and for reading,
from a constant, HTTP_TIMEOUT. The same stalled endpoint now fails the
call after 10 seconds. Only the provider's own client is configured;
process-wide AWS settings, the credential chain and the endpoint and
region rules are untouched.

The AWS SDK's retries were already off. A new test shows it on the
wire: a local stand-in for STS answers with a throttling error, a 500
and a 503, and each provider call makes exactly one request. With the
AWS SDK's defaults the same stand-in receives three.
main gained an opt-in proxy option for the client and support for a
Retry-After header given as an HTTP-date. Both touch the client runtime
that this branch changes, and two files conflicted.

lib/workos/configuration.rb: the configuration keeps `credentials` and
gains the `proxy` reader. The global client is built with both.

lib/workos/base_client.rb:
- The constructor takes `credentials` and `proxy`, checks the
  credentials first and then parses the proxy, as each side did.
- Retry delay. This branch had moved the delay into a class method,
  BaseClient.retry_delay, so that the workload identity token exchange
  waits the way an API request does. main rewrote the instance method
  to read an HTTP-date. The class method now holds main's logic and the
  instance method still delegates to it, so there is one implementation
  and the exchange honors an HTTP-date too.

Not a textual conflict, but needed for the merged tree: the
hand-maintained signatures for BaseClient gain the `proxy` parameter,
the `proxy` reader and `parse_proxy`, and the type-checked caller file
uses them. Without that the type check fails on the constructor.

Test: the exchange honors a Retry-After given as an HTTP-date.
@gjtorikian

Copy link
Copy Markdown
Contributor Author

@greptileai review this draft

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant