Skip to content

Authenticate with workload identity federation - #330

Open
rgarcia wants to merge 3 commits into
mainfrom
hypeship/cli-workload-identity-auth
Open

rgarcia wants to merge 3 commits into
mainfrom
hypeship/cli-workload-identity-auth

Conversation

@rgarcia

@rgarcia rgarcia commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

What changes for a CLI user

The CLI can now authenticate with workload identity federation, so a CI job can run kernel commands with no stored KERNEL_API_KEY:

permissions:
  id-token: write
steps:
  - run: kernel browsers list
    env:
      KERNEL_FEDERATION_RULE_ID: wifr_...

Until now GetAuthenticatedClient tried KERNEL_API_KEY, then the saved login, then failed, so the federation support already in the Go SDK was never reached. No SDK bump was needed (kernel-go-sdk v0.154.0 is already pinned).

  • The identity token sources are the SDK's: github_actions, gcp_metadata, aws_sts, file, env, selected by the same environment variables. The AWS source is now linked into the binary.
  • kernel auth reports the credential commands actually use: API key, workload identity (rule ID and whether a cached token is in use), or saved login. It used to report a saved login even when KERNEL_API_KEY was set and in use.
  • The README's Authentication section documents all of this.

Precedence

  1. KERNEL_API_KEY (unchanged)
  2. KERNEL_FEDERATION_RULE_ID
  3. The login saved by kernel login
  4. The existing "no authentication available" error

When the rule ID is set and no key is, a saved login is ignored. If federation fails (no identity token source, exchange refused, authorization server unreachable), the command fails with that error. It never falls back to the saved login, and never changes or deletes it.

Token cache

Every command is a new process, and a token from a GitHub-federated rule lasts about five minutes, so the access token is kept on disk between commands.

Lifetime. The expiry is the one the exchange returns. A cached token is reused only while it has more than 60 seconds left, both when it is loaded and when it is sent later in a long command.

Rejection. If the API answers 401, the CLI drops the token from memory and disk, exchanges once more and sends the request once more. That second attempt is final: the SDK's own retries do not send it a third time, and a second 401 drops the replacement too. A request is only sent again if net/http itself would replay it. Vault writes opt out of that on purpose, so they are sent once: the token is dropped, the 401 is returned, and the next command exchanges a new one.

Entry name. A digest of the federation rule ID, the authorization server URL, the API origin, KERNEL_IDENTITY_TOKEN_AUDIENCE, the source, the identity token file path, and GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT and GITHUB_JOB. Two rules or two environments on one machine never share an entry.

Binding. Each entry also stores a digest of what the workload obtains its identity token with, and is used only by a process that computes the same digest. This is what keeps a token from a workload with a different identity, including two matrix legs that share repository, run, attempt and job name but run in different environments.

Identity token source Cached Where Reused only by
github_actions Yes, when GITHUB_ACTIONS=true and RUNNER_TEMP is set A 0600 file in $RUNNER_TEMP/kernel-cli (directory 0700), which the runner empties for every job. The keyring is not used. The same job: same repository, run, attempt and job name, and the same ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN
file Yes Like the saved login, as a separate entry: OS keyring first, then a 0600 file in ~/.config/kernel. Under RUNNER_TEMP in a GitHub Actions job. A process whose token file has the same path and holds the same identity token. The binding is taken from the token that was actually exchanged.
env Yes As for file A process with the same KERNEL_IDENTITY_TOKEN
aws_sts, gcp_metadata No

Decision outside a recognized ephemeral job. Where there is no per-run scope, a token is cached only if it can be bound to the identity token itself (file, env). That is at least as narrow as a run: only a process holding the very token that was exchanged can reuse the result. For aws_sts and gcp_metadata the identity is ambient (an IAM role, a service account) and this process cannot tell it apart from another workload's without asking the provider, so those tokens are not cached on disk and every command exchanges. The same applies to github_actions without RUNNER_TEMP. Binding those to the STS caller identity or the metadata server's service account would make caching possible there; this PR does not do that.

Concurrency. Files are written to a temporary file and renamed, so a reader sees the old entry or the new one, never part of either. Two processes that find no usable token both exchange. Dropping a rejected token is a check followed by a delete, so it can remove a token another process stored in between; that costs one more exchange.

Off switch. KERNEL_FEDERATION_TOKEN_CACHE=off (also false, 0, no) stops reading and writing the cache.

Secrets. No access token, identity token or Authorization header is printed, including in debug output and error text. The header the client starts every request with is a non-secret placeholder, which makes the SDK's own cacheless federation support stand down; the access token is put on requests to the API origin only and the placeholder is removed from any other.

Binary size

