Skip to content
Open
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
25 changes: 20 additions & 5 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,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 @@ -170,3 +166,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)
}
}
}
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 @@ -342,8 +349,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 @@ -355,6 +364,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 @@ -363,11 +376,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
88 changes: 88 additions & 0 deletions pkg/auth/oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -172,6 +173,9 @@ func TestRefreshLegacyTokensRemainOrganizationWide(t *testing.T) {
if tokens.ProjectID != "" {
t.Fatalf("ProjectID = %q, want empty", tokens.ProjectID)
}
if tokens.ScopeRecorded {
t.Fatal("ScopeRecorded = true for a response that does not state the scope")
}
}

func TestLegacyTokenRefreshConfigUsesProdDefaults(t *testing.T) {
Expand All @@ -187,3 +191,87 @@ func TestLegacyTokenRefreshConfigUsesProdDefaults(t *testing.T) {
t.Fatalf("tokenOAuthClientID = %q, want %q", got, want)
}
}

func TestTokensKeepNativeProjects(t *testing.T) {
refreshed := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
body := map[string]interface{}{
"access_token": "access-token",
"refresh_token": "refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
"org_id": "org_1",
"access_scope": "organization",
}
if !refreshed {
body["projects"] = []string{"proj_a", "proj_b"}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(body)
}))
defer server.Close()

config := &OAuthConfig{
Config: &oauth2.Config{
ClientID: "client-id",
RedirectURL: "http://localhost/callback",
Endpoint: oauth2.Endpoint{TokenURL: server.URL, AuthStyle: oauth2.AuthStyleInParams},
},
Verifier: "verifier",
AuthBaseURL: server.URL,
OAuthClientID: "client-id",
}
tokens, err := config.exchangeCodeForTokens(context.Background(), "code", "org_1", "", "")
if err != nil {
t.Fatalf("exchangeCodeForTokens() error = %v", err)
}
if got, want := strings.Join(tokens.Projects, ","), "proj_a,proj_b"; got != want {
t.Fatalf("Projects = %q, want %q", got, want)
}
if !tokens.ScopeRecorded {
t.Fatal("ScopeRecorded = false after login")
}

// A refresh response without the field keeps the grant's projects.
refreshed = true
tokens, err = RefreshTokens(context.Background(), tokens)
if err != nil {
t.Fatalf("RefreshTokens() error = %v", err)
}
if got, want := strings.Join(tokens.Projects, ","), "proj_a,proj_b"; got != want {
t.Fatalf("Projects after refresh = %q, want %q", got, want)
}
if !tokens.ScopeRecorded {
t.Fatal("ScopeRecorded = false after refresh")
}
}

func TestRefreshRecordsScopeForOlderCredentials(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"access_token": "access-new",
"refresh_token": "refresh-new",
"token_type": "Bearer",
"expires_in": 600,
"access_scope": "organization",
"projects": []string{"proj_a"},
})
}))
defer server.Close()

// Saved by a CLI that did not record projects or ScopeRecorded.
tokens, err := RefreshTokens(context.Background(), &TokenStorage{
RefreshToken: "refresh-old",
OrgID: "org_1",
AccessScope: "organization",
AuthBaseURL: server.URL,
OAuthClientID: "client-id",
})
if err != nil {
t.Fatalf("RefreshTokens() error = %v", err)
}
if !tokens.ScopeRecorded || strings.Join(tokens.Projects, ",") != "proj_a" {
t.Fatalf("after refresh: ScopeRecorded = %v, Projects = %v", tokens.ScopeRecorded, tokens.Projects)
}
}
69 changes: 56 additions & 13 deletions pkg/auth/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,47 +25,90 @@ type TokenStorage struct {
ProjectID string `json:"project_id,omitempty"`
AuthBaseURL string `json:"auth_base_url,omitempty"`
OAuthClientID string `json:"oauth_client_id,omitempty"`
Projects []string `json:"projects,omitempty"` // projects a native grant is limited to; empty means all
// ScopeRecorded is set by CLI versions that record Projects. Credentials
// saved without it may be limited to projects the CLI does not know about.
ScopeRecorded bool `json:"scope_recorded,omitempty"`
// SavedAt tells which of the keyring and the credentials file is current
// when both hold credentials.
SavedAt time.Time `json:"saved_at,omitzero"`
}

// IsExpired checks if the access token is expired (with 5 minute buffer)
func (t *TokenStorage) IsExpired() bool {
return time.Now().Add(5 * time.Minute).After(t.ExpiresAt)
}

// SaveTokens stores authentication tokens securely in the OS keychain
// setKeyring is keyring.Set, replaceable in tests that need it to fail.
var setKeyring = keyring.Set

// SaveTokens stores authentication tokens in the OS keychain, or in the
// credentials file when the keychain refuses them (for example when they are
// too large). Whichever store is written becomes the one LoadTokens reads.
func SaveTokens(tokens *TokenStorage) error {
data, err := json.Marshal(tokens)
stamped := *tokens
stamped.SavedAt = time.Now().UTC()
data, err := json.Marshal(stamped)
if err != nil {
return fmt.Errorf("failed to marshal tokens: %w", err)
}

// Try to store in OS keychain
err = keyring.Set(KeyringService, KeyringUser, string(data))
if err != nil {
// Fallback to file storage with restrictive permissions
return saveTokensToFile(data)
if err := setKeyring(KeyringService, KeyringUser, string(data)); err == nil {
_ = deleteTokensFile()
return nil
}

// Fallback to file storage with restrictive permissions
if err := saveTokensToFile(data); err != nil {
return err
}
// The keychain may still hold older credentials. LoadTokens prefers the
// newer copy even if this delete fails.
_ = keyring.Delete(KeyringService, KeyringUser)
return nil
}

// LoadTokens retrieves authentication tokens from secure storage
// LoadTokens retrieves authentication tokens from the keychain or the
// credentials file. When both hold credentials, the newer copy wins.
func LoadTokens() (*TokenStorage, error) {
// Try to load from OS keychain first
fromKeyring, keyringErr := loadTokensFromKeyring()
fromFile, fileErr := loadTokensFromFile()
switch {
case keyringErr == nil && fileErr == nil:
if newer(fromFile, fromKeyring) {
return fromFile, nil
}
return fromKeyring, nil
case keyringErr == nil:
return fromKeyring, nil
case fileErr == nil:
return fromFile, nil
default:
return nil, fileErr
}
}

func loadTokensFromKeyring() (*TokenStorage, error) {
data, err := keyring.Get(KeyringService, KeyringUser)
if err != nil {
// Fallback to file storage
return loadTokensFromFile()
return nil, err
}

var tokens TokenStorage
if err := json.Unmarshal([]byte(data), &tokens); err != nil {
return nil, fmt.Errorf("failed to unmarshal tokens from keychain: %w", err)
}

return &tokens, nil
}

// newer reports whether a was saved after b. Credentials saved before SavedAt
// existed compare by expiry.
func newer(a, b *TokenStorage) bool {
if !a.SavedAt.Equal(b.SavedAt) {
return a.SavedAt.After(b.SavedAt)
}
return a.ExpiresAt.After(b.ExpiresAt)
}

// DeleteTokens removes stored authentication tokens
func DeleteTokens() error {
// Try to delete from keychain
Expand Down
Loading
Loading