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
21 changes: 16 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,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"
}
}
24 changes: 24 additions & 0 deletions cmd/auth_scope_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
22 changes: 22 additions & 0 deletions pkg/auth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand Down
49 changes: 49 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 @@ -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)
}
}
1 change: 1 addition & 0 deletions pkg/auth/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading