Repository navigation
Conversation
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.
|
Picked masnwilliams to review: touched the changed code in |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ 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.
| Body: http.NoBody, | ||
| Request: req, | ||
| }, err | ||
| } |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 61d3a4d. Configure here.
| } | ||
| if _, err := federation.tokens.Token(context.Background()); err != nil { | ||
| return nil, err | ||
| } |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 61d3a4d. Configure here.
masnwilliams
left a comment
There was a problem hiding this comment.
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:
- Move the cross-process cache into the SDK (follow-up).
federation.middleware,unauthenticatedandsameOriginmostly repeat whatcredentials.EnvClientOption()already does insidekernel.NewClient, and theBearer workload-identityplaceholder 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. - Make vault "send once" explicit.
replayable(req)works because the vault middleware changes the same*http.Requestin place and runs inside this one. A context marker set byvaultWriteRequestOptions()and read here would state the policy directly instead of relying on that. - Build the cache settings once.
federationCacheFromEnvruns on everytoken()andreject(), rereading the env and the token file. If it's built innewFederation, and the source wrapper records the exchanged identity token on the struct (TokenCachenever calls the provider concurrently), thenexchangedAssertionKey,fromFileand the binding reassignment after the exchange can go. - Share storage with
storage.go.copies/save/forgetare a second keyring-plus-file store with slightly different rules (ExpiresAtinstead ofSavedAt, rename-based writes). One small store type could serve both. - Nit:
runAuthrepeats the credential order fromGetAuthenticatedClient. A sharedActiveCredential()would keep the two from drifting.
On the two Bugbot threads, I believe both are false positives:
- Retries on federation errors:
unauthenticatedreturns a response withX-Should-Retry: false, andshouldRetryreads 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
TokenCacherefresh regardless of the caller's context. Passing the command context instead ofcontext.Background()would only let cancellation take effect sooner.


What changes for a CLI user
The CLI can now authenticate with workload identity federation, so a CI job can run
kernelcommands with no storedKERNEL_API_KEY:Until now
GetAuthenticatedClienttriedKERNEL_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-sdkv0.154.0 is already pinned).github_actions,gcp_metadata,aws_sts,file,env, selected by the same environment variables. The AWS source is now linked into the binary.kernel authreports 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 whenKERNEL_API_KEYwas set and in use.Precedence
KERNEL_API_KEY(unchanged)KERNEL_FEDERATION_RULE_IDkernel loginWhen 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/httpitself 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, andGITHUB_REPOSITORY,GITHUB_RUN_ID,GITHUB_RUN_ATTEMPTandGITHUB_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.
github_actionsGITHUB_ACTIONS=trueandRUNNER_TEMPis set0600file in$RUNNER_TEMP/kernel-cli(directory0700), which the runner empties for every job. The keyring is not used.ACTIONS_ID_TOKEN_REQUEST_URLandACTIONS_ID_TOKEN_REQUEST_TOKENfile0600file in~/.config/kernel. UnderRUNNER_TEMPin a GitHub Actions job.envfileKERNEL_IDENTITY_TOKENaws_sts,gcp_metadataDecision 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. Foraws_stsandgcp_metadatathe 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 togithub_actionswithoutRUNNER_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(alsofalse,0,no) stops reading and writing the cache.Secrets. No access token, identity token or
Authorizationheader 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):main)That is +2,654,208 bytes (+10.8%), from linking the AWS SDK packages the
aws_stssource needs. No other dependency was added.What was run
make buildmake test(go vet ./...andgo test ./...): passgo test -race -count=3 ./pkg/auth/andgo test -race ./cmd -run 'Federation|TestAuthReports': passGOOS=windowsandGOOS=darwin(arm64):go build ./...andgo vet ./pkg/auth ./cmdmake lint, andgolangci-lint run --max-issues-per-linter 0 --max-same-issues 0 ./...(v2.15.0): 243 issues onmainand 243 with this change, none in the files added or changed heregofmt -l cmd pkg: onlypkg/util/fileops.go, which this PR does not touchKERNEL_API_KEYwinsThe new tests use
httpteststand-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 authoutput, 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
ACTIONS_ID_TOKEN_REQUEST_URLandACTIONS_ID_TOKEN_REQUEST_TOKENstay 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 emptyingRUNNER_TEMPper job, as GitHub documents.aws_stsis linked in and registered but was not exercised against AWS;gcp_metadatawas not exercised either. Tests only check that neither is cached.