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
33 changes: 21 additions & 12 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/kernel/cli/pkg/util"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"github.com/zalando/go-keyring"
)

// JWTClaims represents the claims in a JWT token
Expand Down Expand Up @@ -103,11 +102,7 @@ func runAuth(cmd *cobra.Command, args []string) error {
pterm.Info.Printf("API URL: %s\n", util.GetBaseURL())
pterm.Info.Printf("Auth URL: %s\n", tokenAuthBaseURLForDisplay(tokens))
pterm.Info.Printf("OAuth client ID: %s\n", maskClientID(tokenOAuthClientIDForDisplay(tokens)))
if tokens.AccessScope == "project" && tokens.ProjectID != "" {
pterm.Info.Printf("Access scope: project %s\n", tokens.ProjectID)
} else {
pterm.Info.Println("Access scope: organization-wide")
}
pterm.Info.Printf("Access scope: %s\n", accessScopeLabel(tokens))

// Extract info from JWT token
if claims, err := parseJWT(tokens.AccessToken); err == nil && claims != nil {
Expand Down Expand Up @@ -135,12 +130,7 @@ func runAuth(cmd *cobra.Command, args []string) error {
}
}

// Storage method
if _, err := keyring.Get(auth.KeyringService, auth.KeyringUser); err == nil {
logger.Debug("Storage method", logger.Args("method", "OS Keychain"))
} else {
logger.Debug("Storage method", logger.Args("method", "Local file (~/.config/kernel/credentials)"))
}
logger.Debug("Storage method", logger.Args("method", tokens.Source))

return nil
}
Expand All @@ -165,3 +155,22 @@ func maskClientID(clientID string) string {
}
return clientID[:4] + "..." + clientID[len(clientID)-4:]
}

// accessScopeLabel describes where the stored credentials may act: one
// project, the projects a native grant is limited to, or the organization.
// Credentials saved by older CLI versions did not record the projects, so
// their scope is unknown until they are refreshed or replaced.
func accessScopeLabel(tokens *auth.TokenStorage) string {
switch {
case tokens.AccessScope == "project" && tokens.ProjectID != "":
return "project " + tokens.ProjectID
case len(tokens.Projects) == 1:
return "project " + tokens.Projects[0]
case len(tokens.Projects) > 1:
return "projects " + strings.Join(tokens.Projects, ", ")
case !tokens.ScopeRecorded:
return "unknown (saved by an older CLI version; run 'kernel login --force' to record it)"
default:
return "organization-wide"
}
}
25 changes: 25 additions & 0 deletions cmd/auth_scope_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cmd

import (
"testing"

"github.com/kernel/cli/pkg/auth"
)