Stripped linux/amd64 build (CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" ./cmd/kernel, go1.27.4):

Bytes MB
Before (main) 24,543,392 24.5
After 27,197,600 27.2

That is +2,654,208 bytes (+10.8%), from linking the AWS SDK packages the aws_sts source needs. No other dependency was added.

What was run

  • make build
  • make test (go vet ./... and go test ./...): pass
  • go test -race -count=3 ./pkg/auth/ and go test -race ./cmd -run 'Federation|TestAuthReports': pass
  • GOOS=windows and GOOS=darwin (arm64): go build ./... and go vet ./pkg/auth ./cmd
  • make lint, and golangci-lint run --max-issues-per-linter 0 --max-same-issues 0 ./... (v2.15.0): 243 issues on main and 243 with this change, none in the files added or changed here
  • gofmt -l cmd pkg: only pkg/util/fileops.go, which this PR does not touch
  • The built binary as separate processes against local stand-in servers for the GitHub OIDC endpoint, the token endpoint and the API: three commands made one exchange; a revoked token was dropped, re-exchanged and the request retried; cache off; a refused exchange and a missing identity source exit 1 with the federation error; KERNEL_API_KEY wins

The new tests use httptest stand-ins for the GitHub OIDC endpoint, the token endpoint and the API. They cover the precedence table, no fallback, cache hit across processes, the 60-second margin at load and at send, separation by rule, authorization server, API origin, audience, repository, run, attempt, job, job instance, token file path and token content, the sources that are not cached, the 401 drop-and-retry and its limits, parallel writers and readers, cache off, kernel auth output, and that nothing secret is printed. Each behavior was also checked by removing the line that implements it and confirming a test fails.

The change was reviewed before opening by a separate automated reviewer over three rounds. Seven findings: five fixed, one settled by keeping the vault no-replay rule above, one closed with a comment. It approved the final diff.

Not verified

  • A real exchange. No request was made to a real authorization server or API, and nothing was created or changed in any Kernel organization. A real exchange cannot be run from the machine this was built on.
  • A real GitHub Actions runner. The job scope assumes ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN stay the same across the steps of one job. If they differ between steps, the cache misses between steps (it never shares). It also relies on the runner emptying RUNNER_TEMP per job, as GitHub documents.
  • AWS and Google Cloud sources. aws_sts is linked in and registered but was not exercised against AWS; gcp_metadata was not exercised either. Tests only check that neither is cached.
  • Windows and macOS. Cross-compiled and vetted only; the tests ran on Linux. Replacing the cache file by rename while another process has it open can fail on Windows, in which case the token is not cached for that command.
  • A real OS keyring. Tests use the mock keyring.

Commands now authenticate with KERNEL_API_KEY, then with the federation
rule in KERNEL_FEDERATION_RULE_ID, then with the saved login. A failed
federation exchange fails the command instead of falling back to the
saved login.

The access token is cached between CLI processes where it can be tied to
the workload that obtained it, and the AWS identity token source is
linked in.
Bind a token from a file source to the identity token that was exchanged
for it, hold a cached token to the 60 second margin when it is sent, make
the retry after a 401 final, and keep the token off requests to other
hosts.
After a 401, send a request again only when net/http itself would
replay it, so a vault write without a body is sent once as well.
@rgarcia
rgarcia requested a review from masnwilliams November 25, 2026 03:46
@rgarcia

rgarcia commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Picked masnwilliams to review: touched the changed code in auth; 10 pending

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 61d3a4d. Configure here.

Comment thread pkg/auth/federation.go
Body: http.NoBody,
Request: req,
}, err
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Federation errors still trigger SDK retries

Medium Severity

unauthenticated returns a non-nil error together with X-Should-Retry: false. Stainless consults that header only after a successful HTTP response, and retries on any middleware error. After a 401, a failed re-exchange is therefore retried up to MaxRetries more times, repeating identity-token fetches and token-endpoint calls. GitHub OIDC is rate-limited, so those extra attempts can fail a job that would have recovered from a single refused exchange.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 61d3a4d. Configure here.

Comment thread pkg/auth/client.go
}
if _, err := federation.tokens.Token(context.Background()); err != nil {
return nil, err
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Federation exchange can hang indefinitely

Medium Severity

Client setup calls tokens.Token with context.Background() and no deadline. OAuth refresh is bounded by tokenExchangeTimeout (30s); federation is not. A stalled GitHub OIDC endpoint, metadata server, or authorization server can hang every authenticated command until the process is killed, and Ctrl+C will not cancel the exchange.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 61d3a4d. Configure here.

@masnwilliams masnwilliams left a comment

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.

Approving. The precedence, the no-fallback rule, and the decision not to cache aws_sts / gcp_metadata tokens all look right, and kernel auth now reports the credential commands actually use.

Non-blocking suggestions:

  1. Move the cross-process cache into the SDK (follow-up). federation.middleware, unauthenticated and sameOrigin mostly repeat what credentials.EnvClientOption() already does inside kernel.NewClient, and the Bearer workload-identity placeholder exists only to make that option stand down. The only thing the CLI adds is keeping the token between processes. A store hook in the SDK (Load / Save / Forget(accessToken)) would let the CLI supply just the store and delete the middleware. It would also bring back two things the SDK path has: retrying transient identity-token failures (failRequest), and exchanging through the request's HTTP client.
  2. Make vault "send once" explicit. replayable(req) works because the vault middleware changes the same *http.Request in place and runs inside this one. A context marker set by vaultWriteRequestOptions() and read here would state the policy directly instead of relying on that.
  3. Build the cache settings once. federationCacheFromEnv runs on every token() and reject(), rereading the env and the token file. If it's built in newFederation, and the source wrapper records the exchanged identity token on the struct (TokenCache never calls the provider concurrently), then exchangedAssertionKey, fromFile and the binding reassignment after the exchange can go.
  4. Share storage with storage.go. copies / save / forget are a second keyring-plus-file store with slightly different rules (ExpiresAt instead of SavedAt, rename-based writes). One small store type could serve both.
  5. Nit: runAuth repeats the credential order from GetAuthenticatedClient. A shared ActiveCredential() would keep the two from drifting.

On the two Bugbot threads, I believe both are false positives:

  • Retries on federation errors: unauthenticated returns a response with X-Should-Retry: false, and shouldRetry reads that header whenever there is a response, even if an error came back with it. So no retry happens.
  • Exchange can hang: the SDK already sets time limits: 30s on identity-token sources, 30s on the exchange, and 60s per TokenCache refresh regardless of the caller's context. Passing the command context instead of context.Background() would only let cancellation take effect sooner.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants