Skip to content

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

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

gjtorikian wants to merge 25 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=WorkloadIdentityCredentials(...) to WorkOSClient or AsyncWorkOSClient in place of api_key. 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 distributions 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 SDK gains no dependency: the providers are also available as the extras workos[github-actions], workos[gcp] and workos[aws], and boto3 is a dependency of the AWS distribution 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.

A workload can now authenticate with a platform-issued JWT instead of a
stored API key. Pass WorkloadIdentityCredentials as `credentials=` to
WorkOSClient or AsyncWorkOSClient; the SDK exchanges the JWT for a
short-lived access token (jwt-bearer grant), caches it on the credentials
instance and refreshes it once less than min(60s, 20% of its lifetime)
remains.

Every client now authenticates through a credentials contract, resolved
before each HTTP attempt. A static API key is the trivial implementation
and its requests are unchanged. With workload identity the client also
sends x-url-environment-id and, on a 401, discards that token generation,
exchanges again and retries the request once.

The exchange is shared by concurrent callers, bounded by a 30-second
deadline, retried on transport failures, 429 and 5xx with the SDK's
existing backoff, and never follows a redirect. OAuth errors surface as
WorkloadIdentityError with a code, description and hint; neither token
appears in an error. token_file and token_env providers are built in.

Passing both api_key and credentials raises ValueError. Explicit
credentials win over WORKOS_API_KEY, and a failing exchange never falls
back to a key.

No generated file is edited: the `credentials` keyword lives on the
hand-maintained constructors in _base_client.py.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md
…en providers

Three new distributions under packages/, each exporting one factory that
takes an audience and returns an identity token provider for
WorkloadIdentityCredentials:

- workos-workload-identity-github-actions: github_actions(audience)
- workos-workload-identity-gcp: gcp_metadata(audience)
- workos-workload-identity-aws: aws_sts(audience, region=None)

The GitHub Actions and GCP providers make one standard-library GET with
a 10-second timeout and no redirects, and have no dependencies. The AWS
provider calls STS GetWebIdentityToken (RS256) through boto3 on a
regional endpoint. None of them depends on workos, and boto3 never
becomes a dependency of the SDK.

The repo becomes a uv workspace. The SDK gains `github-actions`, `gcp`
and `aws` extras that pull in the matching distribution; installing one
does not select it. The root wheel's contents are unchanged.

CI: the nox `ci` session (and so scripts/ci) and a new `packages` job in
ci.yml lint, type-check and test each distribution in an environment of
its own. Root pytest is limited to tests/ so it does not collect them.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md
Turn the repo into a release-please manifest monorepo. The root entry is
unchanged, so SDK tags stay vX.Y.Z and its release PR title stays
"chore(main): release X.Y.Z". Each provider distribution gets an entry
(release type python, starting at 0.0.0 so the first release is 0.1.0),
its own release PR (separate-pull-requests), a tag of the form
<distribution>-vX.Y.Z, and a publish job gated on its own release.

The release PR enrichment job assumed one release PR. It now runs once
per PR: every release PR gets its uv.lock refreshed, because the one
lockfile records each distribution's version, and changelog fragments
are inlined only into the SDK's PR.

A workspace member builds into the workspace root's dist/ by default, so
the provider jobs build with --out-dir dist before uv publish.