func TestAccessScopeLabel(t *testing.T) {
for _, tc := range []struct {
name string
tokens auth.TokenStorage
want string
}{
{"legacy project scope", auth.TokenStorage{AccessScope: "project", ProjectID: "proj_1"}, "project proj_1"},
{"native grant for one project", auth.TokenStorage{AccessScope: "organization", Projects: []string{"proj_a"}}, "project proj_a"},
{"native grant for several projects", auth.TokenStorage{AccessScope: "organization", Projects: []string{"proj_a", "proj_b"}}, "projects proj_a, proj_b"},
{"every project", auth.TokenStorage{AccessScope: "organization", ScopeRecorded: true}, "organization-wide"},
{"saved by an older CLI", auth.TokenStorage{AccessScope: "organization"}, "unknown (saved by an older CLI version; run 'kernel login --force' to record it)"},
} {
if got := accessScopeLabel(&tc.tokens); got != tc.want {
t.Errorf("%s: accessScopeLabel() = %q, want %q", tc.name, got, tc.want)
}
}
}
3 changes: 3 additions & 0 deletions cmd/project_scope_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ func TestDeployGithubProjectScope(t *testing.T) {
cmd := projectTestCommand(t, server.URL, tt.flag)
if tt.oauth {
t.Setenv("KERNEL_API_KEY", "")
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
keyring.MockInit()
t.Cleanup(keyring.MockInit)
require.NoError(t, auth.SaveTokens(&auth.TokenStorage{
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
golang.org/x/crypto v0.52.0
golang.org/x/oauth2 v0.30.0
golang.org/x/sync v0.20.0
golang.org/x/sys v0.45.0
golang.org/x/term v0.43.0
gopkg.in/yaml.v3 v3.0.1
)
Expand Down Expand Up @@ -59,6 +60,5 @@ require (
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
)
43 changes: 32 additions & 11 deletions pkg/auth/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,13 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error
if err == nil {
// Check if access token is expired and refresh if needed
if tokens.IsExpired() && tokens.RefreshToken != "" {
pterm.Debug.Println("Access token expired, attempting refresh...")

refreshedTokens, refreshErr := RefreshTokens(context.Background(), tokens)
refreshed, refreshErr := refreshStoredTokens(context.Background())
if refreshErr != nil {
pterm.Warning.Printf("Failed to refresh tokens: %v\n", refreshErr)
pterm.Info.Println("Please run 'kernel login' to re-authenticate")
return nil, fmt.Errorf("expired credentials, please re-authenticate: %w", refreshErr)
}

// Save refreshed tokens
if saveErr := SaveTokens(refreshedTokens); saveErr != nil {
pterm.Warning.Printf("Failed to save refreshed tokens: %v\n", saveErr)
}

tokens = refreshedTokens
pterm.Debug.Println("Successfully refreshed access token")
tokens = refreshed
}

// Use JWT token for authentication via Authorization header
Expand All @@ -54,3 +45,33 @@ func GetAuthenticatedClient(opts ...option.RequestOption) (*kernel.Client, error
// No authentication available
return nil, fmt.Errorf("no authentication available. Please run 'kernel login' or set KERNEL_API_KEY environment variable")
}

// refreshStoredTokens refreshes the stored credentials while holding the
// credentials lock. It re-reads them first, so when another CLI process has
// already refreshed, its tokens are used and the consumed refresh token is
// never presented again.
func refreshStoredTokens(ctx context.Context) (*TokenStorage, error) {
var tokens *TokenStorage
err := withCredentialsLock(func() error {
current, err := loadTokens()
if err != nil {
return err
}
if !current.IsExpired() || current.RefreshToken == "" {
tokens = current
return nil
}
pterm.Debug.Println("Access token expired, attempting refresh...")
refreshed, err := RefreshTokens(ctx, current)
if err != nil {
return err
}
if err := saveTokens(refreshed); err != nil {
pterm.Warning.Printf("Failed to save refreshed tokens: %v\n", err)
}
pterm.Debug.Println("Successfully refreshed access token")
tokens = refreshed
return nil
})
return tokens, err
}
21 changes: 21 additions & 0 deletions pkg/auth/lock_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//go:build !windows

package auth

import (
"errors"
"os"
"syscall"
)

func tryLockFile(f *os.File) (bool, error) {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if errors.Is(err, syscall.EWOULDBLOCK) {
return false, nil
}
return err == nil, err
}

func unlockFile(f *os.File) error {
return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
}
24 changes: 24 additions & 0 deletions pkg/auth/lock_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//go:build windows

package auth

import (
"errors"
"os"

"golang.org/x/sys/windows"
)

func tryLockFile(f *os.File) (bool, error) {
var overlapped windows.Overlapped
err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped)
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
return false, nil
}
return err == nil, err
}

func unlockFile(f *os.File) error {
var overlapped windows.Overlapped
return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, &overlapped)
}
30 changes: 30 additions & 0 deletions pkg/auth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,12 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a
if value, ok := token.Extra("org_id").(string); ok && value != "" {
orgID = value
}
// A response that states the access scope also lists the projects a
// grant is limited to, so its scope is recorded.
scopeRecorded := false
if value, ok := token.Extra("access_scope").(string); ok && value != "" {
accessScope = value
scopeRecorded = true
}
if value, ok := token.Extra("project_id").(string); ok {
projectID = value
Expand All @@ -269,6 +273,7 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a
if accessScope == "organization" {
projectID = ""
}
projects, _ := projectsFromResponse(token.Extra("projects"))

return &TokenStorage{
AccessToken: token.AccessToken,
Expand All @@ -277,6 +282,8 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a
OrgID: orgID,
AccessScope: accessScope,
ProjectID: projectID,
Projects: projects,
ScopeRecorded: scopeRecorded,
AuthBaseURL: oc.AuthBaseURL,
OAuthClientID: oc.OAuthClientID,
}, nil
Expand Down Expand Up @@ -341,8 +348,10 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er
orgID = value
}
accessScope := tokens.AccessScope
scopeRecorded := tokens.ScopeRecorded
if value, ok := tokenResponse["access_scope"].(string); ok && value != "" {
accessScope = value
scopeRecorded = true
}
if accessScope == "" {
accessScope = "organization"
Expand All @@ -354,6 +363,10 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er
if accessScope == "organization" {
projectID = ""
}
projects := tokens.Projects
if value, ok := projectsFromResponse(tokenResponse["projects"]); ok {
projects = value
}

return &TokenStorage{
AccessToken: newToken.AccessToken,
Expand All @@ -362,11 +375,28 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er
OrgID: orgID,
AccessScope: accessScope,
ProjectID: projectID,
Projects: projects,
ScopeRecorded: scopeRecorded,
AuthBaseURL: tokenAuthBaseURL(tokens),
OAuthClientID: tokenOAuthClientID(tokens),
}, nil
}

// projectsFromResponse reads the projects a token response limits the grant
// to. ok reports whether the response carried the field at all.
func projectsFromResponse(value interface{}) (projects []string, ok bool) {
items, ok := value.([]interface{})
if !ok {
return nil, false
}
for _, item := range items {
if id, isString := item.(string); isString && id != "" {
projects = append(projects, id)
}
}
return projects, true
}

// generateCodeVerifier generates a cryptographically secure random string for PKCE
func generateCodeVerifier() (string, error) {
bytes := make([]byte, 32)
Expand Down
Loading
Loading