diff --git a/README.md b/README.md index 96bfd12c..a2961020 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 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 | +| --- | --- | --- | --- | +| `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..891a441a 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,24 @@ 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 + 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 { + 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 + case auth.CredentialFederation: + printFederationStatus(auth.DescribeFederation()) + 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 +138,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..293a91ab 100644 --- a/pkg/auth/client.go +++ b/pkg/auth/client.go @@ -7,23 +7,65 @@ 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" ) +// 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 + case CredentialFederation: + pterm.Debug.Println("Using workload identity federation") + federation, err := newFederation() + if err != nil { + return nil, err + } + if _, err := federation.tokens.Token(context.Background()); err != nil { + return nil, err + } + authOpts := append(opts, + option.WithHeader("Authorization", federationPlaceholder), + option.WithMiddleware(federation.middleware), + ) client := kernel.NewClient(authOpts...) return &client, nil } - // Fallback to OAuth tokens if no API key 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..be83214e --- /dev/null +++ b/pkg/auth/federation.go @@ -0,0 +1,193 @@ +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" +) + +// 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). +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. 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 +} + +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} + 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 +} + +// 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) { + if f.cache == nil { + pterm.Debug.Printfln("Workload identity token is not cached: %s", f.notCached) + } else if !force { + 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 + // than the margin left. + return &credentials.Token{AccessToken: entry.AccessToken, ExpiresAt: entry.ExpiresAt.Add(-federationCacheMargin)}, 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 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 := f.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 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, 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) { + if req.Header.Get("Authorization") == federationPlaceholder { + req.Header.Del("Authorization") + } + 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) { + f.reject(token.AccessToken) + } + return resp, err +} + +// 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", + 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..f8c0e614 --- /dev/null +++ b/pkg/auth/federation_cache.go @@ -0,0 +1,261 @@ +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 + // 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 +} + +// 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") + } + fileToken := "" + 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 + } + cache.fromFile = true + 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 = 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)), + ) +} + +// 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. 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 { + _ = 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..ead216cc --- /dev/null +++ b/pkg/auth/federation_test.go @@ -0,0 +1,953 @@ +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 + // 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. +func (s *federationStandIns) change(fn func()) { + s.mu.Lock() + defer s.mu.Unlock() + 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() + 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, apiStatus: func(string) int { return http.StatusOK }} + + 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")) + 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", + "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") + w.WriteHeader(s.apiStatus(strings.TrimPrefix(authorization, "Bearer "))) + _, _ = 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) + } + }) + } +} + +// 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) { + 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 TestRejectedCachedTokenIsDroppedAndTheRequestIsNotSentAgain(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.apiStatus = rejectOnly("access-token-1") + s.apiRequests = nil + }) + + client := 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 {"name":"thing"}`} + if got := s.seenByAPI(); fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("API saw %q, want the request sent once: %q", got, want) + } + if got := s.exchangeCount(); got != 1 { + t.Fatalf("token exchanges = %d, want none for the rejected request", got) + } + cache, _ := federationCacheFromEnv("wifr_test") + if entry := cache.load(); entry != nil { + t.Fatal("the rejected token is still cached") + } + + // The next command exchanges a new token, and later ones reuse it. + mustCallAPI(t, newProcess(t)) + mustCallAPI(t, newProcess(t)) + if got := s.exchangeCount(); got != 2 { + t.Fatalf("token exchanges = %d, want one replacement", 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 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.apiStatus = func(string) int { return http.StatusUnauthorized } + s.refuseExchange = true + }) + + client := newProcess(t) + 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 { + 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.apiStatus = rejectOnly("access-token-1") }) + _ = callAPI(newProcess(t)) + mustCallAPI(t, newProcess(t)) + s.change(func() { + s.apiStatus = func(string) int { return http.StatusUnauthorized } + 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()) + } + } +} + +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) + } + }) + } +}