Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,42 @@ export KERNEL_API_KEY=<YOUR_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
Expand Down Expand Up @@ -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

Expand Down
48 changes: 34 additions & 14 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.`,
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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
Expand Down
98 changes: 98 additions & 0 deletions cmd/auth_status_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}
13 changes: 13 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
52 changes: 47 additions & 5 deletions pkg/auth/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Comment thread
rgarcia marked this conversation as resolved.
Resolved
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
Expand Down
Loading
Loading