-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathauth.go
More file actions
139 lines (116 loc) · 4.09 KB
/
Copy pathauth.go
File metadata and controls
139 lines (116 loc) · 4.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package cmd
import (
"os"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/kernel/cli/pkg/auth"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"github.com/zalando/go-keyring"
)
// 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
OrgName string `json:"org_name"` // Organization name
}
var authCmd = &cobra.Command{
Use: "auth",
Short: "Show authentication status and manage auth connections",
Long: `Display information about the current authentication state, including logged-in user details and token expiry.
Use --log-level debug to show additional details like user ID and storage method.
Use "kernel auth connections" to manage managed auth connections for automated login flows.`,
RunE: runAuth,
}
func init() {
rootCmd.AddCommand(authCmd)
}
// parseJWT parses a JWT token and returns the claims
func parseJWT(tokenString string) (*JWTClaims, error) {
// Parse the token without verification since we don't have the signing key
token, _, err := jwt.NewParser().ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return nil, err
}
// Extract claims
if claims, ok := token.Claims.(jwt.MapClaims); ok {
jwtClaims := &JWTClaims{}
if sub, ok := claims["sub"].(string); ok {
jwtClaims.Sub = sub
}
if email, ok := claims["email"].(string); ok {
jwtClaims.Email = email
}
if exp, ok := claims["exp"].(float64); ok {
jwtClaims.Exp = int64(exp)
}
if iss, ok := claims["iss"].(string); ok {
jwtClaims.Iss = iss
}
if orgID, ok := claims["org_id"].(string); ok {
jwtClaims.OrgID = orgID
}
if orgName, ok := claims["org_name"].(string); ok {
jwtClaims.OrgName = orgName
}
return jwtClaims, nil
}
return nil, nil
}
func runAuth(cmd *cobra.Command, args []string) error {
// Check for stored OAuth tokens
tokens, err := auth.LoadTokens()
if err != nil {
// Check if API key is being used as fallback
if apiKey := os.Getenv("KERNEL_API_KEY"); apiKey != "" {
pterm.Info.Println("Authentication method: API Key")
if len(apiKey) >= 12 {
pterm.Info.Printf("API Key: %s...%s\n", apiKey[:8], apiKey[len(apiKey)-4:])
} else {
pterm.Info.Printf("API Key: %s\n", strings.Repeat("*", len(apiKey)))
}
return nil
}
pterm.Info.Println("No active session found - not authenticated")
pterm.Info.Println("Run 'kernel login' to authenticate with OAuth")
pterm.Info.Println("Or set KERNEL_API_KEY environment variable")
return nil
}
// Display OAuth authentication status
pterm.Success.Println("✓ Authenticated with OAuth")
// 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))
}
}
// Token expiry status
if tokens.IsExpired() {
if tokens.RefreshToken != "" {
pterm.Warning.Println("⚠️ Access token expired (will be refreshed automatically)")
} else {
pterm.Error.Println("❌ Access token expired and no refresh token available")
pterm.Info.Println("Run 'kernel login --force' to re-authenticate")
}
} else {
timeUntilExpiry := time.Until(tokens.ExpiresAt)
logger.Debug("Time until expiry", logger.Args("time_until_expiry", timeUntilExpiry))
logger.Debug("Expires at", logger.Args("expires_at", tokens.ExpiresAt))
if timeUntilExpiry < 24*time.Hour {
pterm.Warning.Printf("⚠️ Access token expires in %s\n", timeUntilExpiry.Round(time.Second))
} else {
pterm.Success.Printf("✓ Access token valid for %s\n", timeUntilExpiry.Round(time.Second))
}
}
// 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)"))
}
return nil
}