Written but not run: release-please cannot be exercised before merge.
Before the first release, add a PyPI trusted publisher for each of the
three distributions and rehearse the flow on a fork.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md
Add a "Workload Identity" section: how to pass credentials, the settings
and their environment variables, one example per platform provider, the
built-in file and environment providers, a custom callback, and
WorkloadIdentityError.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md
release-please does not treat a manifest version of 0.0.0 as a previous
release, so with no tag yet it would release each provider distribution
as 1.0.0. That is outside the `>=0.1,<1` range of the SDK's extras, and
`pip install "workos[aws]"` could not resolve. Set initial-version so
the first release is 0.1.0.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md
release-please assigns the root package every commit, so a fix that
touched only packages/* also opened an SDK release PR and appeared in
the SDK changelog. Exclude packages/ on the root entry so that a
provider-only commit releases only that provider.

A commit that also changes a root file still reaches the SDK. In
practice that is a provider dependency change, which rewrites the one
uv.lock at the root.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md
release-please gives an empty commit to every package, and for a
package with no release yet it scans the last 500 commits. main has
empty `Release-As:` commits in that range (the newest is 5c1faa3,
`Release-As: 10.6.0`). A Release-As commit wins over initial-version,
so each provider's first release would have been 10.6.0, not 0.1.0.

Set bootstrap-sha to the v10.8.0 release commit so that scan stops
there. release-please reads it only while a package has no release.

Spec: docs/ideation/wif-backend-sdks/spec-phase-4.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-4.md
…hints with the server

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

The server binds a workload identity client to exactly one environment
and takes the environment from that binding, so `x-url-environment-id`
selects nothing. `environment_id` is now optional: the header is sent
only when an environment ID is set, and an empty string counts as not
set. `WORKOS_ENVIRONMENT_ID` still fills the field when it is omitted,
and an explicit value still wins. Setting it is a safety check: a value
that names a different environment gets `403 environment_mismatch`.
The `environment_id` property is now `Optional[str]`.

The hints for `invalid_grant`, `invalid_target`, `invalid_client` and
`unauthorized_client` are reworded to match what the server returns
each code for.

The tests use the real scope name, `orgs:write`. WIF-02 gains part (b):
credentials with no environment ID send no environment header.

The README says that an identity token is good for one exchange, and
what that means for `token_file` and `token_env`.

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

The SDK no longer reads `WORKOS_ENVIRONMENT_ID`. `environment_id` is set
in code or not at all: left out, `None` or an empty string all mean no
`x-url-environment-id` header and no error. The header is an optional
safety check, and a variable left in the environment could turn it into
a `403 environment_mismatch` with no line of code to point at. The
variable did not exist before this work, so removing it breaks no one.
`WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` are
unchanged.

WIF-02 (b) now sets the variable and asserts that no header is sent.
WIF-22 no longer sets it or passes an environment ID.

The README no longer names the variable. Its `token_file` example
describes a file that another process writes, not a Kubernetes token,
which the server refuses. It says "a job shorter than four minutes",
because the SDK exchanges again at four.

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

`token_url` and `scope` are now set in code only. `WORKOS_CLIENT_ID` is
the only environment variable the credentials read.

`token_url` is still required: missing or empty is an error at
construction, with the description `token_url is required`. `scope` is
still optional: not set, `None` or empty means no `scope` field in the
exchange request.

Both variable names came from the CLI spike, where variables are the
only way to configure a command. With no scope a 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. Neither
variable has been released, so removing them breaks no one.

WIF-22 now sets both variables to show that they are ignored, and
gains part (e): with no token URL in code, the credentials cannot be
built.

The README no longer names the two variables, and its example that
relied on them passes the token URL in code. The example token file
path is now `/run/workos/identity-token`, shared by all nine SDKs; the
old path was a Kubernetes one.

Spec: docs/ideation/wif-backend-sdks/shared-design.md (decision 11)
`WorkloadIdentityCredentials` now refuses a `token_url` that is not an
absolute `https` URL. The exchange POST carries the workload's identity
token and the response carries the access token, so neither may travel
over plain HTTP. workos-php already has this rule.

The check runs at construction, after the existing `token_url is
required` check. A URL with another scheme, no scheme or no host raises
`WorkloadIdentityError` with the code `invalid_configuration` and the
description `token_url must be an absolute https URL`. The scheme is
not case-sensitive, so `HTTPS://` is accepted. `http://localhost` and
loopback addresses are refused like any other host. No argument and no
environment variable relaxes the rule.

The URL is parsed with httpx2, the client that sends the exchange, and
not with `urllib.parse`. The two read some input differently: `urlsplit`
drops leading whitespace and does not check the port, so it would pass
URLs that httpx2 cannot send. Such a URL is now refused at construction
too. The error leaves the URL out, because a URL can hold credentials.

One class serves both `WorkOSClient` and `AsyncWorkOSClient`, so one
helper, `_https_url`, covers both.

The existing tests already use `https` token URLs against a mocked
transport, so none needed a change and there is no test-only switch.
The provider packages never build credentials and are unchanged.

The README and the docstrings say that the token URL must be `https`.
…reached

When the GCP provider got no HTTP response from the metadata server, its
error named only the exception class: `GCP metadata identity request
failed: URLError.` That does not say whether the name failed to resolve,
the connection was refused or the request timed out, and it does not say
that the provider works only on Google Cloud.

The description is now this, on one line:

    The GCP metadata server could not be reached: <reason>. This
    provider works only on Google Cloud (Compute Engine, GKE, Cloud
    Run, Cloud Functions).

`<reason>` is the cause in its own words, for example `[Errno -2] Name
or service not known`, `[Errno 111] Connection refused` or `timed out`.
For a `URLError` it is the error's `reason`. A timeout while waiting for
the response arrives unwrapped and is read the same way. A cause with no
text becomes `timed out` for a timeout and `unknown network error`
otherwise, so the reason is never empty and never a class name.

Nothing else changes. The provider still raises
`GcpMetadataProviderError`, which the SDK reports as `provider_failed`
and retries. The request, the 10-second timeout and the rule that the
request never goes through a proxy are the same. The error for a non-200
status, which already names the status, and the error for an empty body
are unchanged.

The tests cover a name that does not resolve, a refused connection and a
timeout, and each one checks the whole description.
When a request got no HTTP response, three errors named only an
exception class:

    The request to the token endpoint failed (TransportConnectError).
    GitHub Actions OIDC token request failed: URLError.
    sts:GetWebIdentityToken failed with EndpointConnectionError.

None of them says whether the name failed to resolve, the connection
was refused, the request timed out or the TLS handshake failed, and
none names the host that was tried. Commit 86910ff fixed the same
thing in the GCP provider. This does it for the token exchange, the
GitHub Actions provider and the AWS provider, the same way.

The three descriptions are now these, each on one line:

    The request to the token endpoint at <host> failed: <reason>.

    The GitHub Actions OIDC token endpoint at <host> could not be
    reached: <reason>. This provider works only in a GitHub Actions
    job, which sets the endpoint in ACTIONS_ID_TOKEN_REQUEST_URL.

    The AWS STS endpoint at <host> could not be reached: <reason>.

`<reason>` is the cause in its own words, for example `[Errno -2] Name
or service not known`, `[Errno 111] Connection refused`, `timed out` or
`[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1085)`. A
cause with no text becomes `timed out` for a timeout and `unknown
network error` otherwise, so the reason is never empty and never a
class name.
`<host>` is the host of the URL, with its port when the URL names one.
No user name, password, path or query of a URL is shown.

Where the reason comes from:

- Token exchange: the text of the httpx2 error. The sentence for
  `exchange_failed` still comes first. The assertion is redacted from
  the text, as it is from what the server sends. One kind of error is
  not quoted: a response that is not valid HTTP. Its text quotes the
  line the parser could not read, and with broken framing that line is
  the body, which holds the access token. That case reads `the server
  did not send a valid HTTP response`.
- GitHub Actions: the `reason` of the `URLError`, or the error itself
  for a timeout while waiting for the response.
- AWS: the error botocore keeps in `error`, followed to the operating
  system's error it was raised from. This covers a failed connection
  and a timeout (botocore's `ConnectionError` family and
  `ReadTimeoutError`). Every other botocore error keeps its message,
  `sts:GetWebIdentityToken failed with <class>.`, because its text can
  quote the request, for example a header value.

The asynchronous client words one case less exactly. For a refused
connection its error says `All connection attempts failed`, where the
synchronous client says `[Errno 111] Connection refused`. The operating
system's error is not in that error's text or in its chain of causes.

Nothing else changes. The codes are the same (`exchange_failed`, and
`provider_failed` for the two providers), every failure is retried as
before, and the exception types are the same. As before, none of these
errors is chained to its cause: the transport error's request holds the
assertion, and a provider's request holds its credentials.

The tests cover a name that does not resolve, a refused connection and
a timeout for each of the three, and check the whole description. For
the exchange they run against both clients, and three of them leave
the HTTP transport in place and open loopback sockets, so the wording
is the real stack's. The AWS tests fake the name lookup or the
connection under a real boto3 client, so nothing leaves the machine.
…errors

The GitHub Actions provider caught only `HTTPError` and `OSError`
around its request. Any other error left the provider as it was, and
the SDK copies the text of a provider's error into its own
`provider_failed` error. With a line break at the end of
`ACTIONS_ID_TOKEN_REQUEST_TOKEN`, the final error read:

    provider_failed: The identity token provider failed, so there was
    no token to exchange. Invalid header value b'Bearer <the request
    token>\n'

A provider must never put a token in an error, and the request token
is a secret too. Other errors got out the same way. `InvalidURL` quotes
the URL, `BadStatusLine` quotes what the server sent, and
`IncompleteRead` holds the part of the body that arrived, which is the
identity token.

Two changes close this.

First, the request token and the URL are checked before a request is
built. A value with a character outside visible ASCII (0x21 to 0x7E)
is refused with a fixed text that names the variable:

    ACTIONS_ID_TOKEN_REQUEST_TOKEN must not contain a space, a line
    break, another control character or a non-ASCII character.

The value is not trimmed or repaired, the error shows no part of it,
and no request is sent.

Second, every error from sending the request or reading the response
now leaves as a `GitHubActionsProviderError` with one of three fixed
texts:

    ACTIONS_ID_TOKEN_REQUEST_URL is not a valid URL.

    GitHub Actions OIDC token response was not valid HTTP.

    GitHub Actions OIDC token request failed with an unexpected
    <class>. Check ACTIONS_ID_TOKEN_REQUEST_URL and
    ACTIONS_ID_TOKEN_REQUEST_TOKEN.

The first is for a URL that cannot be split into its parts, or whose
port is not a number. The second is for any other
`http.client.HTTPException`. The third is for everything else and
names only the class of the error. None of them shows the error's own
text.

The three are raised outside the `except` blocks. `raise ... from
None` inside a handler hides the caught error from a traceback and
still leaves it attached as `__context__`, where its arguments can
hold a token. Raised outside, the new error has nothing attached.

JSON nested too deep to parse raised `RecursionError` out of the
provider. It is now a response with no token value, like any other
body that is not the expected JSON.

Two kinds of value that used to be sent are now refused:

- A request token with a space, a tab, a Latin-1 letter or a control
  character other than a line break. `http.client` sends those.
- A URL with a line break, a tab or a space at the start. `urlsplit`
  drops them, so the request went out without them.

A URL and a bearer token are visible ASCII, so a job on a GitHub
runner should see no difference.

The errors for a status other than 200 and for an endpoint that could
not be reached are unchanged.

The tests cover each case. They check that neither the request token
nor the identity token is in the error's text, repr, arguments or
attributes, or in any error attached to it as cause or context, and
that a refused value sends no request. The responses that are not
valid HTTP come from a loopback server that sends raw bytes, and each
of those tests also shows which error urllib raises for the same
bytes.
Commit f3eca16 made the GitHub Actions provider refuse a request token
or a URL that has a character outside visible ASCII. Its error listed
the characters:

    ACTIONS_ID_TOKEN_REQUEST_TOKEN must not contain a space, a line
    break, another control character or a non-ASCII character.

The Python, Kotlin and Elixir SDKs are to say the same thing for a
refused request token. The text is now this, on one line:

    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.

It also says what to do: the runner sets the variable, so the fix is
to hand it on as it is.

The URL gets the matching text, because a sentence about an HTTP
header does not fit it:

    ACTIONS_ID_TOKEN_REQUEST_URL contains a character that is not
    allowed in a URL, such as a space or a line break. GitHub Actions
    sets this variable; pass it to the program unchanged.

Only the two texts change. Which values are refused is the same as in
f3eca16, the value is still never shown, and no request is sent for a
refused value. The tests compare both texts in full.
Conflict in .release-please-manifest.json: the root package takes main's version (10.9.0), and the three provider entries stay.
…ient secret

Some calls send the API key in the request body, as `client_secret`:
the sign-in methods on `user_management`, `sso.get_profile_and_token`
and `refresh()` on a session. A client built with `credentials` has no
API key. Session refresh on such a client sent `"client_secret": null`
with the workload identity token as the bearer, and turned any error
that followed into a failed refresh.

`_BaseWorkOSClient._client_secret(method)` is now the one place such a
call reads the key:

- A client with an API key gets the key.
- A client with no API key and no credentials gets None, and the
  caller leaves the field out. That is a public client in a PKCE flow,
  which works as before.
- A client built with credentials gets a `ConfigurationError`, before
  any request is sent and before any token exchange:

      <method> needs an API key: this request sends it as the client
      secret. A client that authenticates with workload identity has
      no API key, so use a client built with one for this call.

`Session.refresh` and `AsyncSession.refresh` read the key through it.
They read it first, outside the `try` that turns an error into a
failed refresh, so the error is raised and not returned. For a client
with an API key and for a public client the request is the same as
before.

The generated sign-in and SSO methods still read the key directly.
Generated files are not edited by hand; those methods call the
accessor once the SDK is regenerated. The PKCE helpers
`authenticate_with_code_pkce` and `get_profile_and_token_pkce` are
not changed either.

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

The tests cover the three cases of the accessor on both clients, a
session refresh that is refused with no request and no exchange, the
refresh request of a client with a key and of a public client, and a
public client's PKCE code exchange.
@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 no new actionable issues found.

Summary

Adds workload identity authentication, three platform providers, and separate package releases.

  • WorkOS clients can authenticate with exchanged workload identity tokens.
  • GitHub Actions jobs can provide their identity token to WorkOS.
  • Google Cloud workloads can provide their identity token to WorkOS.
  • AWS workloads can provide their identity token to WorkOS.
  • The SDK and each provider package get their own release and publish path.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[API request] --> B{Fresh cached token?}
  B -->|Yes| E[Send API request]
  B -->|No| C[Start or join shared exchange]
  C --> D[Fetch platform token and exchange it]
  D --> E
  E --> F{First 401?}
  F -->|Yes| G[Discard rejected token and retry once]
  G --> C
  F -->|No| H[Return result]
Loading

Reviews (5) · Last reviewed commit: "test(workload-identity): Keep the test o..." · Reviewed by Greptile

Comment thread src/workos/workload_identity.py Resolved
Comment thread src/workos/workload_identity.py Resolved
… a broken response

The GCP provider caught `HTTPError` and `OSError` around its request.
A response that is not valid HTTP raises `http.client.HTTPException`,
which is neither, so it left the provider as it was. For a response
that is cut short, that is `IncompleteRead`, and its arguments hold
the bytes that arrived, which are part of the identity token:

    IncompleteRead(25 bytes read, 475 more expected)
    args: (b'<the start of the identity token>',)

The SDK keeps a provider's error as the cause of its own
`provider_failed` error, so those bytes travel with it to anything
that records attached errors.

Every error from sending the request or reading the response now
leaves as a `GcpMetadataProviderError`, as in the GitHub Actions
provider. Two fixed texts are new:

    GCP metadata identity response was not valid HTTP.

    GCP metadata identity request failed with an unexpected <class>.

The first is for any `http.client.HTTPException`. The second is for
everything else and names only the class of the error. Neither shows
the error's own text. Both are raised outside the `except` blocks, so
the error that was caught is not attached as context either.

The errors for a status other than 200, for an empty body and for a
server that could not be reached are unchanged.

The tests answer the request with raw bytes from a loopback server:
the token where the status line belongs, a body shorter than its
Content-Length, a body that is not chunked under a chunked header, a
status line that is too long, too many headers and an unknown HTTP
version. They check that the token is not in the error's text, repr,
arguments or attributes, or in any error attached to it, and each one
also shows which error urllib raises for the same bytes.
…ynchronous callers

One `WorkloadIdentityCredentials` can serve a `WorkOSClient` and an
`AsyncWorkOSClient` at once, and coroutines on more than one event
loop. It kept two in-flight exchanges, one for threads and one for
tasks, and a task of another event loop was never joined. So callers
that arrived together could start two exchanges. With `token_file` or
`token_env` both send the same identity token, the server accepts it
once, and one caller fails with `invalid_grant`.

There is now one in-flight exchange per instance, with one shared
result. A thread runs it when a synchronous caller starts it, a task
when an asynchronous caller does, and a caller of either kind waits
for it: a thread blocks on an event, and a coroutine is woken on its
own event loop, so no loop is blocked.

A caller joins an exchange only when it can count on an answer. A
task runs only while its event loop runs, so in two cases a caller
starts an exchange of its own instead of joining:

- A synchronous call made on the thread of the event loop that runs
  the exchange. Blocking that thread would stop the exchange it
  waits for.
- A caller on another thread, when the exchange belongs to an event
  loop that is not running.

Both cases started an exchange of their own before this change too.

A task that is canceled now fails its exchange with `exchange_failed`
and the description "The exchange was canceled before it finished.",
so callers on other threads and loops are not left waiting. A
coroutine that waits for an exchange gives it up one second after the
exchange's deadline, as a thread already did.

A second change is in the same function. An exchange that a waiter
gave up at its deadline could still finish later, and its token then
replaced the one a newer exchange had stored. An exchange that was
given up has failed, so what it returns afterwards is now dropped.

The tests: a coroutine joins an exchange that a thread runs, a thread
joins an exchange that a task runs, and a coroutine on a second event
loop joins it, each with one POST to the token endpoint and one call
of the provider. A blocking call on the loop that runs the exchange
returns instead of waiting for it. A task canceled before its first
step fails its waiter at once. An exchange given up at its deadline
does not publish the token it gets afterwards.
@gjtorikian

Copy link
Copy Markdown
Contributor Author

@greptileai review this draft

Commit 37db2a9 made synchronous and asynchronous callers share one
exchange. An exchange that an asynchronous caller started was still a
task on that caller's event loop, and a task runs only while its loop
runs. One case was left where two exchanges ran: a synchronous client
called from a coroutine blocks the event loop, so it could not wait
for a task of that loop and exchanged for itself. With `token_file`
or `token_env` the second exchange sends the same identity token, and
the server refuses it with `invalid_grant`.

Every exchange now runs on a thread of its own, whichever kind of
client starts it. It depends on no caller's thread and on no event
loop, so any caller can wait for it: a thread blocks on an event, and
a coroutine is woken on its own loop. The blocking call inside a
coroutine joins the exchange that is in flight, and one POST reaches
the token endpoint.

What stays as it was:

- A plain provider may block. It runs on the exchange's thread, never
  on an event loop.
- An `async def` provider is awaited on the event loop of the
  asynchronous caller that started the exchange.
- A synchronous caller with an `async def` provider is refused with
  `provider_failed` and the text "The identity token provider is
  asynchronous. Use it with AsyncWorkOSClient, or pass a synchronous
  provider." It is now refused before it joins or starts an exchange,
  so it cannot block the loop the provider needs.
- A caller that is canceled or times out stops waiting, and the
  exchange goes on for the others.

What changes:

- The exchange is sent with the synchronous HTTP stack for both
  clients. It reads the same settings as the asynchronous stack did:
  each was a client of its own with the library's defaults, so the
  proxy settings and the CA bundle come from the same environment
  variables, and TLS verification is on. An unreachable token
  endpoint is now described the same way for both clients, with the
  operating system's reason, such as "[Errno 111] Connection
  refused". The asynchronous client used to say "All connection
  attempts failed" for a refused connection and "timed out" for a
  timeout.
- An exchange outlives the event loop of the caller that started it.
- A plain callable that returns an awaitable is known to be
  asynchronous only once it is called. If a blocking call holds the
  loop that awaitable needs, the exchange waits for it until its
  deadline and then fails with `provider_failed` for every waiter. No
  second exchange is started.

The thread is a daemon and ends when the exchange does. Nothing is
kept per credentials object between exchanges, and an exchange in
flight does not keep the interpreter alive.

The asynchronous twin of the exchange is removed, and with it the two
cases in which 37db2a9 fell back to a second exchange.

Tests: a blocking call on the event loop joins the exchange that a
coroutine started, with one POST. A blocking call with an `async def`
provider fails at once, and the exchange in flight still succeeds. A
blocking call ends at the deadline when the provider needs the loop
it blocks. An exchange survives the cancellation of the caller that
started it, and the closing of that caller's event loop. The thread
of an exchange is a daemon and ends with the exchange, and a script
that exits with an exchange in flight does exit. Two tests of the
real HTTP stack expected the asynchronous wording for a refused
connection and for a timeout; they now expect the same text for both
clients. The test for a task that is canceled before its first step
is replaced, because there is no task.
… carries

A token endpoint may repeat the assertion it was sent in `error` or
`error_description`. The SDK already replaces it with `[redacted]`
before it keeps either text, and cuts to 500 characters after that,
so the error's code, description, message and repr never showed it.

The error's traceback did. A traceback keeps the frames it passed
through, and the frames of an exchange hold the assertion and the
response in local variables:

    frame _exchange   locals: assertion, response
    frame read        locals: assertion, response, body, detail

A tool that records the local variables of a traceback, such as an
error reporter, would send them along. The exchange now empties the
local variables of every frame in the tracebacks of the error it
hands to its waiters, and of that error's causes. The frames and
their line numbers stay.

WIF-17 gains the two cases in which the token endpoint repeats the
assertion: a 400 with it in `error_description`, and the same body on
a 503 until the retries run out. Both leave the description as
"JWT [redacted] failed validation". The case also checks every local
variable of every frame in each error's tracebacks, as do the two
tests of a repeated assertion. A new test shows that the assertion is
replaced before the description is cut.
… call

The AWS provider built its STS client with the AWS SDK's defaults.
Measured against a local endpoint with boto3 1.44:

- One provider call made 3 STS requests when STS answered with
  `Throttling` or with a 500, because the AWS SDK retries inside the
  client.
- The client waited up to 60 seconds to connect and 60 seconds for
  each read.

A provider does no retries: the WorkOS SDK calls the provider again
as part of the token exchange, which has 30 seconds in all. The
provider's client is now built with one attempt and with 10-second
limits on connecting and on each wait for the response, the same
limit the GitHub Actions and GCP providers use. One provider call is
one STS request.

The settings are on the provider's own client. They win over
`AWS_MAX_ATTEMPTS`, `AWS_RETRY_MODE` and the shared config file, and
change nothing for other AWS clients in the process. The credential
chain, the region rule and the regional endpoint are as before.

Tests: a loopback server stands in for STS, answers with
`Throttling`, a 500 or a 503, and counts one request per provider
call while `AWS_MAX_ATTEMPTS=5` is set. Another test reads the two
limits from the client. The README of the package says that each call
is one request.
@gjtorikian

Copy link
Copy Markdown
Contributor Author

@greptileai review this draft

Comment thread src/workos/workload_identity.py Resolved
… that started it

Commit 8de5545 moved every exchange to a thread of its own. A new
thread starts with an empty context, so a provider that reads a
context variable, such as one a web framework sets per request, found
the variable's default or raised `LookupError`, and the exchange
failed with `provider_failed`.

For an asynchronous caller that was a step back: the task that ran
the exchange copied the caller's context, and `asyncio.to_thread`
passed it on to a blocking provider. A synchronous caller never had
it.

The thread now runs in a copy of the context of the caller that
starts the exchange, for both kinds of client. An `async def`
provider is scheduled from that thread, so the coroutine inherits the
same copy on the caller's event loop. Callers that join an exchange
do not change the context it runs in, as before.

Tests: a provider that returns the value of a context variable, with
both clients, and an `async def` provider that does the same after
yielding to the event loop. Each makes one exchange with the value
the caller set.
@gjtorikian

Copy link
Copy Markdown
Contributor Author

@greptileai review this draft

…er it starts an exchange

Commit 8de5545 replaced
`test_async_exchange_canceled_before_it_ran_does_not_block_the_next`.
The test was written for a task that is canceled before its first
step, and there is no such task now. What it protected is a promise
to the caller, and that still holds: a caller that is canceled right
after it starts an exchange must not block the next caller or make it
fail.

The test is back under its name, written for the thread. A coroutine
starts an exchange and is canceled while the exchange still waits for
its provider, before any request to the token endpoint. The next
caller then gets a token within its time limit, and the token
endpoint has received one POST: the exchange went on without the
caller that started it.

`test_an_exchange_outlives_the_caller_that_started_it`, which cancels
the caller while the request is in flight, stays.
@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