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
7 changes: 1 addition & 6 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
// JWTClaims represents the claims in a JWT token
type JWTClaims struct {
Sub string `json:"sub"` // User ID
Email string `json:"email"` // User email
Exp int64 `json:"exp"` // Expiration time
Iss string `json:"iss"` // Issuer
OrgID string `json:"org_id"` // Organization ID
Expand Down Expand Up @@ -53,10 +52,6 @@ func parseJWT(tokenString string) (*JWTClaims, error) {
jwtClaims.Sub = sub
}

if email, ok := claims["email"].(string); ok {
jwtClaims.Email = email
}

if exp, ok := claims["exp"].(float64); ok {
jwtClaims.Exp = int64(exp)
}
Expand Down Expand Up @@ -117,7 +112,7 @@ func runAuth(cmd *cobra.Command, args []string) error {
// Extract info from JWT token
if claims, err := parseJWT(tokens.AccessToken); err == nil && claims != nil {
if claims.Sub != "" {
logger.Debug("User details", logger.Args("email", claims.Email, "user_id", claims.Sub, "org_id", tokens.OrgID))
logger.Debug("User details", logger.Args("user_id", claims.Sub, "org_id", tokens.OrgID))
}
}

Expand Down
21 changes: 10 additions & 11 deletions pkg/auth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,6 @@ const (
DefaultClientID = "hmFrJn9hKDV2N02M"
RedirectURI = "http://localhost"

// OAuth scopes - openid for the MCP server flow
DefaultScope = "openid email"

// tokenExchangeTimeout bounds the token/refresh HTTP calls so a stalled auth
// server surfaces as an error instead of hanging the CLI indefinitely.
tokenExchangeTimeout = 30 * time.Second
Expand Down Expand Up @@ -143,7 +140,6 @@ func NewOAuthConfig() (*OAuthConfig, error) {
config := &oauth2.Config{
ClientID: clientID,
RedirectURL: redirectURI,
Scopes: strings.Split(DefaultScope, " "),
Endpoint: oauth2.Endpoint{
AuthURL: authorizeURL(authBaseURL),
TokenURL: tokenURL(authBaseURL),
Expand All @@ -160,6 +156,15 @@ func NewOAuthConfig() (*OAuthConfig, error) {
}, nil
}

// authorizationURL returns the authorization request the login opens in the
// browser, with its PKCE challenge.
func (oc *OAuthConfig) authorizationURL() string {
return oc.Config.AuthCodeURL(oc.State,
oauth2.SetAuthURLParam("code_challenge", generateCodeChallenge(oc.Verifier)),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
}

// StartOAuthFlow initiates the OAuth flow with browser redirect
func (oc *OAuthConfig) StartOAuthFlow(ctx context.Context) (*TokenStorage, error) {
// Find an available port and get a listener to prevent race conditions
Expand All @@ -172,12 +177,7 @@ func (oc *OAuthConfig) StartOAuthFlow(ctx context.Context) (*TokenStorage, error
// Update the config with the actual port
oc.Config.RedirectURL = fmt.Sprintf("%s:%d/callback", RedirectURI, port)

// Generate authorization URL with PKCE
challenge := generateCodeChallenge(oc.Verifier)
authURL := oc.Config.AuthCodeURL(oc.State,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
authURL := oc.authorizationURL()

// Print URL immediately for manual access (especially useful for headless environments)
pterm.Info.Println("Authentication URL:")
Expand Down Expand Up @@ -292,7 +292,6 @@ func RefreshTokens(ctx context.Context, tokens *TokenStorage) (*TokenStorage, er
values.Set("grant_type", "refresh_token")
values.Set("refresh_token", tokens.RefreshToken)
values.Set("client_id", tokenOAuthClientID(tokens))
values.Set("scope", DefaultScope)
if tokens.OrgID != "" {
values.Set("org_id", tokens.OrgID)
}
Expand Down
51 changes: 51 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"
"net/url"
"testing"
"time"

Expand Down Expand Up @@ -34,6 +35,29 @@ func TestNewOAuthConfigUsesAuthOverrides(t *testing.T) {
}
}

// The CLI names no scopes: the authorization server's consent page decides
// what the login may do.
func TestAuthorizationRequestNamesNoScope(t *testing.T) {
cfg, err := NewOAuthConfig()
if err != nil {
t.Fatalf("NewOAuthConfig() error = %v", err)
}
authURL, err := url.Parse(cfg.authorizationURL())
if err != nil {
t.Fatalf("authorizationURL() is not a URL: %v", err)
}
query := authURL.Query()
if query.Has("scope") {
t.Fatalf("authorization request names scope %q", query.Get("scope"))
}
if got, want := query.Get("code_challenge"), generateCodeChallenge(cfg.Verifier); got != want {
t.Fatalf("code_challenge = %q, want %q", got, want)
}
if got, want := query.Get("code_challenge_method"), "S256"; got != want {
t.Fatalf("code_challenge_method = %q, want %q", got, want)
}
}

func TestTokenRefreshConfigPrefersStoredValues(t *testing.T) {
t.Setenv("KERNEL_AUTH_BASE_URL", "https://auth.dev.onkernel.com")
t.Setenv("KERNEL_OAUTH_CLIENT_ID", "staging-client-id")
Expand Down Expand Up @@ -107,6 +131,33 @@ func TestOAuthCodeExchangeUsesAuthoritativeProjectScope(t *testing.T) {
}
}

func TestRefreshRequestNamesNoScope(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
t.Fatalf("ParseForm() error = %v", err)
}
if r.Form.Has("scope") {
t.Fatalf("refresh request names scope %q", r.Form.Get("scope"))
}
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": 3600,
})
}))
defer server.Close()

if _, err := RefreshTokens(context.Background(), &TokenStorage{
RefreshToken: "refresh-old",
AuthBaseURL: server.URL,
OAuthClientID: "client-id",
}); err != nil {
t.Fatalf("RefreshTokens() error = %v", err)
}
}

func TestRefreshTokensPreservesProjectScope(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
Expand Down
Loading