diff --git a/cmd/auth.go b/cmd/auth.go index 0b462e04..a01bff55 100644 --- a/cmd/auth.go +++ b/cmd/auth.go @@ -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 { @@ -170,3 +166,18 @@ 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. +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, ", ") + default: + return "organization-wide" + } +} diff --git a/cmd/auth_scope_test.go b/cmd/auth_scope_test.go new file mode 100644 index 00000000..e988df8a --- /dev/null +++ b/cmd/auth_scope_test.go @@ -0,0 +1,24 @@ +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"}, "organization-wide"}, + } { + if got := accessScopeLabel(&tc.tokens); got != tc.want { + t.Errorf("%s: accessScopeLabel() = %q, want %q", tc.name, got, tc.want) + } + } +} diff --git a/pkg/auth/oauth.go b/pkg/auth/oauth.go index ccf4e2f6..f78a4b31 100644 --- a/pkg/auth/oauth.go +++ b/pkg/auth/oauth.go @@ -269,6 +269,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, @@ -277,6 +278,7 @@ func (oc *OAuthConfig) exchangeCodeForTokens(ctx context.Context, code, orgID, a OrgID: orgID, AccessScope: accessScope, ProjectID: projectID, + Projects: projects, AuthBaseURL: oc.AuthBaseURL, OAuthClientID: oc.OAuthClientID, }, nil @@ -355,6 +357,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, @@ -363,11 +369,27 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er OrgID: orgID, AccessScope: accessScope, ProjectID: projectID, + Projects: projects, 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) diff --git a/pkg/auth/oauth_test.go b/pkg/auth/oauth_test.go index 820a314e..73df5f46 100644 --- a/pkg/auth/oauth_test.go +++ b/pkg/auth/oauth_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -187,3 +188,51 @@ 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) + } + + // 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) + } +} diff --git a/pkg/auth/storage.go b/pkg/auth/storage.go index 0a79fc8a..1bca5630 100644 --- a/pkg/auth/storage.go +++ b/pkg/auth/storage.go @@ -25,6 +25,7 @@ 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 } // IsExpired checks if the access token is expired (with 5 minute buffer)