From 4b215247ab74b1d8f4f5192c98ce4d658e2cf047 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:29:15 +0000 Subject: [PATCH 1/5] Authenticate with workload identity federation 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. --- README.md | 38 +- cmd/auth.go | 49 +- cmd/auth_status_test.go | 98 ++++ go.mod | 13 + go.sum | 26 ++ pkg/auth/client.go | 26 +- pkg/auth/federation.go | 186 ++++++++ pkg/auth/federation_cache.go | 250 ++++++++++ pkg/auth/federation_test.go | 856 +++++++++++++++++++++++++++++++++++ 9 files changed, 1526 insertions(+), 16 deletions(-) create mode 100644 cmd/auth_status_test.go create mode 100644 pkg/auth/federation.go create mode 100644 pkg/auth/federation_cache.go create mode 100644 pkg/auth/federation_test.go diff --git a/README.md b/README.md index 96bfd12c..20dbfe0e 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,42 @@ export KERNEL_API_KEY= Create an API key from the [Kernel dashboard](https://dashboard.onkernel.com). +### Workload identity federation + +A CI job or other workload can authenticate without a stored API key. Set `KERNEL_FEDERATION_RULE_ID` to a federation rule (see `kernel workload-identity federation-rules`), and the CLI exchanges the workload's own identity token for a short-lived Kernel access token: + +```yaml +# GitHub Actions +permissions: + id-token: write +steps: + - run: kernel browsers list + env: + KERNEL_FEDERATION_RULE_ID: wifr_... +``` + +| Variable | Purpose | +| --- | --- | +| `KERNEL_FEDERATION_RULE_ID` | The federation rule to authenticate with. Turns federation on. | +| `KERNEL_IDENTITY_TOKEN_SOURCE` | Where the identity token comes from: `github_actions`, `gcp_metadata`, `aws_sts`, `file` or `env`. When unset: `KERNEL_IDENTITY_TOKEN_FILE` if set, then `KERNEL_IDENTITY_TOKEN`, then GitHub Actions when the job exposes an OIDC token. | +| `KERNEL_IDENTITY_TOKEN_FILE` | Path of a file holding the identity token, read again for every exchange. | +| `KERNEL_IDENTITY_TOKEN` | A literal identity token. | +| `KERNEL_IDENTITY_TOKEN_AUDIENCE` | Audience the built-in sources request. Defaults to the authorization server URL. | +| `KERNEL_FEDERATION_TOKEN_CACHE` | Set to `off` (or `false`, `0`, `no`) to exchange a new access token in every command instead of caching it. | + +The CLI authenticates with the first of these that is configured: `KERNEL_API_KEY`, then `KERNEL_FEDERATION_RULE_ID`, then the login saved by `kernel login`. When `KERNEL_FEDERATION_RULE_ID` is set and the exchange fails, the command fails. It does not fall back to a saved login. `kernel auth` shows which one is in use. + +Each command is a new process, so the access token is cached between commands until 60 seconds before it expires. If the API rejects a cached token, the CLI drops it, exchanges a new one and retries the request once. A token is cached only where it can be tied to the workload that obtained it: + +| Identity token source | Cached | Where | Reused only by | +| --- | --- | --- | --- | +| `github_actions` | Yes, when `RUNNER_TEMP` is set | A file under `RUNNER_TEMP`, which the runner empties for every job | The same job: same repository, run, attempt, job name and OIDC request credentials | +| `file` | Yes | Next to the saved login: the OS keychain, or a file in `~/.config/kernel` that only you can read. Under `RUNNER_TEMP` in a GitHub Actions job. | A process whose token file has the same path and holds the same identity token | +| `env` | Yes | As for `file` | A process with the same `KERNEL_IDENTITY_TOKEN` | +| `aws_sts`, `gcp_metadata` | No | | | + +The cache entry is also specific to the federation rule, the authorization server, the API URL and `KERNEL_IDENTITY_TOKEN_AUDIENCE`. It never replaces the saved login. + ## Commands Reference ### Global Flags @@ -190,7 +226,7 @@ kernel search contents srch_01jsearchresult --limit 3 --content-source browser - `kernel login [--force]` - Login via OAuth 2.0 - `kernel logout` - Clear stored credentials -- `kernel auth` - Check authentication status +- `kernel auth` - Check authentication status and which credential is in use (API key, workload identity or saved login) ### App Creation diff --git a/cmd/auth.go b/cmd/auth.go index 9a1f338c..e7dc16ca 100644 --- a/cmd/auth.go +++ b/cmd/auth.go @@ -24,7 +24,7 @@ type JWTClaims struct { var authCmd = &cobra.Command{ Use: "auth", Short: "Show authentication status and manage auth connections", - Long: `Display information about the current authentication state, including logged-in user details and token expiry. + Long: `Display the credential commands authenticate with (API key, workload identity federation, or saved login) and its state, including logged-in user details and token expiry. Use --log-level debug to show additional details like user ID and storage method. Use "kernel auth connections" to manage managed auth connections for automated login flows.`, @@ -74,21 +74,25 @@ func parseJWT(tokenString string) (*JWTClaims, error) { } func runAuth(cmd *cobra.Command, args []string) error { - // Check for stored OAuth tokens - tokens, err := auth.LoadTokens() - if err != nil { - // Check if API key is being used as fallback - if apiKey := os.Getenv("KERNEL_API_KEY"); apiKey != "" { - pterm.Info.Println("Authentication method: API Key") - pterm.Info.Printf("API URL: %s\n", util.GetBaseURL()) - if len(apiKey) >= 12 { - pterm.Info.Printf("API Key: %s...%s\n", apiKey[:8], apiKey[len(apiKey)-4:]) - } else { - pterm.Info.Printf("API Key: %s\n", strings.Repeat("*", len(apiKey))) - } - return nil + // The sources are reported in the order commands try them. + if apiKey := os.Getenv("KERNEL_API_KEY"); apiKey != "" { + pterm.Info.Println("Authentication method: API Key") + pterm.Info.Printf("API URL: %s\n", util.GetBaseURL()) + if len(apiKey) >= 12 { + pterm.Info.Printf("API Key: %s...%s\n", apiKey[:8], apiKey[len(apiKey)-4:]) + } else { + pterm.Info.Printf("API Key: %s\n", strings.Repeat("*", len(apiKey))) } + return nil + } + + if federation := auth.DescribeFederation(); federation != nil { + printFederationStatus(federation) + return nil + } + tokens, err := auth.LoadTokens() + if err != nil { pterm.Info.Println("No active session found - not authenticated") pterm.Info.Printf("API URL: %s\n", util.GetBaseURL()) pterm.Info.Printf("Auth URL: %s\n", auth.CurrentAuthBaseURL()) @@ -135,6 +139,23 @@ func runAuth(cmd *cobra.Command, args []string) error { return nil } +func printFederationStatus(federation *auth.FederationStatus) { + pterm.Info.Println("Authentication method: Workload identity federation") + pterm.Info.Printf("API URL: %s\n", util.GetBaseURL()) + pterm.Info.Printf("Auth URL: %s\n", auth.CurrentAuthBaseURL()) + pterm.Info.Printf("Federation rule: %s\n", federation.RuleID) + switch { + case federation.Err != nil: + pterm.Error.Printf("%v\n", federation.Err) + case federation.NotCached != "": + pterm.Info.Printf("Cached token: not in use (%s); every command exchanges a new one\n", federation.NotCached) + case federation.CachedTokenExpiresAt.IsZero(): + pterm.Info.Println("Cached token: not in use; the next command exchanges a new one") + default: + pterm.Info.Printf("Cached token: in use, expires in %s\n", time.Until(federation.CachedTokenExpiresAt).Round(time.Second)) + } +} + func tokenAuthBaseURLForDisplay(tokens *auth.TokenStorage) string { if tokens.AuthBaseURL != "" { return tokens.AuthBaseURL diff --git a/cmd/auth_status_test.go b/cmd/auth_status_test.go new file mode 100644 index 00000000..427423de --- /dev/null +++ b/cmd/auth_status_test.go @@ -0,0 +1,98 @@ +package cmd + +import ( + "strings" + "testing" + "time" + + "github.com/kernel/cli/pkg/auth" + "github.com/pterm/pterm" + "github.com/zalando/go-keyring" +) + +func TestAuthReportsTheSourceCommandsUse(t *testing.T) { + for _, tc := range []struct { + name string + apiKey, rule, login bool + env map[string]string + want []string + notWant string + }{ + {name: "API key first", apiKey: true, rule: true, login: true, + want: []string{"Authentication method: API Key"}, notWant: "Workload identity"}, + {name: "workload identity before a saved login", rule: true, login: true, + want: []string{ + "Authentication method: Workload identity federation", + "Federation rule: wifr_status", + "Cached token: not in use; the next command exchanges a new one", + }, notWant: "OAuth"}, + {name: "workload identity with the cache off", rule: true, + env: map[string]string{auth.EnvFederationTokenCache: "off"}, + want: []string{"Cached token: not in use (turned off by KERNEL_FEDERATION_TOKEN_CACHE); every command exchanges a new one"}}, + {name: "workload identity without an identity token source", rule: true, login: true, + env: map[string]string{"ACTIONS_ID_TOKEN_REQUEST_URL": ""}, + want: []string{"Federation rule: wifr_status", "no identity token source could be configured"}, notWant: "OAuth"}, + {name: "saved login", login: true, + want: []string{"Authenticated with OAuth"}, notWant: "Workload identity"}, + {name: "nothing", want: []string{"not authenticated"}}, + } { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + keyring.MockInit() + env := map[string]string{ + "HOME": home, "USERPROFILE": home, + "KERNEL_API_KEY": "", "KERNEL_FEDERATION_RULE_ID": "", + "KERNEL_IDENTITY_TOKEN_SOURCE": "", "KERNEL_IDENTITY_TOKEN_FILE": "", "KERNEL_IDENTITY_TOKEN": "", + auth.EnvFederationTokenCache: "", + "GITHUB_ACTIONS": "true", "RUNNER_TEMP": t.TempDir(), + "ACTIONS_ID_TOKEN_REQUEST_URL": "http://127.0.0.1:1/idtoken", "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-credential", + } + if tc.apiKey { + env["KERNEL_API_KEY"] = "sk_test_0123456789" + } + if tc.rule { + env["KERNEL_FEDERATION_RULE_ID"] = "wifr_status" + } + for name, value := range tc.env { + env[name] = value + } + for name, value := range env { + t.Setenv(name, value) + } + if tc.login { + if err := auth.SaveTokens(&auth.TokenStorage{AccessToken: "login-token", ExpiresAt: time.Now().Add(48 * time.Hour)}); err != nil { + t.Fatal(err) + } + } + previous := logger + logger = pterm.DefaultLogger.WithLevel(pterm.LogLevelWarn) + t.Cleanup(func() { logger = previous }) + output := capturePtermOutput(t) + + if err := runAuth(authCmd, nil); err != nil { + t.Fatal(err) + } + for _, want := range tc.want { + if !strings.Contains(output.String(), want) { + t.Errorf("output does not contain %q:\n%s", want, output.String()) + } + } + if tc.notWant != "" && strings.Contains(output.String(), tc.notWant) { + t.Errorf("output contains %q:\n%s", tc.notWant, output.String()) + } + for _, secret := range []string{"login-token", "request-credential", "sk_test_0123456789"} { + if strings.Contains(output.String(), secret) { + t.Errorf("output contains the secret %q:\n%s", secret, output.String()) + } + } + }) + } +} + +func TestAuthReportsACachedWorkloadIdentityToken(t *testing.T) { + output := capturePtermOutput(t) + printFederationStatus(&auth.FederationStatus{RuleID: "wifr_status", CachedTokenExpiresAt: time.Now().Add(3 * time.Minute)}) + if !strings.Contains(output.String(), "Cached token: in use, expires in 3m0s") { + t.Fatalf("output = %s, want the cached token reported in use", output.String()) + } +} diff --git a/go.mod b/go.mod index 2e556e72..93a351b5 100644 --- a/go.mod +++ b/go.mod @@ -32,6 +32,19 @@ require ( atomicgo.dev/cursor v0.2.0 // indirect atomicgo.dev/keyboard v0.2.9 // indirect atomicgo.dev/schedule v0.1.0 // indirect + github.com/aws/aws-sdk-go-v2 v1.39.6 // indirect + github.com/aws/aws-sdk-go-v2/config v1.31.21 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.18.25 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.13 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.13 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.41.0 // indirect + github.com/aws/smithy-go v1.23.2 // indirect github.com/charmbracelet/colorprofile v0.3.0 // indirect github.com/charmbracelet/x/ansi v0.8.0 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect diff --git a/go.sum b/go.sum index 01207a70..2093845f 100644 --- a/go.sum +++ b/go.sum @@ -20,6 +20,32 @@ github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk= +github.com/aws/aws-sdk-go-v2 v1.39.6 h1:2JrPCVgWJm7bm83BDwY5z8ietmeJUbh3O2ACnn+Xsqk= +github.com/aws/aws-sdk-go-v2 v1.39.6/go.mod h1:c9pm7VwuW0UPxAEYGyTmyurVcNrbF6Rt/wixFqDhcjE= +github.com/aws/aws-sdk-go-v2/config v1.31.21 h1:gH/y+NphLGIVuNHXNkTQir3PmL44Efe8OpPAsbDms0o= +github.com/aws/aws-sdk-go-v2/config v1.31.21/go.mod h1:P6I8guuLej6F2++fKUlo9OIhI59LuEsyEZZMMmgqh/4= +github.com/aws/aws-sdk-go-v2/credentials v1.18.25 h1:MvtSN3ECsQbgEHcux1pZQhuMjZnShlsqcS0Pqlan4Vw= +github.com/aws/aws-sdk-go-v2/credentials v1.18.25/go.mod h1:YATyDPzlHucr1cxEE9rsZl7ZG3gQsxpjD6o5of/8qXE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13 h1:T1brd5dR3/fzNFAQch/iBKeX07/ffu/cLu+q+RuzEWk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.13/go.mod h1:Peg/GBAQ6JDt+RoBf4meB1wylmAipb7Kg2ZFakZTlwk= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.13 h1:a+8/MLcWlIxo1lF9xaGt3J/u3yOZx+CdSveSNwjhD40= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.13/go.mod h1:oGnKwIYZ4XttyU2JWxFrwvhF6YKiK/9/wmE3v3Iu9K8= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.13 h1:HBSI2kDkMdWz4ZM7FjwE7e/pWDEZ+nR95x8Ztet1ooY= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.13/go.mod h1:YE94ZoDArI7awZqJzBAZ3PDD2zSfuP7w6P2knOzIn8M= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3 h1:x2Ibm/Af8Fi+BH+Hsn9TXGdT+hKbDd5XOTZxTMxDk7o= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.3/go.mod h1:IW1jwyrQgMdhisceG8fQLmQIydcT/jWY21rFhzgaKwo= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13 h1:kDqdFvMY4AtKoACfzIGD8A0+hbT41KTKF//gq7jITfM= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.13/go.mod h1:lmKuogqSU3HzQCwZ9ZtcqOc5XGMqtDK7OIc2+DxiUEg= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.3 h1:NjShtS1t8r5LUfFVtFeI8xLAHQNTa7UI0VawXlrBMFQ= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.3/go.mod h1:fKvyjJcz63iL/ftA6RaM8sRCtN4r4zl4tjL3qw5ec7k= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7 h1:gTsnx0xXNQ6SBbymoDvcoRHL+q4l/dAFsQuKfDWSaGc= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.7/go.mod h1:klO+ejMvYsB4QATfEOIXk8WAEwN4N0aBfJpvC+5SZBo= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.0 h1:JoO/STlEltv5nSbzbg709MLNW0/BWgyK2t/R9OWcCyQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.0/go.mod h1:E19xDjpzPZC7LS2knI9E6BaRFDK43Eul7vd6rSq2HWk= +github.com/aws/smithy-go v1.23.2 h1:Crv0eatJUQhaManss33hS5r40CG3ZFH+21XSkqMrIUM= +github.com/aws/smithy-go v1.23.2/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= github.com/boyter/gocodewalker v1.4.0 h1:fVmFeQxKpj5tlpjPcyTtJ96btgaHYd9yn6m+T/66et4= diff --git a/pkg/auth/client.go b/pkg/auth/client.go index 38f63b9f..f3851da3 100644 --- a/pkg/auth/client.go +++ b/pkg/auth/client.go @@ -7,6 +7,7 @@ import ( "os" kernel "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/lib/credentials" "github.com/kernel/kernel-go-sdk/option" "github.com/pterm/pterm" ) @@ -23,7 +24,30 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error return &client, nil } - // Fallback to OAuth tokens if no API key is available + // Workload identity federation comes next. Once it is configured, a + // failure to authenticate with it is final: the saved login is not tried. + if os.Getenv(credentials.EnvFederationRuleID) != "" { + pterm.Debug.Println("Using workload identity federation") + federation, err := newFederation() + if err != nil { + return nil, err + } + token, err := federation.tokens.Token(context.Background()) + if err != nil { + return nil, err + } + // The header makes the SDK's own federation support, which reads the + // same environment variables and has no cache, leave requests alone. + // The middleware replaces it with the current token on each request. + authOpts := append(opts, + option.WithHeader("Authorization", "Bearer "+token.AccessToken), + option.WithMiddleware(federation.middleware), + ) + client := kernel.NewClient(authOpts...) + return &client, nil + } + + // Fallback to OAuth tokens if neither is available tokens, err := LoadTokens() if err == nil { // Check if access token is expired and refresh if needed diff --git a/pkg/auth/federation.go b/pkg/auth/federation.go new file mode 100644 index 00000000..3cc1fa6d --- /dev/null +++ b/pkg/auth/federation.go @@ -0,0 +1,186 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "net/url" + "os" + "strings" + "sync" + "time" + + "github.com/kernel/cli/pkg/util" + "github.com/kernel/kernel-go-sdk/lib/credentials" + // Registers the aws_sts identity token source. + _ "github.com/kernel/kernel-go-sdk/lib/credentials/awssts" + "github.com/kernel/kernel-go-sdk/option" + "github.com/pterm/pterm" +) + +// federation authenticates requests with workload identity federation: the +// workload's identity token is exchanged for a short-lived Kernel access +// token, which is kept on disk between CLI processes (see federationCache). +type federation struct { + ruleID string + apiURL *url.URL + exchange credentials.AccessTokenProvider + // tokens holds the token for the life of this process and renews it + // before it expires. + tokens *credentials.TokenCache + + mu sync.Mutex + rejected string +} + +func newFederation() (*federation, error) { + source, opts, err := credentials.FederationFromEnv() + if err != nil { + return nil, err + } + apiBaseURL := util.GetBaseURL() + apiURL, err := url.Parse(apiBaseURL) + if err != nil { + return nil, errors.New("KERNEL_BASE_URL is not a valid URL") + } + f := &federation{ + ruleID: opts.FederationRuleID, + apiURL: apiURL, + exchange: credentials.NewFederationProvider(credentials.FederationConfig{ + IdentityTokenProvider: source, + FederationRuleID: opts.FederationRuleID, + APIBaseURL: apiBaseURL, + }), + } + f.tokens = credentials.NewTokenCache(f.token) + return f, nil +} + +// token returns the workload's cached access token, or exchanges an identity +// token for a new one and caches it. force is set after the API rejected the +// previous token, whose cache entry has been removed by then. +func (f *federation) token(ctx context.Context, force bool) (*credentials.Token, error) { + cache, reason := federationCacheFromEnv(f.ruleID) + if cache == nil { + pterm.Debug.Printfln("Workload identity token is not cached: %s", reason) + } else if !force { + if entry := cache.load(); entry != nil { + pterm.Debug.Printfln("Using the cached workload identity token (valid for %s)", time.Until(entry.ExpiresAt).Round(time.Second)) + return &credentials.Token{AccessToken: entry.AccessToken, ExpiresAt: entry.ExpiresAt}, nil + } + } + token, err := f.exchange(ctx, force) + if err != nil { + return nil, err + } + pterm.Debug.Printfln("Exchanged an identity token for a Kernel access token (valid for %s)", time.Until(token.ExpiresAt).Round(time.Second)) + if cache != nil { + if err := cache.save(token); err != nil { + pterm.Debug.Printfln("Could not cache the workload identity token: %v", err) + } + } + return token, nil +} + +// reject drops an access token the API refused, so the next one comes from a +// new exchange. Requests refused with the same token drop it once. +func (f *federation) reject(accessToken string) { + f.mu.Lock() + defer f.mu.Unlock() + if f.rejected == accessToken { + return + } + f.rejected = accessToken + f.tokens.Invalidate() + if cache, _ := federationCacheFromEnv(f.ruleID); cache != nil { + cache.forget(accessToken) + } +} + +// middleware authenticates each API request with the current access token. +// When the API answers 401 it drops that token, exchanges a new one and sends +// the request once more. +func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { + // The token is for the API only. + if !sameOrigin(req.URL, f.apiURL) { + return next(req) + } + token, err := f.tokens.Token(req.Context()) + if err != nil { + return unauthenticated(req, err) + } + req.Header.Set("Authorization", "Bearer "+token.AccessToken) + resp, err := next(req) + // A later middleware can send the request to a browser VM instead. A 401 + // from there says nothing about this token. + if err != nil || resp.StatusCode != http.StatusUnauthorized || !sameOrigin(req.URL, f.apiURL) { + return resp, err + } + + f.reject(token.AccessToken) + if req.Body != nil && req.GetBody == nil { + return resp, nil + } + if req.GetBody != nil { + body, err := req.GetBody() + if err != nil { + return resp, nil + } + req.Body = body + } + _ = resp.Body.Close() + token, err = f.tokens.Token(req.Context()) + if err != nil { + return unauthenticated(req, err) + } + req.Header.Set("Authorization", "Bearer "+token.AccessToken) + return next(req) +} + +// unauthenticated fails a request that has no access token. The response +// tells the client not to send the request again. +func unauthenticated(req *http.Request, err error) (*http.Response, error) { + return &http.Response{ + Status: "credentials unavailable", + Header: http.Header{"X-Should-Retry": {"false"}}, + Body: http.NoBody, + Request: req, + }, err +} + +func sameOrigin(a, b *url.URL) bool { + return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host) +} + +// FederationStatus describes workload identity federation as configured in +// the environment. +type FederationStatus struct { + RuleID string + // Err is why no identity token source could be set up. + Err error + // CachedTokenExpiresAt is when the cached access token expires. It is + // zero when the next command exchanges a new one. + CachedTokenExpiresAt time.Time + // NotCached is why this workload's tokens are not cached, if they are not. + NotCached string +} + +// DescribeFederation reports how workload identity federation is set up, or +// nil when KERNEL_FEDERATION_RULE_ID is not set. It makes no network request. +func DescribeFederation() *FederationStatus { + ruleID := os.Getenv(credentials.EnvFederationRuleID) + if ruleID == "" { + return nil + } + status := &FederationStatus{RuleID: ruleID} + if _, _, status.Err = credentials.FederationFromEnv(); status.Err != nil { + return status + } + cache, reason := federationCacheFromEnv(ruleID) + if cache == nil { + status.NotCached = reason + } else if entry := cache.load(); entry != nil { + status.CachedTokenExpiresAt = entry.ExpiresAt + } + return status +} diff --git a/pkg/auth/federation_cache.go b/pkg/auth/federation_cache.go new file mode 100644 index 00000000..4d58b896 --- /dev/null +++ b/pkg/auth/federation_cache.go @@ -0,0 +1,250 @@ +package auth + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/kernel/cli/pkg/util" + "github.com/kernel/kernel-go-sdk/lib/credentials" + "github.com/zalando/go-keyring" +) + +// EnvFederationTokenCache turns the on-disk cache of workload identity access +// tokens off when set to "off", "false", "0" or "no". +const EnvFederationTokenCache = "KERNEL_FEDERATION_TOKEN_CACHE" + +// federationCacheMargin is how much lifetime a cached token needs to be +// reused. With less left, a new one is exchanged. +const federationCacheMargin = 60 * time.Second + +// federationCacheEntry is a cached workload identity access token. +type federationCacheEntry struct { + AccessToken string `json:"access_token"` + ExpiresAt time.Time `json:"expires_at"` + // Binding ties the token to the workload that obtained it; see + // federationCache. + Binding string `json:"binding"` +} + +// federationCache is where the current workload keeps its access token +// between CLI processes. +// +// The entry name is a digest of the federation rule ID, the authorization +// server, the API origin, the identity token audience and source, the identity +// token file path, and the GitHub Actions repository, run, attempt and job. +// The entry also records a binding, a digest of what the workload gets its +// identity token with: the GitHub Actions token request URL and credential, +// which differ for every job, or the identity token itself for a token from a +// file or the environment. An entry is used only by a process that computes +// the same binding, so a token never reaches a workload that could not have +// obtained it. +type federationCache struct { + name string + binding string + // dir holds the entry as a file when set, and the keychain is not used. + // It is the per-job temporary directory of a GitHub Actions runner. + dir string +} + +// federationCacheFromEnv returns the token cache of the current workload, or +// nil and the reason when its tokens are not cached. +func federationCacheFromEnv(ruleID string) (*federationCache, string) { + switch strings.ToLower(strings.TrimSpace(os.Getenv(EnvFederationTokenCache))) { + case "off", "false", "0", "no": + return nil, "turned off by " + EnvFederationTokenCache + } + apiURL, err := url.Parse(util.GetBaseURL()) + if err != nil || apiURL.Host == "" { + return nil, "the API URL is not valid" + } + + // The source is chosen the way credentials.FederationFromEnv chooses it. + source := os.Getenv(credentials.EnvIdentityTokenSource) + tokenFile := os.Getenv(credentials.EnvIdentityTokenFile) + if source == "" { + switch { + case tokenFile != "": + source = credentials.SourceFile + case os.Getenv(credentials.EnvIdentityToken) != "": + source = credentials.SourceEnv + case os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL") != "": + source = credentials.SourceGitHubActions + } + } + + cache := &federationCache{} + if os.Getenv("GITHUB_ACTIONS") == "true" && os.Getenv("RUNNER_TEMP") != "" { + cache.dir = filepath.Join(os.Getenv("RUNNER_TEMP"), "kernel-cli") + } + var fileToken string + switch source { + case credentials.SourceGitHubActions: + if cache.dir == "" { + return nil, "there is no GitHub Actions job directory (RUNNER_TEMP) to keep it in" + } + case credentials.SourceFile: + data, err := os.ReadFile(tokenFile) + if fileToken = strings.TrimSpace(string(data)); err != nil || fileToken == "" { + return nil, "the identity token file could not be read" + } + if abs, err := filepath.Abs(tokenFile); err == nil { + tokenFile = abs + } + case credentials.SourceEnv: + default: + // The identity comes from the machine's surroundings (an AWS role, a + // Google Cloud service account), which this process cannot tell apart + // from another workload's without asking the provider. + return nil, fmt.Sprintf("the %s identity token source has nothing to tie a cached token to this workload", source) + } + + cache.name = "federation-token-" + digest( + ruleID, authBaseURLFromEnv(), strings.ToLower(apiURL.Scheme+"://"+apiURL.Host), + os.Getenv(credentials.EnvIdentityTokenAudience), source, tokenFile, + os.Getenv("GITHUB_REPOSITORY"), os.Getenv("GITHUB_RUN_ID"), os.Getenv("GITHUB_RUN_ATTEMPT"), os.Getenv("GITHUB_JOB"), + ) + cache.binding = digest( + os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL"), os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN"), + fileToken, strings.TrimSpace(os.Getenv(credentials.EnvIdentityToken)), + ) + return cache, "" +} + +// digest hashes parts so that no two lists of parts collide. +func digest(parts ...string) string { + var b strings.Builder + for _, part := range parts { + b.WriteString(strconv.Itoa(len(part)) + ":" + part) + } + sum := sha256.Sum256([]byte(b.String())) + return hex.EncodeToString(sum[:]) +} + +func (c *federationCache) filePath() (string, error) { + dir := c.dir + if dir == "" { + var err error + if dir, err = getConfigDir(); err != nil { + return "", err + } + } + return filepath.Join(dir, c.name+".json"), nil +} + +// copies returns the entry from each store that holds one. +func (c *federationCache) copies() (fromKeyring, fromFile *federationCacheEntry) { + parse := func(data []byte) *federationCacheEntry { + var entry federationCacheEntry + if json.Unmarshal(data, &entry) != nil { + return nil + } + return &entry + } + if c.dir == "" { + if data, err := keyring.Get(KeyringService, c.name); err == nil { + fromKeyring = parse([]byte(data)) + } + } + if path, err := c.filePath(); err == nil { + if data, err := os.ReadFile(path); err == nil { + fromFile = parse(data) + } + } + return fromKeyring, fromFile +} + +// load returns the cached token when this workload may still use it. +func (c *federationCache) load() *federationCacheEntry { + var usable *federationCacheEntry + fromKeyring, fromFile := c.copies() + for _, entry := range []*federationCacheEntry{fromKeyring, fromFile} { + if entry == nil || entry.AccessToken == "" || entry.Binding != c.binding || + time.Until(entry.ExpiresAt) <= federationCacheMargin { + continue + } + if usable == nil || entry.ExpiresAt.After(usable.ExpiresAt) { + usable = entry + } + } + return usable +} + +// save stores the token where saveTokens stores a login: in the keychain, or +// in a file when the keychain refuses it. Under a GitHub Actions runner it is +// always a file in the job's temporary directory. +func (c *federationCache) save(token *credentials.Token) error { + data, err := json.Marshal(federationCacheEntry{ + AccessToken: token.AccessToken, + ExpiresAt: token.ExpiresAt, + Binding: c.binding, + }) + if err != nil { + return err + } + path, pathErr := c.filePath() + if c.dir == "" { + if err := setKeyring(KeyringService, c.name, string(data)); err == nil { + if pathErr == nil { + _ = os.Remove(path) + } + return nil + } + } + if pathErr != nil { + return pathErr + } + if err := writeFileAtomically(path, data); err != nil { + return err + } + if c.dir == "" { + _ = keyring.Delete(KeyringService, c.name) + } + return nil +} + +// writeFileAtomically replaces path with data, readable by the owner only. A +// process reading path sees the old content or the new, never part of either. +func writeFileAtomically(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + // CreateTemp creates the file with mode 0600. + tmp, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + _, err = tmp.Write(data) + if closeErr := tmp.Close(); err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(tmp.Name(), path) + } + if err != nil { + _ = os.Remove(tmp.Name()) + } + return err +} + +// forget removes the cached token if it is still accessToken, which the API +// rejected. A token another process has stored since then is kept. +func (c *federationCache) forget(accessToken string) { + fromKeyring, fromFile := c.copies() + if fromKeyring != nil && fromKeyring.AccessToken == accessToken { + _ = keyring.Delete(KeyringService, c.name) + } + if fromFile != nil && fromFile.AccessToken == accessToken { + if path, err := c.filePath(); err == nil { + _ = os.Remove(path) + } + } +} diff --git a/pkg/auth/federation_test.go b/pkg/auth/federation_test.go new file mode 100644 index 00000000..9b562433 --- /dev/null +++ b/pkg/auth/federation_test.go @@ -0,0 +1,856 @@ +package auth + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + kernel "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/lib/credentials" + "github.com/kernel/kernel-go-sdk/option" + "github.com/pterm/pterm" + "github.com/zalando/go-keyring" +) + +// federationStandIns are local servers standing in for the GitHub Actions +// OIDC endpoint, the Kernel token endpoint and the Kernel API. +type federationStandIns struct { + api, auth, github *httptest.Server + + mu sync.Mutex + // exchanges is the federation rule ID of every token request. + exchanges []string + // expiresIn is the lifetime the token endpoint reports, in seconds. + expiresIn int + // refuseExchange makes the token endpoint answer invalid_grant. + refuseExchange bool + // refuseIdentityToken makes the GitHub Actions endpoint answer 403. + refuseIdentityToken bool + identityTokens int + // apiRequests is " " of every API request. + apiRequests []string + // rejected reports whether the API answers 401 to an access token. + rejected func(accessToken string) bool +} + +// change updates the stand-ins' behavior between requests. +func (s *federationStandIns) change(fn func()) { + s.mu.Lock() + defer s.mu.Unlock() + fn() +} + +func (s *federationStandIns) exchangeCount() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.exchanges) +} + +func (s *federationStandIns) seenByAPI() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.apiRequests...) +} + +// federationFixture points the environment at stand-in servers and makes it +// look like a GitHub Actions job with workload identity federation set up. +func federationFixture(t *testing.T) *federationStandIns { + t.Helper() + storageFixture(t) + s := &federationStandIns{expiresIn: 300, rejected: func(string) bool { return false }} + + s.github = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + if s.refuseIdentityToken || !strings.HasPrefix(r.Header.Get("Authorization"), "Bearer request-credential-") || r.URL.Query().Get("audience") == "" { + w.WriteHeader(http.StatusForbidden) + return + } + s.identityTokens++ + _ = json.NewEncoder(w).Encode(map[string]string{"value": fmt.Sprintf("identity-token-%d", s.identityTokens)}) + })) + t.Cleanup(s.github.Close) + + s.auth = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + s.mu.Lock() + defer s.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/token" || s.refuseExchange || r.Form.Get("assertion") == "" { + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant", "error_description": "no rule matched"}) + return + } + s.exchanges = append(s.exchanges, r.Form.Get("federation_rule_id")) + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": fmt.Sprintf("access-token-%d", len(s.exchanges)), + "token_type": "Bearer", + "expires_in": s.expiresIn, + }) + })) + t.Cleanup(s.auth.Close) + + s.api = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + s.mu.Lock() + defer s.mu.Unlock() + authorization := r.Header.Get("Authorization") + s.apiRequests = append(s.apiRequests, strings.TrimSpace(authorization+" "+string(body))) + w.Header().Set("Content-Type", "application/json") + if s.rejected(strings.TrimPrefix(authorization, "Bearer ")) { + w.WriteHeader(http.StatusUnauthorized) + } + _, _ = w.Write([]byte("{}")) + })) + t.Cleanup(s.api.Close) + + for name, value := range map[string]string{ + "KERNEL_API_KEY": "", + "KERNEL_BASE_URL": s.api.URL, + "KERNEL_AUTH_BASE_URL": s.auth.URL, + credentials.EnvFederationRuleID: "wifr_test", + credentials.EnvIdentityTokenSource: "", + credentials.EnvIdentityTokenFile: "", + credentials.EnvIdentityToken: "", + credentials.EnvIdentityTokenAudience: "", + EnvFederationTokenCache: "", + "GITHUB_ACTIONS": "true", + "RUNNER_TEMP": t.TempDir(), + "ACTIONS_ID_TOKEN_REQUEST_URL": s.github.URL + "/idtoken?api-version=2", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-credential-1", + "GITHUB_REPOSITORY": "acme/app", + "GITHUB_RUN_ID": "100", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_JOB": "deploy", + } { + t.Setenv(name, value) + } + return s +} + +// newProcess authenticates the way a new CLI process does: nothing is carried +// over from an earlier call except what is on disk. +func newProcess(t *testing.T) *kernel.Client { + t.Helper() + client, err := GetAuthenticatedClient(option.WithMaxRetries(0)) + if err != nil { + t.Fatalf("GetAuthenticatedClient() error = %v", err) + } + return client +} + +func callAPI(client *kernel.Client) error { + var out map[string]any + return client.Get(context.Background(), "ping", nil, &out) +} + +func mustCallAPI(t *testing.T, client *kernel.Client) { + t.Helper() + if err := callAPI(client); err != nil { + t.Fatalf("API request error = %v", err) + } +} + +func saveLogin(t *testing.T) { + t.Helper() + if err := SaveTokens(&TokenStorage{AccessToken: "login-token", RefreshToken: "login-refresh", ExpiresAt: time.Now().Add(time.Hour)}); err != nil { + t.Fatal(err) + } +} + +func requireLoginUntouched(t *testing.T) { + t.Helper() + loaded, err := LoadTokens() + if err != nil || loaded.AccessToken != "login-token" || loaded.RefreshToken != "login-refresh" { + t.Fatalf("saved login = %+v, %v, want it untouched", loaded, err) + } +} + +func TestAuthenticationPrecedence(t *testing.T) { + for _, tc := range []struct { + name string + apiKey, rule, login bool + want string + wantExchanges int + }{ + {name: "API key beats federation and a saved login", apiKey: true, rule: true, login: true, want: "Bearer api-key"}, + {name: "API key alone", apiKey: true, want: "Bearer api-key"}, + {name: "federation beats a saved login", rule: true, login: true, want: "Bearer access-token-1", wantExchanges: 1}, + {name: "federation alone", rule: true, want: "Bearer access-token-1", wantExchanges: 1}, + {name: "saved login", login: true, want: "Bearer login-token"}, + {name: "nothing"}, + } { + t.Run(tc.name, func(t *testing.T) { + s := federationFixture(t) + if tc.apiKey { + t.Setenv("KERNEL_API_KEY", "api-key") + } + if !tc.rule { + t.Setenv(credentials.EnvFederationRuleID, "") + } + if tc.login { + saveLogin(t) + } + + client, err := GetAuthenticatedClient(option.WithMaxRetries(0)) + if tc.want == "" { + if err == nil || !strings.Contains(err.Error(), "no authentication available") { + t.Fatalf("GetAuthenticatedClient() error = %v, want no authentication available", err) + } + return + } + if err != nil { + t.Fatalf("GetAuthenticatedClient() error = %v", err) + } + mustCallAPI(t, client) + if got := s.seenByAPI(); len(got) != 1 || got[0] != tc.want { + t.Fatalf("API saw %q, want %q", got, tc.want) + } + if got := s.exchangeCount(); got != tc.wantExchanges { + t.Fatalf("token exchanges = %d, want %d", got, tc.wantExchanges) + } + if tc.login { + requireLoginUntouched(t) + } + }) + } +} + +func TestFederationFailureDoesNotFallBackToTheSavedLogin(t *testing.T) { + for _, tc := range []struct { + name string + setup func(t *testing.T, s *federationStandIns) + want string + }{ + {"no identity token source", func(t *testing.T, s *federationStandIns) { + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + }, "no identity token source could be configured"}, + {"identity provider refuses", func(t *testing.T, s *federationStandIns) { + s.change(func() { s.refuseIdentityToken = true }) + }, "could not get an identity token"}, + {"exchange refused", func(t *testing.T, s *federationStandIns) { + s.change(func() { s.refuseExchange = true }) + }, "invalid_grant"}, + {"authorization server unreachable", func(t *testing.T, s *federationStandIns) { + s.auth.Close() + }, "token request failed"}, + } { + t.Run(tc.name, func(t *testing.T) { + s := federationFixture(t) + saveLogin(t) + tc.setup(t, s) + + _, err := GetAuthenticatedClient() + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("GetAuthenticatedClient() error = %v, want %q", err, tc.want) + } + if got := s.seenByAPI(); len(got) != 0 { + t.Fatalf("API saw %q, want no request", got) + } + requireLoginUntouched(t) + }) + } +} + +func cacheFiles(t *testing.T, dir string) []string { + t.Helper() + files, err := filepath.Glob(filepath.Join(dir, "federation-token-*")) + if err != nil { + t.Fatal(err) + } + return files +} + +func TestFederationTokenIsReusedByLaterProcesses(t *testing.T) { + s := federationFixture(t) + for range 3 { + client := newProcess(t) + mustCallAPI(t, client) + mustCallAPI(t, client) + } + // One exchange also shows that the SDK's own federation support, which + // reads the same environment, did not get a token of its own. + if got := s.exchangeCount(); got != 1 { + t.Fatalf("token exchanges = %d, want 1", got) + } + for _, seen := range s.seenByAPI() { + if seen != "Bearer access-token-1" { + t.Fatalf("API saw %q, want the cached token on every request", s.seenByAPI()) + } + } + + // In a GitHub Actions job the token is kept in the job's temporary + // directory only, readable by the owner. + files := cacheFiles(t, filepath.Join(os.Getenv("RUNNER_TEMP"), "kernel-cli")) + if len(files) != 1 { + t.Fatalf("cache files in RUNNER_TEMP = %q, want one", files) + } + if runtime.GOOS != "windows" { + info, err := os.Stat(files[0]) + if err != nil || info.Mode().Perm() != 0600 { + t.Fatalf("cache file mode = %v, %v, want 0600", info.Mode().Perm(), err) + } + } + configDir, _ := getConfigDir() + if files := cacheFiles(t, configDir); len(files) != 0 { + t.Fatalf("cache files in the config directory = %q, want none", files) + } + cache, _ := federationCacheFromEnv("wifr_test") + if _, err := keyring.Get(KeyringService, cache.name); err != keyring.ErrNotFound { + t.Fatalf("keychain entry error = %v, want none stored", err) + } +} + +func TestCachedTokenIsReusedOnlyWithMoreThanSixtySecondsLeft(t *testing.T) { + for _, tc := range []struct { + left time.Duration + wantExchanges int + }{ + {-time.Minute, 1}, + {0, 1}, + {55 * time.Second, 1}, + {90 * time.Second, 0}, + {5 * time.Minute, 0}, + } { + t.Run(tc.left.String(), func(t *testing.T) { + s := federationFixture(t) + cache, _ := federationCacheFromEnv("wifr_test") + if err := cache.save(&credentials.Token{AccessToken: "cached-token", ExpiresAt: time.Now().Add(tc.left)}); err != nil { + t.Fatal(err) + } + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != tc.wantExchanges { + t.Fatalf("token exchanges = %d, want %d", got, tc.wantExchanges) + } + want := "Bearer cached-token" + if tc.wantExchanges == 1 { + want = "Bearer access-token-1" + } + if got := s.seenByAPI(); len(got) != 1 || got[0] != want { + t.Fatalf("API saw %q, want %q", got, want) + } + }) + } +} + +// leaveGitHubActions makes the environment a machine that is not running a +// GitHub Actions job. +func leaveGitHubActions(t *testing.T) { + t.Helper() + for _, name := range []string{"GITHUB_ACTIONS", "RUNNER_TEMP", "ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"} { + t.Setenv(name, "") + } +} + +// useTokenFile takes the identity token from a file, outside GitHub Actions. +func useTokenFile(t *testing.T, content string) string { + t.Helper() + leaveGitHubActions(t) + path := filepath.Join(t.TempDir(), "identity-token") + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + t.Setenv(credentials.EnvIdentityTokenFile, path) + return path +} + +func fromTokenFile(t *testing.T) { useTokenFile(t, "identity-token-from-file") } + +// Each case changes one thing about the environment after a token was cached. +// The changed environment must exchange a token of its own. +func TestCachedTokenIsNotSharedAcrossRulesServersOrWorkloads(t *testing.T) { + for _, tc := range []struct { + name string + // source replaces the GitHub Actions job with another identity token + // source before the first token is cached. + source func(t *testing.T) + change func(t *testing.T, s *federationStandIns) + // sameEntry is set when the change leaves the entry's name alone, so + // the new workload's token replaces the first one instead of sitting + // beside it. + sameEntry bool + }{ + {name: "federation rule", change: func(t *testing.T, s *federationStandIns) { + t.Setenv(credentials.EnvFederationRuleID, "wifr_other") + }}, + {name: "authorization server", change: func(t *testing.T, s *federationStandIns) { + other := httptest.NewServer(s.auth.Config.Handler) + t.Cleanup(other.Close) + t.Setenv("KERNEL_AUTH_BASE_URL", other.URL) + }}, + {name: "API origin", change: func(t *testing.T, s *federationStandIns) { + other := httptest.NewServer(s.api.Config.Handler) + t.Cleanup(other.Close) + t.Setenv("KERNEL_BASE_URL", other.URL) + }}, + {name: "identity token audience", change: func(t *testing.T, s *federationStandIns) { + t.Setenv(credentials.EnvIdentityTokenAudience, "another-audience") + }}, + {name: "repository", change: func(t *testing.T, s *federationStandIns) { + t.Setenv("GITHUB_REPOSITORY", "other/app") + }}, + {name: "workflow run", change: func(t *testing.T, s *federationStandIns) { + t.Setenv("GITHUB_RUN_ID", "101") + }}, + {name: "run attempt", change: func(t *testing.T, s *federationStandIns) { + t.Setenv("GITHUB_RUN_ATTEMPT", "2") + }}, + {name: "job", change: func(t *testing.T, s *federationStandIns) { + t.Setenv("GITHUB_JOB", "test") + }}, + // Two legs of a matrix job share the repository, run, attempt and + // job name, and can still run as different identities. + {name: "job instance", sameEntry: true, change: func(t *testing.T, s *federationStandIns) { + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "request-credential-2") + }}, + {name: "identity token file path", source: fromTokenFile, change: func(t *testing.T, s *federationStandIns) { + other := filepath.Join(t.TempDir(), "identity-token") + if err := os.WriteFile(other, []byte("identity-token-from-file"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv(credentials.EnvIdentityTokenFile, other) + }}, + {name: "identity token in the file", source: fromTokenFile, sameEntry: true, change: func(t *testing.T, s *federationStandIns) { + if err := os.WriteFile(os.Getenv(credentials.EnvIdentityTokenFile), []byte("identity-token-of-another-workload"), 0600); err != nil { + t.Fatal(err) + } + }}, + {name: "identity token in the environment", sameEntry: true, source: func(t *testing.T) { + leaveGitHubActions(t) + // The SDK lets a process exchange a literal token once, so each + // run of the test needs its own. + t.Setenv(credentials.EnvIdentityToken, fmt.Sprintf("identity-token-from-the-environment-%d", time.Now().UnixNano())) + }, change: func(t *testing.T, s *federationStandIns) { + t.Setenv(credentials.EnvIdentityToken, fmt.Sprintf("identity-token-of-another-workload-%d", time.Now().UnixNano())) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := federationFixture(t) + if tc.source != nil { + tc.source(t) + } + before := map[string]string{} + for _, entry := range os.Environ() { + name, value, _ := strings.Cut(entry, "=") + before[name] = value + } + firstCache, _ := federationCacheFromEnv(os.Getenv(credentials.EnvFederationRuleID)) + + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 1 { + t.Fatalf("token exchanges before the change = %d, want 1", got) + } + + tc.change(t, s) + secondCache, _ := federationCacheFromEnv(os.Getenv(credentials.EnvFederationRuleID)) + if sameEntry := firstCache.name == secondCache.name; sameEntry != tc.sameEntry { + t.Fatalf("same cache entry = %v, want %v", sameEntry, tc.sameEntry) + } + if secondCache.load() != nil { + t.Fatal("the changed environment can load the first token") + } + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges after the change = %d, want 2: the first token must not be reused", got) + } + if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { + t.Fatalf("API saw %q last, want the second token", got[len(got)-1]) + } + if tc.sameEntry { + return + } + + // Both tokens stay cached, each for its own environment. + for name, value := range before { + if os.Getenv(name) != value { + t.Setenv(name, value) + } + } + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges after changing back = %d, want 2: the first token is still cached", got) + } + if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-1" { + t.Fatalf("API saw %q last, want the first token", got[len(got)-1]) + } + }) + } +} + +func TestTokenFromAFileSourceIsCachedLikeALogin(t *testing.T) { + s := federationFixture(t) + useTokenFile(t, "identity-token-from-file") + saveLogin(t) + + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 1 { + t.Fatalf("token exchanges = %d, want 1", got) + } + cache, _ := federationCacheFromEnv("wifr_test") + if cache.name == KeyringUser { + t.Fatal("the federation token shares the saved login's keychain entry") + } + if _, err := keyring.Get(KeyringService, cache.name); err != nil { + t.Fatalf("keychain entry error = %v, want the token stored there", err) + } + configDir, _ := getConfigDir() + if files := cacheFiles(t, configDir); len(files) != 0 { + t.Fatalf("cache files = %q, want none while the keychain works", files) + } + + // Without a keychain the token goes to a file only the owner can read. + _ = keyring.Delete(KeyringService, cache.name) + setKeyring = func(string, string, string) error { return keyring.ErrSetDataTooBig } + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want 2", got) + } + files := cacheFiles(t, configDir) + if len(files) != 1 { + t.Fatalf("cache files = %q, want one", files) + } + if runtime.GOOS != "windows" { + if info, err := os.Stat(files[0]); err != nil || info.Mode().Perm() != 0600 { + t.Fatalf("cache file mode = %v, %v, want 0600", info.Mode().Perm(), err) + } + } + requireLoginUntouched(t) +} + +func TestTokensAreNotCachedWithoutAWorkloadScope(t *testing.T) { + for _, tc := range []struct { + name string + setup func(t *testing.T) + want string + }{ + {"AWS", func(t *testing.T) { t.Setenv(credentials.EnvIdentityTokenSource, credentials.SourceAWSSTS) }, "aws_sts"}, + {"Google Cloud", func(t *testing.T) { t.Setenv(credentials.EnvIdentityTokenSource, credentials.SourceGCPMetadata) }, "gcp_metadata"}, + {"GitHub Actions without a job directory", func(t *testing.T) { t.Setenv("RUNNER_TEMP", "") }, "RUNNER_TEMP"}, + {"GitHub Actions token outside a job", func(t *testing.T) { t.Setenv("GITHUB_ACTIONS", "") }, "RUNNER_TEMP"}, + {"unreadable token file", func(t *testing.T) { + t.Setenv(credentials.EnvIdentityTokenFile, filepath.Join(t.TempDir(), "missing")) + }, "identity token file"}, + } { + t.Run(tc.name, func(t *testing.T) { + federationFixture(t) + tc.setup(t) + cache, reason := federationCacheFromEnv("wifr_test") + if cache != nil || !strings.Contains(reason, tc.want) { + t.Fatalf("federationCacheFromEnv() = %+v, %q, want no cache because of %s", cache, reason, tc.want) + } + }) + } + + // Without a cache every process exchanges, and nothing is written. + s := federationFixture(t) + runnerTemp := os.Getenv("RUNNER_TEMP") + t.Setenv("GITHUB_ACTIONS", "") + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want 2", got) + } + requireNothingCached(t, runnerTemp) +} + +func requireNothingCached(t *testing.T, runnerTemp string) { + t.Helper() + configDir, _ := getConfigDir() + for _, dir := range []string{configDir, filepath.Join(runnerTemp, "kernel-cli")} { + if files := cacheFiles(t, dir); len(files) != 0 { + t.Fatalf("cache files = %q, want none", files) + } + } +} + +func TestCacheCanBeTurnedOff(t *testing.T) { + for _, value := range []string{"off", "OFF", "false", "0", "no"} { + t.Run(value, func(t *testing.T) { + s := federationFixture(t) + t.Setenv(EnvFederationTokenCache, value) + for range 2 { + client := newProcess(t) + mustCallAPI(t, client) + mustCallAPI(t, client) + } + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want one per process", got) + } + requireNothingCached(t, os.Getenv("RUNNER_TEMP")) + if status := DescribeFederation(); status == nil || !strings.Contains(status.NotCached, EnvFederationTokenCache) { + t.Fatalf("DescribeFederation() = %+v, want the cache reported off", status) + } + }) + } +} + +func TestCacheTurnedOffIgnoresAnExistingEntry(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + t.Setenv(EnvFederationTokenCache, "off") + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want 2", got) + } + if got := s.seenByAPI(); got[1] != "Bearer access-token-2" { + t.Fatalf("API saw %q, want a new token with the cache off", got) + } +} + +func TestRejectedCachedTokenIsDroppedAndTheRequestRetriedOnce(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + + // The API stops accepting the cached token, as when it is revoked. + s.change(func() { + s.rejected = func(accessToken string) bool { return accessToken == "access-token-1" } + s.apiRequests = nil + }) + + client := newProcess(t) + var out map[string]any + if err := client.Post(context.Background(), "things", map[string]string{"name": "thing"}, &out); err != nil { + t.Fatalf("API request error = %v, want the retry to succeed", err) + } + want := []string{`Bearer access-token-1 {"name":"thing"}`, `Bearer access-token-2 {"name":"thing"}`} + if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("API saw %q, want %q", got, want) + } + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want 2", got) + } + + // The replacement is what later requests and processes use. + mustCallAPI(t, client) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want the replacement cached", got) + } + if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { + t.Fatalf("API saw %q last, want the replacement", got[len(got)-1]) + } +} + +func TestSecondRejectionFailsTheCommand(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.rejected = func(string) bool { return true } + s.apiRequests = nil + }) + + err := callAPI(newProcess(t)) + if err == nil || !strings.Contains(err.Error(), "401") { + t.Fatalf("API request error = %v, want the 401", err) + } + want := []string{"Bearer access-token-1", "Bearer access-token-2"} + if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("API saw %q, want %q: one retry, with a new token", got, want) + } + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want 2", got) + } +} + +func TestRejectedTokenIsDroppedWhenTheExchangeFails(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.rejected = func(string) bool { return true } + s.refuseExchange = true + }) + + client := newProcess(t) + if err := callAPI(client); err == nil || !strings.Contains(err.Error(), "invalid_grant") { + t.Fatalf("API request error = %v, want the refused exchange", err) + } + cache, _ := federationCacheFromEnv("wifr_test") + if entry := cache.load(); entry != nil { + t.Fatal("the rejected token is still cached") + } + if _, err := GetAuthenticatedClient(); err == nil { + t.Fatal("GetAuthenticatedClient() succeeded, want the refused exchange") + } +} + +func TestParallelProcessesNeverReadAPartialEntry(t *testing.T) { + for _, store := range []string{"job directory", "config directory"} { + t.Run(store, func(t *testing.T) { + federationFixture(t) + if store == "config directory" { + useTokenFile(t, "identity-token-from-file") + setKeyring = func(string, string, string) error { return keyring.ErrSetDataTooBig } + } + cache, _ := federationCacheFromEnv("wifr_test") + path, err := cache.filePath() + if err != nil { + t.Fatal(err) + } + // Tokens large enough that a write in place would be seen half done. + tokens := make([]string, 8) + for i := range tokens { + tokens[i] = strings.Repeat(fmt.Sprint(i), 256<<10) + } + expiresAt := time.Now().Add(5 * time.Minute) + + var writers, readers sync.WaitGroup + done := make(chan struct{}) + for _, token := range tokens { + writers.Add(1) + go func() { + defer writers.Done() + for range 20 { + if err := cache.save(&credentials.Token{AccessToken: token, ExpiresAt: expiresAt}); err != nil { + t.Errorf("save() error = %v", err) + } + } + }() + } + for range 4 { + readers.Add(1) + go func() { + defer readers.Done() + for { + select { + case <-done: + return + default: + } + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + continue + } + var entry federationCacheEntry + if err != nil || json.Unmarshal(data, &entry) != nil || len(entry.AccessToken) != 256<<10 || + strings.Trim(entry.AccessToken, entry.AccessToken[:1]) != "" { + t.Errorf("read a partial cache entry (%d bytes, error %v)", len(data), err) + return + } + if got := cache.load(); got == nil || len(got.AccessToken) != 256<<10 { + t.Errorf("load() = %v, want a complete entry", got != nil) + return + } + } + }() + } + writers.Wait() + close(done) + readers.Wait() + + if leftovers, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "*.tmp")); len(leftovers) != 0 { + t.Fatalf("temporary files left behind: %q", leftovers) + } + }) + } +} + +func TestProcessesStartingTogetherAllAuthenticate(t *testing.T) { + s := federationFixture(t) + var wg sync.WaitGroup + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + client, err := GetAuthenticatedClient(option.WithMaxRetries(0)) + if err != nil { + t.Errorf("GetAuthenticatedClient() error = %v", err) + return + } + if err := callAPI(client); err != nil { + t.Errorf("API request error = %v", err) + } + }() + } + wg.Wait() + if got := s.exchangeCount(); got < 1 || got > 8 { + t.Fatalf("token exchanges = %d, want between 1 and 8", got) + } + for _, seen := range s.seenByAPI() { + if !strings.HasPrefix(seen, "Bearer access-token-") { + t.Fatalf("API saw %q, want a complete token", seen) + } + } + // Whichever process wrote last, the next one finds a usable token. + before := s.exchangeCount() + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != before { + t.Fatalf("token exchanges = %d, want %d: a token is cached", got, before) + } +} + +func TestDescribeFederation(t *testing.T) { + s := federationFixture(t) + status := DescribeFederation() + if status == nil || status.RuleID != "wifr_test" || status.Err != nil || status.NotCached != "" || !status.CachedTokenExpiresAt.IsZero() { + t.Fatalf("DescribeFederation() = %+v, want the rule with nothing cached yet", status) + } + if got := s.exchangeCount(); got != 0 { + t.Fatalf("token exchanges = %d: describing must not exchange", got) + } + + mustCallAPI(t, newProcess(t)) + status = DescribeFederation() + if left := time.Until(status.CachedTokenExpiresAt); left < 4*time.Minute || left > 5*time.Minute { + t.Fatalf("cached token expires in %s, want the five minutes the exchange returned", left) + } + + t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "") + if status = DescribeFederation(); status.Err == nil { + t.Fatalf("DescribeFederation() = %+v, want the missing identity token source reported", status) + } + t.Setenv(credentials.EnvFederationRuleID, "") + if status = DescribeFederation(); status != nil { + t.Fatalf("DescribeFederation() = %+v, want nil without a rule", status) + } +} + +func TestTokensAreNeverPrinted(t *testing.T) { + s := federationFixture(t) + var output bytes.Buffer + pterm.EnableDebugMessages() + debugWriter := pterm.Debug.Writer + pterm.Debug.Writer = &output + t.Cleanup(func() { + pterm.DisableDebugMessages() + pterm.Debug.Writer = debugWriter + }) + + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + s.change(func() { s.rejected = func(accessToken string) bool { return accessToken == "access-token-1" } }) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.rejected = func(string) bool { return true } + s.refuseExchange = true + }) + apiErr := callAPI(newProcess(t)) + _, authErr := GetAuthenticatedClient() + if apiErr == nil || authErr == nil { + t.Fatalf("errors = %v, %v, want both to fail", apiErr, authErr) + } + fmt.Fprintln(&output, apiErr, authErr) + + if !strings.Contains(output.String(), "Using the cached workload identity token") { + t.Fatalf("debug output = %q, want it to say the cached token was used", output.String()) + } + for _, secret := range []string{"access-token-", "identity-token-", "request-credential-"} { + if strings.Contains(output.String(), secret) { + t.Fatalf("output contains %q:\n%s", secret, output.String()) + } + } +} From 6d8b4e7d10048ac783885e4b1ff798a14ea1b1dd Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:39:25 +0000 Subject: [PATCH 2/5] Tighten the workload identity token cache 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. --- README.md | 2 +- pkg/auth/client.go | 8 +- pkg/auth/federation.go | 51 ++++++++-- pkg/auth/federation_cache.go | 16 +++- pkg/auth/federation_test.go | 174 ++++++++++++++++++++++++++++++++--- 5 files changed, 224 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 20dbfe0e..50b81bf8 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ steps: The CLI authenticates with the first of these that is configured: `KERNEL_API_KEY`, then `KERNEL_FEDERATION_RULE_ID`, then the login saved by `kernel login`. When `KERNEL_FEDERATION_RULE_ID` is set and the exchange fails, the command fails. It does not fall back to a saved login. `kernel auth` shows which one is in use. -Each command is a new process, so the access token is cached between commands until 60 seconds before it expires. If the API rejects a cached token, the CLI drops it, exchanges a new one and retries the request once. A token is cached only where it can be tied to the workload that obtained it: +Each command is a new process, so the access token is cached between commands until 60 seconds before it expires. If the API rejects a cached token, the CLI drops it, exchanges a new one and retries the request once. Vault writes, which are never sent twice, are not retried: the command fails and the next one exchanges a new token. A token is cached only where it can be tied to the workload that obtained it: | Identity token source | Cached | Where | Reused only by | | --- | --- | --- | --- | diff --git a/pkg/auth/client.go b/pkg/auth/client.go index f3851da3..02c04aed 100644 --- a/pkg/auth/client.go +++ b/pkg/auth/client.go @@ -32,15 +32,11 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error if err != nil { return nil, err } - token, err := federation.tokens.Token(context.Background()) - if err != nil { + if _, err := federation.tokens.Token(context.Background()); err != nil { return nil, err } - // The header makes the SDK's own federation support, which reads the - // same environment variables and has no cache, leave requests alone. - // The middleware replaces it with the current token on each request. authOpts := append(opts, - option.WithHeader("Authorization", "Bearer "+token.AccessToken), + option.WithHeader("Authorization", federationPlaceholder), option.WithMiddleware(federation.middleware), ) client := kernel.NewClient(authOpts...) diff --git a/pkg/auth/federation.go b/pkg/auth/federation.go index 3cc1fa6d..0db5e1ad 100644 --- a/pkg/auth/federation.go +++ b/pkg/auth/federation.go @@ -18,6 +18,13 @@ import ( "github.com/pterm/pterm" ) +// federationPlaceholder is the Authorization header every request starts +// with. The SDK's own federation support, which reads the same environment +// variables and has no cache, leaves a request that has the header alone. The +// middleware replaces it with the access token on requests to the API and +// removes it from any other. +const federationPlaceholder = "Bearer workload-identity" + // federation authenticates requests with workload identity federation: the // workload's identity token is exchanged for a short-lived Kernel access // token, which is kept on disk between CLI processes (see federationCache). @@ -33,11 +40,22 @@ type federation struct { rejected string } +// exchangedAssertionKey is the context key of a *string that receives the +// identity token an exchange sends. +type exchangedAssertionKey struct{} + func newFederation() (*federation, error) { source, opts, err := credentials.FederationFromEnv() if err != nil { return nil, err } + identityToken := func(ctx context.Context) (string, error) { + assertion, err := source(ctx) + if sent, _ := ctx.Value(exchangedAssertionKey{}).(*string); sent != nil { + *sent = strings.TrimSpace(assertion) + } + return assertion, err + } apiBaseURL := util.GetBaseURL() apiURL, err := url.Parse(apiBaseURL) if err != nil { @@ -47,7 +65,7 @@ func newFederation() (*federation, error) { ruleID: opts.FederationRuleID, apiURL: apiURL, exchange: credentials.NewFederationProvider(credentials.FederationConfig{ - IdentityTokenProvider: source, + IdentityTokenProvider: identityToken, FederationRuleID: opts.FederationRuleID, APIBaseURL: apiBaseURL, }), @@ -66,15 +84,24 @@ func (f *federation) token(ctx context.Context, force bool) (*credentials.Token, } else if !force { if entry := cache.load(); entry != nil { pterm.Debug.Printfln("Using the cached workload identity token (valid for %s)", time.Until(entry.ExpiresAt).Round(time.Second)) - return &credentials.Token{AccessToken: entry.AccessToken, ExpiresAt: entry.ExpiresAt}, nil + // The expiry is brought forward by the margin, so this process + // comes back for another token before the cached one has less + // than the margin left. + return &credentials.Token{AccessToken: entry.AccessToken, ExpiresAt: entry.ExpiresAt.Add(-federationCacheMargin)}, nil } } - token, err := f.exchange(ctx, force) + var assertion string + token, err := f.exchange(context.WithValue(ctx, exchangedAssertionKey{}, &assertion), force) if err != nil { return nil, err } pterm.Debug.Printfln("Exchanged an identity token for a Kernel access token (valid for %s)", time.Until(token.ExpiresAt).Round(time.Second)) if cache != nil { + if cache.fromFile { + // The file may have changed since the cache was looked up. The + // token belongs to the identity that was exchanged for it. + cache.binding = federationBinding(assertion) + } if err := cache.save(token); err != nil { pterm.Debug.Printfln("Could not cache the workload identity token: %v", err) } @@ -103,6 +130,9 @@ func (f *federation) reject(accessToken string) { func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { // The token is for the API only. if !sameOrigin(req.URL, f.apiURL) { + if req.Header.Get("Authorization") == federationPlaceholder { + req.Header.Del("Authorization") + } return next(req) } token, err := f.tokens.Token(req.Context()) @@ -134,11 +164,20 @@ func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) ( return unauthenticated(req, err) } req.Header.Set("Authorization", "Bearer "+token.AccessToken) - return next(req) + resp, err = next(req) + // The request is sent again only this once, whatever comes back. + if err != nil { + return unauthenticated(req, err) + } + resp.Header.Set("X-Should-Retry", "false") + if resp.StatusCode == http.StatusUnauthorized && sameOrigin(req.URL, f.apiURL) { + f.reject(token.AccessToken) + } + return resp, nil } -// unauthenticated fails a request that has no access token. The response -// tells the client not to send the request again. +// unauthenticated fails a request with err. The response tells the client +// not to send the request again. func unauthenticated(req *http.Request, err error) (*http.Response, error) { return &http.Response{ Status: "credentials unavailable", diff --git a/pkg/auth/federation_cache.go b/pkg/auth/federation_cache.go index 4d58b896..becc588f 100644 --- a/pkg/auth/federation_cache.go +++ b/pkg/auth/federation_cache.go @@ -49,6 +49,9 @@ type federationCacheEntry struct { type federationCache struct { name string binding string + // fromFile is set when the identity token comes from a file, whose + // content is part of the binding. + fromFile bool // dir holds the entry as a file when set, and the keychain is not used. // It is the per-job temporary directory of a GitHub Actions runner. dir string @@ -84,7 +87,7 @@ func federationCacheFromEnv(ruleID string) (*federationCache, string) { if os.Getenv("GITHUB_ACTIONS") == "true" && os.Getenv("RUNNER_TEMP") != "" { cache.dir = filepath.Join(os.Getenv("RUNNER_TEMP"), "kernel-cli") } - var fileToken string + fileToken := "" switch source { case credentials.SourceGitHubActions: if cache.dir == "" { @@ -98,6 +101,7 @@ func federationCacheFromEnv(ruleID string) (*federationCache, string) { if abs, err := filepath.Abs(tokenFile); err == nil { tokenFile = abs } + cache.fromFile = true case credentials.SourceEnv: default: // The identity comes from the machine's surroundings (an AWS role, a @@ -111,11 +115,17 @@ func federationCacheFromEnv(ruleID string) (*federationCache, string) { os.Getenv(credentials.EnvIdentityTokenAudience), source, tokenFile, os.Getenv("GITHUB_REPOSITORY"), os.Getenv("GITHUB_RUN_ID"), os.Getenv("GITHUB_RUN_ATTEMPT"), os.Getenv("GITHUB_JOB"), ) - cache.binding = digest( + cache.binding = federationBinding(fileToken) + return cache, "" +} + +// federationBinding is the binding of a workload whose identity token file, +// if it uses one, holds fileToken. +func federationBinding(fileToken string) string { + return digest( os.Getenv("ACTIONS_ID_TOKEN_REQUEST_URL"), os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN"), fileToken, strings.TrimSpace(os.Getenv(credentials.EnvIdentityToken)), ) - return cache, "" } // digest hashes parts so that no two lists of parts collide. diff --git a/pkg/auth/federation_test.go b/pkg/auth/federation_test.go index 9b562433..08befe71 100644 --- a/pkg/auth/federation_test.go +++ b/pkg/auth/federation_test.go @@ -40,8 +40,10 @@ type federationStandIns struct { identityTokens int // apiRequests is " " of every API request. apiRequests []string - // rejected reports whether the API answers 401 to an access token. - rejected func(accessToken string) bool + // apiStatus is the status the API answers a request with. + apiStatus func(accessToken string) int + // assertions is the identity token of every token request. + assertions []string } // change updates the stand-ins' behavior between requests. @@ -51,6 +53,17 @@ func (s *federationStandIns) change(fn func()) { fn() } +// rejectOnly makes the API answer 401 to one access token, as when it is +// revoked. +func rejectOnly(accessToken string) func(string) int { + return func(got string) int { + if got == accessToken { + return http.StatusUnauthorized + } + return http.StatusOK + } +} + func (s *federationStandIns) exchangeCount() int { s.mu.Lock() defer s.mu.Unlock() @@ -68,7 +81,7 @@ func (s *federationStandIns) seenByAPI() []string { func federationFixture(t *testing.T) *federationStandIns { t.Helper() storageFixture(t) - s := &federationStandIns{expiresIn: 300, rejected: func(string) bool { return false }} + s := &federationStandIns{expiresIn: 300, apiStatus: func(string) int { return http.StatusOK }} s.github = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.mu.Lock() @@ -93,6 +106,7 @@ func federationFixture(t *testing.T) *federationStandIns { return } s.exchanges = append(s.exchanges, r.Form.Get("federation_rule_id")) + s.assertions = append(s.assertions, r.Form.Get("assertion")) _ = json.NewEncoder(w).Encode(map[string]any{ "access_token": fmt.Sprintf("access-token-%d", len(s.exchanges)), "token_type": "Bearer", @@ -108,9 +122,7 @@ func federationFixture(t *testing.T) *federationStandIns { authorization := r.Header.Get("Authorization") s.apiRequests = append(s.apiRequests, strings.TrimSpace(authorization+" "+string(body))) w.Header().Set("Content-Type", "application/json") - if s.rejected(strings.TrimPrefix(authorization, "Bearer ")) { - w.WriteHeader(http.StatusUnauthorized) - } + w.WriteHeader(s.apiStatus(strings.TrimPrefix(authorization, "Bearer "))) _, _ = w.Write([]byte("{}")) })) t.Cleanup(s.api.Close) @@ -344,6 +356,62 @@ func TestCachedTokenIsReusedOnlyWithMoreThanSixtySecondsLeft(t *testing.T) { } } +// A token loaded with just over a minute left is not used once it has less. +func TestCachedTokenIsNotSentWithLessThanSixtySecondsLeft(t *testing.T) { + s := federationFixture(t) + cache, _ := federationCacheFromEnv("wifr_test") + if err := cache.save(&credentials.Token{AccessToken: "cached-token", ExpiresAt: time.Now().Add(61 * time.Second)}); err != nil { + t.Fatal(err) + } + client := newProcess(t) + mustCallAPI(t, client) + time.Sleep(1200 * time.Millisecond) + mustCallAPI(t, client) + want := []string{"Bearer cached-token", "Bearer access-token-1"} + if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("API saw %q, want %q", got, want) + } +} + +// The token file can be replaced between the cache lookup and the exchange. +// The new token is then cached for the identity that was exchanged, not for +// the one the lookup saw. +func TestTokenIsCachedForTheIdentityThatWasExchanged(t *testing.T) { + s := federationFixture(t) + path := useTokenFile(t, "identity-token-a") + f, err := newFederation() + if err != nil { + t.Fatal(err) + } + exchange := f.exchange + f.exchange = func(ctx context.Context, force bool) (*credentials.Token, error) { + if err := os.WriteFile(path, []byte("identity-token-b\n"), 0600); err != nil { + t.Error(err) + } + return exchange(ctx, force) + } + if _, err := f.tokens.Token(context.Background()); err != nil { + t.Fatal(err) + } + s.change(func() { + if got := s.assertions; len(got) != 1 || got[0] != "identity-token-b" { + t.Errorf("exchanged identity tokens = %q, want identity-token-b", got) + } + }) + + cache, _ := federationCacheFromEnv("wifr_test") + if cache.load() == nil { + t.Fatal("the workload that exchanged the token cannot load it") + } + if err := os.WriteFile(path, []byte("identity-token-a"), 0600); err != nil { + t.Fatal(err) + } + cache, _ = federationCacheFromEnv("wifr_test") + if cache.load() != nil { + t.Fatal("the workload the lookup saw can load a token exchanged for another identity") + } +} + // leaveGitHubActions makes the environment a machine that is not running a // GitHub Actions job. func leaveGitHubActions(t *testing.T) { @@ -618,7 +686,7 @@ func TestRejectedCachedTokenIsDroppedAndTheRequestRetriedOnce(t *testing.T) { // The API stops accepting the cached token, as when it is revoked. s.change(func() { - s.rejected = func(accessToken string) bool { return accessToken == "access-token-1" } + s.apiStatus = rejectOnly("access-token-1") s.apiRequests = nil }) @@ -650,7 +718,7 @@ func TestSecondRejectionFailsTheCommand(t *testing.T) { s := federationFixture(t) mustCallAPI(t, newProcess(t)) s.change(func() { - s.rejected = func(string) bool { return true } + s.apiStatus = func(string) int { return http.StatusUnauthorized } s.apiRequests = nil }) @@ -665,13 +733,97 @@ func TestSecondRejectionFailsTheCommand(t *testing.T) { if got := s.exchangeCount(); got != 2 { t.Fatalf("token exchanges = %d, want 2", got) } + cache, _ := federationCacheFromEnv("wifr_test") + if cache.load() != nil { + t.Fatal("the replacement the API rejected is still cached") + } +} + +// The request is sent a second time only once: the SDK's own retries, which +// are on by default, must not send it a third time. +func TestRetryAfterRejectionIsFinal(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.apiStatus = func(accessToken string) int { + if accessToken == "access-token-1" { + return http.StatusUnauthorized + } + return http.StatusServiceUnavailable + } + s.apiRequests = nil + }) + + client, err := GetAuthenticatedClient() + if err != nil { + t.Fatal(err) + } + if err := callAPI(client); err == nil || !strings.Contains(err.Error(), "503") { + t.Fatalf("API request error = %v, want the 503", err) + } + want := []string{"Bearer access-token-1", "Bearer access-token-2"} + if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("API saw %q, want %q", got, want) + } +} + +// Vault writes remove the request's replayable body so that they are never +// sent twice. A rejected token is dropped and the 401 returned. +func TestRejectionOfARequestThatMustNotBeReplayedIsNotRetried(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.apiStatus = rejectOnly("access-token-1") + s.apiRequests = nil + }) + + noReplay := option.WithMiddleware(func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { + req.GetBody = nil + return next(req) + }) + var out map[string]any + err := newProcess(t).Post(context.Background(), "things", map[string]string{"name": "thing"}, &out, noReplay) + if err == nil || !strings.Contains(err.Error(), "401") { + t.Fatalf("API request error = %v, want the 401", err) + } + if got := s.seenByAPI(); len(got) != 1 { + t.Fatalf("API saw %q, want the request sent once", got) + } + mustCallAPI(t, newProcess(t)) + if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { + t.Fatalf("API saw %q last, want the next command to use a new token", got[len(got)-1]) + } +} + +func TestTokenIsSentToTheAPIOnly(t *testing.T) { + s := federationFixture(t) + seen := make(chan string, 1) + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen <- r.Header.Get("Authorization") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte("{}")) + })) + defer other.Close() + + client := newProcess(t) + var out map[string]any + if err := client.Get(context.Background(), other.URL+"/elsewhere", nil, &out); err != nil { + t.Fatal(err) + } + if got := <-seen; got != "" { + t.Fatalf("another host saw Authorization %q, want none", got) + } + mustCallAPI(t, client) + if got := s.seenByAPI(); len(got) != 1 || got[0] != "Bearer access-token-1" { + t.Fatalf("API saw %q, want the access token", got) + } } func TestRejectedTokenIsDroppedWhenTheExchangeFails(t *testing.T) { s := federationFixture(t) mustCallAPI(t, newProcess(t)) s.change(func() { - s.rejected = func(string) bool { return true } + s.apiStatus = func(string) int { return http.StatusUnauthorized } s.refuseExchange = true }) @@ -832,10 +984,10 @@ func TestTokensAreNeverPrinted(t *testing.T) { mustCallAPI(t, newProcess(t)) mustCallAPI(t, newProcess(t)) - s.change(func() { s.rejected = func(accessToken string) bool { return accessToken == "access-token-1" } }) + s.change(func() { s.apiStatus = rejectOnly("access-token-1") }) mustCallAPI(t, newProcess(t)) s.change(func() { - s.rejected = func(string) bool { return true } + s.apiStatus = func(string) int { return http.StatusUnauthorized } s.refuseExchange = true }) apiErr := callAPI(newProcess(t)) From 61d3a4d501691a3c51a915c3c921742799835eed Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:44:20 +0000 Subject: [PATCH 3/5] Send a request that must not be replayed once 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. --- cmd/vaults_federation_test.go | 81 +++++++++++++++++++++++++++++++++++ pkg/auth/federation.go | 19 +++++++- pkg/auth/federation_cache.go | 3 +- pkg/auth/federation_test.go | 69 +++++++++++++++++++++-------- 4 files changed, 152 insertions(+), 20 deletions(-) create mode 100644 cmd/vaults_federation_test.go diff --git a/cmd/vaults_federation_test.go b/cmd/vaults_federation_test.go new file mode 100644 index 00000000..a63751fe --- /dev/null +++ b/cmd/vaults_federation_test.go @@ -0,0 +1,81 @@ +package cmd + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/kernel/cli/pkg/auth" + kernel "github.com/kernel/kernel-go-sdk" + "github.com/kernel/kernel-go-sdk/option" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// With workload identity federation, a request the API answers 401 is sent +// again with a new token. Vault writes are the exception: they are sent once. +func TestVaultWritesAreNotReplayedAfterARejectedFederationToken(t *testing.T) { + var mu sync.Mutex + var requests []string + issued := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/token" { + issued++ + _ = json.NewEncoder(w).Encode(map[string]any{"access_token": fmt.Sprintf("access-token-%d", issued), "token_type": "Bearer", "expires_in": 300}) + return + } + requests = append(requests, r.Method+" "+r.URL.Path) + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"code":"unauthorized","message":"invalid token"}`)) + })) + defer server.Close() + + tokenFile := filepath.Join(t.TempDir(), "identity-token") + require.NoError(t, os.WriteFile(tokenFile, []byte("identity-token"), 0600)) + for name, value := range map[string]string{ + "KERNEL_API_KEY": "", "KERNEL_BASE_URL": server.URL, "KERNEL_AUTH_BASE_URL": server.URL, + "KERNEL_FEDERATION_RULE_ID": "wifr_vaults", "KERNEL_IDENTITY_TOKEN_SOURCE": "", "KERNEL_IDENTITY_TOKEN": "", + "KERNEL_IDENTITY_TOKEN_FILE": tokenFile, auth.EnvFederationTokenCache: "off", + } { + t.Setenv(name, value) + } + client, err := auth.GetAuthenticatedClient() + require.NoError(t, err) + ctx := context.Background() + + for _, tc := range []struct { + name string + send func(opts ...option.RequestOption) error + }{ + {"with a body", func(opts ...option.RequestOption) error { + _, err := client.Vaults.Upsert(ctx, kernel.VaultUpsertParams{Name: "user"}, opts...) + return err + }}, + {"without a body", func(opts ...option.RequestOption) error { + return client.Vaults.Delete(ctx, "user", opts...) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + sent := func(send func() error) int { + mu.Lock() + requests = nil + mu.Unlock() + require.Error(t, send()) + mu.Lock() + defer mu.Unlock() + return len(requests) + } + assert.Equal(t, 1, sent(func() error { return tc.send(vaultWriteRequestOptions()...) }), "a vault write is sent once") + assert.Equal(t, 2, sent(func() error { return tc.send(option.WithMaxRetries(0)) }), "the same request without the vault options is sent again") + }) + } +} diff --git a/pkg/auth/federation.go b/pkg/auth/federation.go index 0db5e1ad..97a556b9 100644 --- a/pkg/auth/federation.go +++ b/pkg/auth/federation.go @@ -126,7 +126,7 @@ func (f *federation) reject(accessToken string) { // middleware authenticates each API request with the current access token. // When the API answers 401 it drops that token, exchanges a new one and sends -// the request once more. +// the request once more, unless the request must not be sent twice. func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { // The token is for the API only. if !sameOrigin(req.URL, f.apiURL) { @@ -148,7 +148,7 @@ func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) ( } f.reject(token.AccessToken) - if req.Body != nil && req.GetBody == nil { + if !replayable(req) { return resp, nil } if req.GetBody != nil { @@ -187,6 +187,21 @@ func unauthenticated(req *http.Request, err error) (*http.Response, error) { }, err } +// replayable reports whether req may be sent a second time, by the rule +// net/http applies before it replays a request on a new connection: the body +// can be read again, and the method is safe or the request carries an +// idempotency key. Vault writes take both away so that they are sent once. +func replayable(req *http.Request) bool { + if req.Body != nil && req.Body != http.NoBody && req.GetBody == nil { + return false + } + switch req.Method { + case "", http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace: + return true + } + return req.Header.Get("Idempotency-Key") != "" || req.Header.Get("X-Idempotency-Key") != "" +} + func sameOrigin(a, b *url.URL) bool { return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host) } diff --git a/pkg/auth/federation_cache.go b/pkg/auth/federation_cache.go index becc588f..f8c0e614 100644 --- a/pkg/auth/federation_cache.go +++ b/pkg/auth/federation_cache.go @@ -246,7 +246,8 @@ func writeFileAtomically(path string, data []byte) error { } // forget removes the cached token if it is still accessToken, which the API -// rejected. A token another process has stored since then is kept. +// rejected. The check and the removal are separate steps: a token another +// process stores in between is removed too, which costs one more exchange. func (c *federationCache) forget(accessToken string) { fromKeyring, fromFile := c.copies() if fromKeyring != nil && fromKeyring.AccessToken == accessToken { diff --git a/pkg/auth/federation_test.go b/pkg/auth/federation_test.go index 08befe71..d4efedec 100644 --- a/pkg/auth/federation_test.go +++ b/pkg/auth/federation_test.go @@ -767,31 +767,66 @@ func TestRetryAfterRejectionIsFinal(t *testing.T) { } } -// Vault writes remove the request's replayable body so that they are never -// sent twice. A rejected token is dropped and the 401 returned. +// Vault writes take away what would let a request be sent twice: the +// replayable body, and for a request without a body the idempotency key. A +// rejected token is dropped and the 401 returned. func TestRejectionOfARequestThatMustNotBeReplayedIsNotRetried(t *testing.T) { + noReplay := option.WithMiddleware(func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { + req.GetBody = nil + if req.Body == nil || req.Body == http.NoBody { + req.Header.Del("Idempotency-Key") + req.Header.Del("X-Idempotency-Key") + } + return next(req) + }) + for _, tc := range []struct { + name string + send func(client *kernel.Client) error + }{ + {"write with a body", func(client *kernel.Client) error { + return client.Post(context.Background(), "things", map[string]string{"name": "thing"}, nil, noReplay) + }}, + {"write without a body", func(client *kernel.Client) error { + return client.Delete(context.Background(), "things/thing", nil, nil, noReplay) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := federationFixture(t) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.apiStatus = rejectOnly("access-token-1") + s.apiRequests = nil + }) + + if err := tc.send(newProcess(t)); err == nil || !strings.Contains(err.Error(), "401") { + t.Fatalf("API request error = %v, want the 401", err) + } + if got := s.seenByAPI(); len(got) != 1 { + t.Fatalf("API saw %q, want the request sent once", got) + } + mustCallAPI(t, newProcess(t)) + if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { + t.Fatalf("API saw %q last, want the next command to use a new token", got[len(got)-1]) + } + }) + } +} + +// A write that keeps its idempotency key is sent again after a rejection, +// with or without a body. +func TestRejectedWriteWithoutABodyIsRetried(t *testing.T) { s := federationFixture(t) mustCallAPI(t, newProcess(t)) s.change(func() { s.apiStatus = rejectOnly("access-token-1") s.apiRequests = nil }) - - noReplay := option.WithMiddleware(func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { - req.GetBody = nil - return next(req) - }) - var out map[string]any - err := newProcess(t).Post(context.Background(), "things", map[string]string{"name": "thing"}, &out, noReplay) - if err == nil || !strings.Contains(err.Error(), "401") { - t.Fatalf("API request error = %v, want the 401", err) - } - if got := s.seenByAPI(); len(got) != 1 { - t.Fatalf("API saw %q, want the request sent once", got) + if err := newProcess(t).Delete(context.Background(), "things/thing", nil, nil); err != nil { + t.Fatalf("API request error = %v, want the retry to succeed", err) } - mustCallAPI(t, newProcess(t)) - if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { - t.Fatalf("API saw %q last, want the next command to use a new token", got[len(got)-1]) + want := []string{"Bearer access-token-1", "Bearer access-token-2"} + if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("API saw %q, want %q", got, want) } } From 19d9d8a635ecc4dfd22cc49d332420dbc7147934 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:57:16 +0000 Subject: [PATCH 4/5] Share one credential order between commands and kernel auth --- cmd/auth.go | 11 +++++----- pkg/auth/client.go | 42 ++++++++++++++++++++++++++++--------- pkg/auth/federation_test.go | 21 +++++++++++++++++++ 3 files changed, 58 insertions(+), 16 deletions(-) diff --git a/cmd/auth.go b/cmd/auth.go index e7dc16ca..891a441a 100644 --- a/cmd/auth.go +++ b/cmd/auth.go @@ -74,8 +74,9 @@ func parseJWT(tokenString string) (*JWTClaims, error) { } func runAuth(cmd *cobra.Command, args []string) error { - // The sources are reported in the order commands try them. - if apiKey := os.Getenv("KERNEL_API_KEY"); apiKey != "" { + switch auth.ActiveCredential() { + case auth.CredentialAPIKey: + apiKey := os.Getenv("KERNEL_API_KEY") pterm.Info.Println("Authentication method: API Key") pterm.Info.Printf("API URL: %s\n", util.GetBaseURL()) if len(apiKey) >= 12 { @@ -84,10 +85,8 @@ func runAuth(cmd *cobra.Command, args []string) error { pterm.Info.Printf("API Key: %s\n", strings.Repeat("*", len(apiKey))) } return nil - } - - if federation := auth.DescribeFederation(); federation != nil { - printFederationStatus(federation) + case auth.CredentialFederation: + printFederationStatus(auth.DescribeFederation()) return nil } diff --git a/pkg/auth/client.go b/pkg/auth/client.go index 02c04aed..293a91ab 100644 --- a/pkg/auth/client.go +++ b/pkg/auth/client.go @@ -12,21 +12,44 @@ import ( "github.com/pterm/pterm" ) +// Credential is a way commands authenticate to the Kernel API. +type Credential int + +const ( + // CredentialAPIKey is the key in KERNEL_API_KEY. + CredentialAPIKey Credential = iota + // CredentialFederation is workload identity federation through the rule + // in KERNEL_FEDERATION_RULE_ID. + CredentialFederation + // CredentialSavedLogin is the login saved by "kernel login", if any. + CredentialSavedLogin +) + +// ActiveCredential reports which credential commands authenticate with. An +// API key comes first, then workload identity federation, then a saved login. +// The first one configured is used even when it then fails: a later one is +// never tried in its place. +func ActiveCredential() Credential { + switch { + case os.Getenv("KERNEL_API_KEY") != "": + return CredentialAPIKey + case os.Getenv(credentials.EnvFederationRuleID) != "": + return CredentialFederation + default: + return CredentialSavedLogin + } +} + // GetAuthenticatedClient returns a Kernel client with appropriate authentication func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error) { - // Try to use API key first if available - apiKey := os.Getenv("KERNEL_API_KEY") - if apiKey != "" { + switch ActiveCredential() { + case CredentialAPIKey: pterm.Debug.Println("Using API key authentication") - authOpts := append(opts, option.WithHeader("Authorization", "Bearer "+apiKey)) + authOpts := append(opts, option.WithHeader("Authorization", "Bearer "+os.Getenv("KERNEL_API_KEY"))) client := kernel.NewClient(authOpts...) return &client, nil - } - - // Workload identity federation comes next. Once it is configured, a - // failure to authenticate with it is final: the saved login is not tried. - if os.Getenv(credentials.EnvFederationRuleID) != "" { + case CredentialFederation: pterm.Debug.Println("Using workload identity federation") federation, err := newFederation() if err != nil { @@ -43,7 +66,6 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error return &client, nil } - // Fallback to OAuth tokens if neither is available tokens, err := LoadTokens() if err == nil { // Check if access token is expired and refresh if needed diff --git a/pkg/auth/federation_test.go b/pkg/auth/federation_test.go index d4efedec..142961a2 100644 --- a/pkg/auth/federation_test.go +++ b/pkg/auth/federation_test.go @@ -1041,3 +1041,24 @@ func TestTokensAreNeverPrinted(t *testing.T) { } } } + +func TestActiveCredentialOrder(t *testing.T) { + for _, tc := range []struct { + name string + apiKey, rule string + want Credential + }{ + {"API key alone", "sk_test", "", CredentialAPIKey}, + {"API key beats a federation rule", "sk_test", "wifr_test", CredentialAPIKey}, + {"federation rule beats a saved login", "", "wifr_test", CredentialFederation}, + {"neither leaves the saved login", "", "", CredentialSavedLogin}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("KERNEL_API_KEY", tc.apiKey) + t.Setenv(credentials.EnvFederationRuleID, tc.rule) + if got := ActiveCredential(); got != tc.want { + t.Fatalf("ActiveCredential() = %v, want %v", got, tc.want) + } + }) + } +} From b359474fa18523a4447a4a5ff17427412071731f Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:37:15 +0000 Subject: [PATCH 5/5] Work out the token cache once and stop resending after a rejected token --- README.md | 2 +- cmd/vaults_federation_test.go | 81 ------------------- pkg/auth/federation.go | 115 ++++++++------------------- pkg/auth/federation_test.go | 143 ++++------------------------------ 4 files changed, 51 insertions(+), 290 deletions(-) delete mode 100644 cmd/vaults_federation_test.go diff --git a/README.md b/README.md index 50b81bf8..a2961020 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ steps: The CLI authenticates with the first of these that is configured: `KERNEL_API_KEY`, then `KERNEL_FEDERATION_RULE_ID`, then the login saved by `kernel login`. When `KERNEL_FEDERATION_RULE_ID` is set and the exchange fails, the command fails. It does not fall back to a saved login. `kernel auth` shows which one is in use. -Each command is a new process, so the access token is cached between commands until 60 seconds before it expires. If the API rejects a cached token, the CLI drops it, exchanges a new one and retries the request once. Vault writes, which are never sent twice, are not retried: the command fails and the next one exchanges a new token. A token is cached only where it can be tied to the workload that obtained it: +Each command is a new process, so the access token is cached between commands until 60 seconds before it expires. If the API rejects a cached token, the command fails, the CLI drops the token, and the next command exchanges a new one. A request is never sent twice. A token is cached only where it can be tied to the workload that obtained it: | Identity token source | Cached | Where | Reused only by | | --- | --- | --- | --- | diff --git a/cmd/vaults_federation_test.go b/cmd/vaults_federation_test.go deleted file mode 100644 index a63751fe..00000000 --- a/cmd/vaults_federation_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package cmd - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "sync" - "testing" - - "github.com/kernel/cli/pkg/auth" - kernel "github.com/kernel/kernel-go-sdk" - "github.com/kernel/kernel-go-sdk/option" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// With workload identity federation, a request the API answers 401 is sent -// again with a new token. Vault writes are the exception: they are sent once. -func TestVaultWritesAreNotReplayedAfterARejectedFederationToken(t *testing.T) { - var mu sync.Mutex - var requests []string - issued := 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - defer mu.Unlock() - w.Header().Set("Content-Type", "application/json") - if r.URL.Path == "/token" { - issued++ - _ = json.NewEncoder(w).Encode(map[string]any{"access_token": fmt.Sprintf("access-token-%d", issued), "token_type": "Bearer", "expires_in": 300}) - return - } - requests = append(requests, r.Method+" "+r.URL.Path) - w.WriteHeader(http.StatusUnauthorized) - _, _ = w.Write([]byte(`{"code":"unauthorized","message":"invalid token"}`)) - })) - defer server.Close() - - tokenFile := filepath.Join(t.TempDir(), "identity-token") - require.NoError(t, os.WriteFile(tokenFile, []byte("identity-token"), 0600)) - for name, value := range map[string]string{ - "KERNEL_API_KEY": "", "KERNEL_BASE_URL": server.URL, "KERNEL_AUTH_BASE_URL": server.URL, - "KERNEL_FEDERATION_RULE_ID": "wifr_vaults", "KERNEL_IDENTITY_TOKEN_SOURCE": "", "KERNEL_IDENTITY_TOKEN": "", - "KERNEL_IDENTITY_TOKEN_FILE": tokenFile, auth.EnvFederationTokenCache: "off", - } { - t.Setenv(name, value) - } - client, err := auth.GetAuthenticatedClient() - require.NoError(t, err) - ctx := context.Background() - - for _, tc := range []struct { - name string - send func(opts ...option.RequestOption) error - }{ - {"with a body", func(opts ...option.RequestOption) error { - _, err := client.Vaults.Upsert(ctx, kernel.VaultUpsertParams{Name: "user"}, opts...) - return err - }}, - {"without a body", func(opts ...option.RequestOption) error { - return client.Vaults.Delete(ctx, "user", opts...) - }}, - } { - t.Run(tc.name, func(t *testing.T) { - sent := func(send func() error) int { - mu.Lock() - requests = nil - mu.Unlock() - require.Error(t, send()) - mu.Lock() - defer mu.Unlock() - return len(requests) - } - assert.Equal(t, 1, sent(func() error { return tc.send(vaultWriteRequestOptions()...) }), "a vault write is sent once") - assert.Equal(t, 2, sent(func() error { return tc.send(option.WithMaxRetries(0)) }), "the same request without the vault options is sent again") - }) - } -} diff --git a/pkg/auth/federation.go b/pkg/auth/federation.go index 97a556b9..be83214e 100644 --- a/pkg/auth/federation.go +++ b/pkg/auth/federation.go @@ -33,43 +33,40 @@ type federation struct { apiURL *url.URL exchange credentials.AccessTokenProvider // tokens holds the token for the life of this process and renews it - // before it expires. + // before it expires. It never runs two exchanges at once. tokens *credentials.TokenCache + // cache is where the token is kept between processes, or nil with + // notCached saying why. It is worked out once, when the process starts. + cache *federationCache + notCached string + // exchanged is the identity token the last exchange sent. + exchanged string mu sync.Mutex rejected string } -// exchangedAssertionKey is the context key of a *string that receives the -// identity token an exchange sends. -type exchangedAssertionKey struct{} - func newFederation() (*federation, error) { source, opts, err := credentials.FederationFromEnv() if err != nil { return nil, err } - identityToken := func(ctx context.Context) (string, error) { - assertion, err := source(ctx) - if sent, _ := ctx.Value(exchangedAssertionKey{}).(*string); sent != nil { - *sent = strings.TrimSpace(assertion) - } - return assertion, err - } apiBaseURL := util.GetBaseURL() apiURL, err := url.Parse(apiBaseURL) if err != nil { return nil, errors.New("KERNEL_BASE_URL is not a valid URL") } - f := &federation{ - ruleID: opts.FederationRuleID, - apiURL: apiURL, - exchange: credentials.NewFederationProvider(credentials.FederationConfig{ - IdentityTokenProvider: identityToken, - FederationRuleID: opts.FederationRuleID, - APIBaseURL: apiBaseURL, - }), - } + f := &federation{ruleID: opts.FederationRuleID, apiURL: apiURL} + f.cache, f.notCached = federationCacheFromEnv(f.ruleID) + f.exchange = credentials.NewFederationProvider(credentials.FederationConfig{ + IdentityTokenProvider: func(ctx context.Context) (string, error) { + assertion, err := source(ctx) + f.exchanged = strings.TrimSpace(assertion) + return assertion, err + }, + FederationRuleID: opts.FederationRuleID, + APIBaseURL: apiBaseURL, + }) f.tokens = credentials.NewTokenCache(f.token) return f, nil } @@ -78,11 +75,10 @@ func newFederation() (*federation, error) { // token for a new one and caches it. force is set after the API rejected the // previous token, whose cache entry has been removed by then. func (f *federation) token(ctx context.Context, force bool) (*credentials.Token, error) { - cache, reason := federationCacheFromEnv(f.ruleID) - if cache == nil { - pterm.Debug.Printfln("Workload identity token is not cached: %s", reason) + if f.cache == nil { + pterm.Debug.Printfln("Workload identity token is not cached: %s", f.notCached) } else if !force { - if entry := cache.load(); entry != nil { + if entry := f.cache.load(); entry != nil { pterm.Debug.Printfln("Using the cached workload identity token (valid for %s)", time.Until(entry.ExpiresAt).Round(time.Second)) // The expiry is brought forward by the margin, so this process // comes back for another token before the cached one has less @@ -90,19 +86,18 @@ func (f *federation) token(ctx context.Context, force bool) (*credentials.Token, return &credentials.Token{AccessToken: entry.AccessToken, ExpiresAt: entry.ExpiresAt.Add(-federationCacheMargin)}, nil } } - var assertion string - token, err := f.exchange(context.WithValue(ctx, exchangedAssertionKey{}, &assertion), force) + token, err := f.exchange(ctx, force) if err != nil { return nil, err } pterm.Debug.Printfln("Exchanged an identity token for a Kernel access token (valid for %s)", time.Until(token.ExpiresAt).Round(time.Second)) - if cache != nil { - if cache.fromFile { - // The file may have changed since the cache was looked up. The - // token belongs to the identity that was exchanged for it. - cache.binding = federationBinding(assertion) + if f.cache != nil { + if f.cache.fromFile { + // The file may have changed since the process started. The token + // belongs to the identity that was exchanged for it. + f.cache.binding = federationBinding(f.exchanged) } - if err := cache.save(token); err != nil { + if err := f.cache.save(token); err != nil { pterm.Debug.Printfln("Could not cache the workload identity token: %v", err) } } @@ -119,14 +114,14 @@ func (f *federation) reject(accessToken string) { } f.rejected = accessToken f.tokens.Invalidate() - if cache, _ := federationCacheFromEnv(f.ruleID); cache != nil { - cache.forget(accessToken) + if f.cache != nil { + f.cache.forget(accessToken) } } // middleware authenticates each API request with the current access token. -// When the API answers 401 it drops that token, exchanges a new one and sends -// the request once more, unless the request must not be sent twice. +// When the API answers 401 it drops that token, so the next command exchanges +// a new one. The request is not sent again. func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { // The token is for the API only. if !sameOrigin(req.URL, f.apiURL) { @@ -143,37 +138,10 @@ func (f *federation) middleware(req *http.Request, next option.MiddlewareNext) ( resp, err := next(req) // A later middleware can send the request to a browser VM instead. A 401 // from there says nothing about this token. - if err != nil || resp.StatusCode != http.StatusUnauthorized || !sameOrigin(req.URL, f.apiURL) { - return resp, err - } - - f.reject(token.AccessToken) - if !replayable(req) { - return resp, nil - } - if req.GetBody != nil { - body, err := req.GetBody() - if err != nil { - return resp, nil - } - req.Body = body - } - _ = resp.Body.Close() - token, err = f.tokens.Token(req.Context()) - if err != nil { - return unauthenticated(req, err) - } - req.Header.Set("Authorization", "Bearer "+token.AccessToken) - resp, err = next(req) - // The request is sent again only this once, whatever comes back. - if err != nil { - return unauthenticated(req, err) - } - resp.Header.Set("X-Should-Retry", "false") - if resp.StatusCode == http.StatusUnauthorized && sameOrigin(req.URL, f.apiURL) { + if err == nil && resp.StatusCode == http.StatusUnauthorized && sameOrigin(req.URL, f.apiURL) { f.reject(token.AccessToken) } - return resp, nil + return resp, err } // unauthenticated fails a request with err. The response tells the client @@ -187,21 +155,6 @@ func unauthenticated(req *http.Request, err error) (*http.Response, error) { }, err } -// replayable reports whether req may be sent a second time, by the rule -// net/http applies before it replays a request on a new connection: the body -// can be read again, and the method is safe or the request carries an -// idempotency key. Vault writes take both away so that they are sent once. -func replayable(req *http.Request) bool { - if req.Body != nil && req.Body != http.NoBody && req.GetBody == nil { - return false - } - switch req.Method { - case "", http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace: - return true - } - return req.Header.Get("Idempotency-Key") != "" || req.Header.Get("X-Idempotency-Key") != "" -} - func sameOrigin(a, b *url.URL) bool { return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host) } diff --git a/pkg/auth/federation_test.go b/pkg/auth/federation_test.go index 142961a2..ead216cc 100644 --- a/pkg/auth/federation_test.go +++ b/pkg/auth/federation_test.go @@ -680,7 +680,7 @@ func TestCacheTurnedOffIgnoresAnExistingEntry(t *testing.T) { } } -func TestRejectedCachedTokenIsDroppedAndTheRequestRetriedOnce(t *testing.T) { +func TestRejectedCachedTokenIsDroppedAndTheRequestIsNotSentAgain(t *testing.T) { s := federationFixture(t) mustCallAPI(t, newProcess(t)) @@ -691,142 +691,30 @@ func TestRejectedCachedTokenIsDroppedAndTheRequestRetriedOnce(t *testing.T) { }) client := newProcess(t) - var out map[string]any - if err := client.Post(context.Background(), "things", map[string]string{"name": "thing"}, &out); err != nil { - t.Fatalf("API request error = %v, want the retry to succeed", err) - } - want := []string{`Bearer access-token-1 {"name":"thing"}`, `Bearer access-token-2 {"name":"thing"}`} - if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("API saw %q, want %q", got, want) - } - if got := s.exchangeCount(); got != 2 { - t.Fatalf("token exchanges = %d, want 2", got) - } - - // The replacement is what later requests and processes use. - mustCallAPI(t, client) - mustCallAPI(t, newProcess(t)) - if got := s.exchangeCount(); got != 2 { - t.Fatalf("token exchanges = %d, want the replacement cached", got) - } - if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { - t.Fatalf("API saw %q last, want the replacement", got[len(got)-1]) - } -} - -func TestSecondRejectionFailsTheCommand(t *testing.T) { - s := federationFixture(t) - mustCallAPI(t, newProcess(t)) - s.change(func() { - s.apiStatus = func(string) int { return http.StatusUnauthorized } - s.apiRequests = nil - }) - - err := callAPI(newProcess(t)) + err := client.Post(context.Background(), "things", map[string]string{"name": "thing"}, nil) if err == nil || !strings.Contains(err.Error(), "401") { t.Fatalf("API request error = %v, want the 401", err) } - want := []string{"Bearer access-token-1", "Bearer access-token-2"} + want := []string{`Bearer access-token-1 {"name":"thing"}`} if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("API saw %q, want %q: one retry, with a new token", got, want) + t.Fatalf("API saw %q, want the request sent once: %q", got, want) } - if got := s.exchangeCount(); got != 2 { - t.Fatalf("token exchanges = %d, want 2", got) + if got := s.exchangeCount(); got != 1 { + t.Fatalf("token exchanges = %d, want none for the rejected request", got) } cache, _ := federationCacheFromEnv("wifr_test") - if cache.load() != nil { - t.Fatal("the replacement the API rejected is still cached") + if entry := cache.load(); entry != nil { + t.Fatal("the rejected token is still cached") } -} -// The request is sent a second time only once: the SDK's own retries, which -// are on by default, must not send it a third time. -func TestRetryAfterRejectionIsFinal(t *testing.T) { - s := federationFixture(t) + // The next command exchanges a new token, and later ones reuse it. mustCallAPI(t, newProcess(t)) - s.change(func() { - s.apiStatus = func(accessToken string) int { - if accessToken == "access-token-1" { - return http.StatusUnauthorized - } - return http.StatusServiceUnavailable - } - s.apiRequests = nil - }) - - client, err := GetAuthenticatedClient() - if err != nil { - t.Fatal(err) - } - if err := callAPI(client); err == nil || !strings.Contains(err.Error(), "503") { - t.Fatalf("API request error = %v, want the 503", err) - } - want := []string{"Bearer access-token-1", "Bearer access-token-2"} - if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("API saw %q, want %q", got, want) - } -} - -// Vault writes take away what would let a request be sent twice: the -// replayable body, and for a request without a body the idempotency key. A -// rejected token is dropped and the 401 returned. -func TestRejectionOfARequestThatMustNotBeReplayedIsNotRetried(t *testing.T) { - noReplay := option.WithMiddleware(func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { - req.GetBody = nil - if req.Body == nil || req.Body == http.NoBody { - req.Header.Del("Idempotency-Key") - req.Header.Del("X-Idempotency-Key") - } - return next(req) - }) - for _, tc := range []struct { - name string - send func(client *kernel.Client) error - }{ - {"write with a body", func(client *kernel.Client) error { - return client.Post(context.Background(), "things", map[string]string{"name": "thing"}, nil, noReplay) - }}, - {"write without a body", func(client *kernel.Client) error { - return client.Delete(context.Background(), "things/thing", nil, nil, noReplay) - }}, - } { - t.Run(tc.name, func(t *testing.T) { - s := federationFixture(t) - mustCallAPI(t, newProcess(t)) - s.change(func() { - s.apiStatus = rejectOnly("access-token-1") - s.apiRequests = nil - }) - - if err := tc.send(newProcess(t)); err == nil || !strings.Contains(err.Error(), "401") { - t.Fatalf("API request error = %v, want the 401", err) - } - if got := s.seenByAPI(); len(got) != 1 { - t.Fatalf("API saw %q, want the request sent once", got) - } - mustCallAPI(t, newProcess(t)) - if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { - t.Fatalf("API saw %q last, want the next command to use a new token", got[len(got)-1]) - } - }) - } -} - -// A write that keeps its idempotency key is sent again after a rejection, -// with or without a body. -func TestRejectedWriteWithoutABodyIsRetried(t *testing.T) { - s := federationFixture(t) mustCallAPI(t, newProcess(t)) - s.change(func() { - s.apiStatus = rejectOnly("access-token-1") - s.apiRequests = nil - }) - if err := newProcess(t).Delete(context.Background(), "things/thing", nil, nil); err != nil { - t.Fatalf("API request error = %v, want the retry to succeed", err) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want one replacement", got) } - want := []string{"Bearer access-token-1", "Bearer access-token-2"} - if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { - t.Fatalf("API saw %q, want %q", got, want) + if got := s.seenByAPI(); got[len(got)-1] != "Bearer access-token-2" { + t.Fatalf("API saw %q last, want the replacement", got[len(got)-1]) } } @@ -863,8 +751,8 @@ func TestRejectedTokenIsDroppedWhenTheExchangeFails(t *testing.T) { }) client := newProcess(t) - if err := callAPI(client); err == nil || !strings.Contains(err.Error(), "invalid_grant") { - t.Fatalf("API request error = %v, want the refused exchange", err) + if err := callAPI(client); err == nil || !strings.Contains(err.Error(), "401") { + t.Fatalf("API request error = %v, want the 401", err) } cache, _ := federationCacheFromEnv("wifr_test") if entry := cache.load(); entry != nil { @@ -1020,6 +908,7 @@ func TestTokensAreNeverPrinted(t *testing.T) { mustCallAPI(t, newProcess(t)) mustCallAPI(t, newProcess(t)) s.change(func() { s.apiStatus = rejectOnly("access-token-1") }) + _ = callAPI(newProcess(t)) mustCallAPI(t, newProcess(t)) s.change(func() { s.apiStatus = func(string) int { return http.StatusUnauthorized }