-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
636 lines (553 loc) · 18.4 KB
/
main.go
File metadata and controls
636 lines (553 loc) · 18.4 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/go-authgate/oauth-cli/tui"
"github.com/go-authgate/sdk-go/credstore"
tea "charm.land/bubbletea/v2"
retry "github.com/appleboy/go-httpretry"
"github.com/google/uuid"
"github.com/joho/godotenv"
)
var (
serverURL string
clientID string
clientSecret string
redirectURI string
callbackPort int
scope string
tokenFile string
tokenStore credstore.Store[credstore.Token]
configOnce sync.Once
retryClient *retry.Client
configWarnings []string
flagServerURL *string
flagClientID *string
flagClientSecret *string
flagRedirectURI *string
flagCallbackPort *int
flagScope *string
flagTokenFile *string
flagTokenStore *string
)
const (
tokenExchangeTimeout = 10 * time.Second
tokenVerificationTimeout = 10 * time.Second
refreshTokenTimeout = 10 * time.Second
maxResponseSize = 1 << 20 // 1 MiB
)
func init() {
_ = godotenv.Load()
flagServerURL = flag.String(
"server-url",
"",
"OAuth server URL (default: http://localhost:8080 or SERVER_URL env)",
)
flagClientID = flag.String("client-id", "", "OAuth client ID (required, or set CLIENT_ID env)")
flagClientSecret = flag.String(
"client-secret",
"",
"OAuth client secret (confidential clients only; omit for public/PKCE clients)",
)
flagRedirectURI = flag.String(
"redirect-uri",
"",
"Redirect URI registered with the OAuth server (default: http://localhost:CALLBACK_PORT/callback)",
)
flagCallbackPort = flag.Int(
"port",
0,
"Local port for the callback server (default: 8888 or CALLBACK_PORT env)",
)
flagScope = flag.String("scope", "", "Space-separated OAuth scopes (default: \"read write\")")
flagTokenFile = flag.String(
"token-file",
"",
"Token storage file (default: .authgate-tokens.json or TOKEN_FILE env)",
)
flagTokenStore = flag.String(
"token-store",
"",
"Token storage backend: auto, file, keyring (default: auto or TOKEN_STORE env)",
)
}
// initConfig parses flags and initializes all configuration.
func initConfig() {
configOnce.Do(doInitConfig)
}
func doInitConfig() {
flag.Parse()
serverURL = getConfig(*flagServerURL, "SERVER_URL", "http://localhost:8080")
clientID = getConfig(*flagClientID, "CLIENT_ID", "")
clientSecret = getConfig(*flagClientSecret, "CLIENT_SECRET", "")
if *flagClientSecret != "" {
configWarnings = append(configWarnings,
"Client secret passed via command-line flag. "+
"This may be visible in process listings. "+
"Consider using CLIENT_SECRET env var or .env file instead.")
}
scope = getConfig(*flagScope, "SCOPE", "read write")
tokenFile = getConfig(*flagTokenFile, "TOKEN_FILE", ".authgate-tokens.json")
// Resolve callback port (int flag needs special handling).
portStr := ""
if *flagCallbackPort != 0 {
portStr = strconv.Itoa(*flagCallbackPort)
}
portStr = getConfig(portStr, "CALLBACK_PORT", "8888")
if _, err := fmt.Sscanf(portStr, "%d", &callbackPort); err != nil || callbackPort <= 0 {
callbackPort = 8888
}
// Resolve redirect URI (default depends on port, so compute after port is known).
defaultRedirectURI := fmt.Sprintf("http://localhost:%d/callback", callbackPort)
redirectURI = getConfig(*flagRedirectURI, "REDIRECT_URI", defaultRedirectURI)
// Validate SERVER_URL.
if err := validateServerURL(serverURL); err != nil {
fmt.Fprintf(os.Stderr, "Error: Invalid SERVER_URL: %v\n", err)
os.Exit(1)
}
if strings.HasPrefix(strings.ToLower(serverURL), "http://") {
configWarnings = append(configWarnings,
"Using HTTP instead of HTTPS. Tokens will be transmitted in plaintext!")
configWarnings = append(configWarnings,
"This is only safe for local development. Use HTTPS in production.")
}
if clientID == "" {
fmt.Println("Error: CLIENT_ID not set. Please provide it via:")
fmt.Println(" 1. Command-line flag: -client-id=<your-client-id>")
fmt.Println(" 2. Environment variable: CLIENT_ID=<your-client-id>")
fmt.Println(" 3. .env file: CLIENT_ID=<your-client-id>")
fmt.Println("\nYou can find the client_id in the server startup logs.")
os.Exit(1)
}
if _, err := uuid.Parse(clientID); err != nil {
configWarnings = append(configWarnings,
"CLIENT_ID doesn't appear to be a valid UUID: "+clientID)
}
// Build HTTP client with TLS and retry support.
baseHTTPClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
MaxIdleConns: 10,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
},
}
var err error
retryClient, err = retry.NewBackgroundClient(retry.WithHTTPClient(baseHTTPClient))
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to create retry client: %v\n", err)
os.Exit(1)
}
const defaultKeyringService = "authgate-oauth-cli"
tokenStoreMode := getConfig(*flagTokenStore, "TOKEN_STORE", "auto")
var warnings []string
tokenStore, warnings, err = initTokenStore(tokenStoreMode, tokenFile, defaultKeyringService)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
configWarnings = append(configWarnings, warnings...)
}
// initTokenStore creates a token store based on the given mode.
// It returns the store, any warnings, and an error if the mode is invalid.
func initTokenStore(
mode, filePath, keyringService string,
) (credstore.Store[credstore.Token], []string, error) {
fileStore := credstore.NewTokenFileStore(filePath)
var warnings []string
switch mode {
case "file":
return fileStore, nil, nil
case "keyring":
return credstore.NewTokenKeyringStore(keyringService), nil, nil
case "auto":
ss := credstore.DefaultTokenSecureStore(keyringService, filePath)
if !ss.UseKeyring() {
warnings = append(warnings,
"OS keyring unavailable, falling back to file-based token storage")
}
return ss, warnings, nil
default:
return nil, nil, fmt.Errorf(
"invalid token-store value: %s (must be auto, file, or keyring)",
mode,
)
}
}
func getConfig(flagValue, envKey, defaultValue string) string {
if flagValue != "" {
return flagValue
}
return getEnv(envKey, defaultValue)
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
func validateServerURL(rawURL string) error {
if rawURL == "" {
return errors.New("server URL cannot be empty")
}
u, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("invalid URL format: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("URL scheme must be http or https, got: %s", u.Scheme)
}
if u.Host == "" {
return errors.New("URL must include a host")
}
return nil
}
// isPublicClient returns true when no client secret is configured —
// i.e., this is a public client that must use PKCE.
func isPublicClient() bool {
return clientSecret == ""
}
// -----------------------------------------------------------------------
// Token storage
// -----------------------------------------------------------------------
// ErrorResponse is an OAuth error payload.
type ErrorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
// tokenResponse is the JSON structure returned by /oauth/token.
type tokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
// errResponseTooLarge is returned when a server response exceeds maxResponseSize.
var errResponseTooLarge = fmt.Errorf(
"response body exceeds maximum allowed size of %d bytes",
maxResponseSize,
)
// readResponseBody reads up to maxResponseSize bytes from r and returns an
// explicit error when the response is too large (rather than silently truncating).
func readResponseBody(r io.Reader) ([]byte, error) {
body, err := io.ReadAll(io.LimitReader(r, maxResponseSize+1))
if err != nil {
return nil, err
}
if int64(len(body)) > maxResponseSize {
return nil, errResponseTooLarge
}
return body, nil
}
// parseOAuthError attempts to extract a structured OAuth error from a non-200
// response body. Falls back to including the raw body in the error message.
func parseOAuthError(statusCode int, body []byte, action string) error {
var errResp ErrorResponse
if jsonErr := json.Unmarshal(body, &errResp); jsonErr == nil && errResp.Error != "" {
return fmt.Errorf("%s: %s", errResp.Error, errResp.ErrorDescription)
}
return fmt.Errorf("%s failed with status %d: %s", action, statusCode, string(body))
}
// isRefreshTokenError checks whether the response body indicates an expired
// or invalid refresh token (invalid_grant / invalid_token).
func isRefreshTokenError(body []byte) bool {
var errResp ErrorResponse
if err := json.Unmarshal(body, &errResp); err == nil {
return errResp.Error == "invalid_grant" || errResp.Error == "invalid_token"
}
return false
}
// validateTokenResponse performs basic sanity checks on a token response.
func validateTokenResponse(accessToken, tokenType string, expiresIn int) error {
if accessToken == "" {
return errors.New("access_token is empty")
}
if len(accessToken) < 10 {
return fmt.Errorf("access_token is too short (length: %d)", len(accessToken))
}
if expiresIn <= 0 {
return fmt.Errorf("expires_in must be positive, got: %d", expiresIn)
}
if tokenType != "" && tokenType != "Bearer" {
return fmt.Errorf("unexpected token_type: %s (expected Bearer)", tokenType)
}
return nil
}
// -----------------------------------------------------------------------
// Authorization Code Flow
// -----------------------------------------------------------------------
// buildAuthURL constructs the /oauth/authorize URL with all required parameters.
func buildAuthURL(state string, pkce *tui.PKCEParams) string {
params := url.Values{}
params.Set("client_id", clientID)
params.Set("redirect_uri", redirectURI)
params.Set("response_type", "code")
params.Set("scope", scope)
params.Set("state", state)
params.Set("code_challenge", pkce.Challenge)
params.Set("code_challenge_method", pkce.Method)
return serverURL + "/oauth/authorize?" + params.Encode()
}
// exchangeCode exchanges an authorization code for access + refresh tokens.
func exchangeCode(ctx context.Context, code, codeVerifier string) (*tui.TokenStorage, error) {
ctx, cancel := context.WithTimeout(ctx, tokenExchangeTimeout)
defer cancel()
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("code", code)
data.Set("redirect_uri", redirectURI)
data.Set("client_id", clientID)
// PKCE is always enabled (defense in depth).
data.Set("code_verifier", codeVerifier)
if !isPublicClient() {
data.Set("client_secret", clientSecret)
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
serverURL+"/oauth/token",
strings.NewReader(data.Encode()),
)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := retryClient.DoWithContext(ctx, req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, parseOAuthError(resp.StatusCode, body, "token exchange")
}
var tokenResp tokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
if err := validateTokenResponse(
tokenResp.AccessToken,
tokenResp.TokenType,
tokenResp.ExpiresIn,
); err != nil {
return nil, fmt.Errorf("invalid token response: %w", err)
}
return &tui.TokenStorage{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
TokenType: tokenResp.TokenType,
ExpiresAt: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second),
ClientID: clientID,
}, nil
}
// -----------------------------------------------------------------------
// Token refresh
// -----------------------------------------------------------------------
func refreshAccessToken(ctx context.Context, refreshToken string) (*tui.TokenStorage, error) {
ctx, cancel := context.WithTimeout(ctx, refreshTokenTimeout)
defer cancel()
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", refreshToken)
data.Set("client_id", clientID)
if !isPublicClient() {
data.Set("client_secret", clientSecret)
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
serverURL+"/oauth/token",
strings.NewReader(data.Encode()),
)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := retryClient.DoWithContext(ctx, req)
if err != nil {
return nil, fmt.Errorf("refresh request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
// Check for expired/invalid refresh token before general error handling.
if isRefreshTokenError(body) {
return nil, tui.ErrRefreshTokenExpired
}
return nil, parseOAuthError(resp.StatusCode, body, "refresh")
}
var tokenResp tokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
if err := validateTokenResponse(
tokenResp.AccessToken,
tokenResp.TokenType,
tokenResp.ExpiresIn,
); err != nil {
return nil, fmt.Errorf("invalid token response: %w", err)
}
// Preserve the old refresh token in fixed-mode (server may not return a new one).
newRefreshToken := tokenResp.RefreshToken
if newRefreshToken == "" {
newRefreshToken = refreshToken
}
storage := &tui.TokenStorage{
AccessToken: tokenResp.AccessToken,
RefreshToken: newRefreshToken,
TokenType: tokenResp.TokenType,
ExpiresAt: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second),
ClientID: clientID,
}
return storage, nil
}
// -----------------------------------------------------------------------
// Token verification / API demo
// -----------------------------------------------------------------------
func verifyToken(ctx context.Context, accessToken string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, tokenVerificationTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, serverURL+"/oauth/tokeninfo", nil)
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := retryClient.DoWithContext(ctx, req)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return "", parseOAuthError(resp.StatusCode, body, "token verification")
}
return string(body), nil
}
// makeAPICallWithAutoRefresh demonstrates the 401 → refresh → retry pattern.
func makeAPICallWithAutoRefresh(ctx context.Context, storage *tui.TokenStorage) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, serverURL+"/oauth/tokeninfo", nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+storage.AccessToken)
resp, err := retryClient.DoWithContext(ctx, req)
if err != nil {
return fmt.Errorf("API request failed: %w", err)
}
if resp.StatusCode == http.StatusUnauthorized {
// Drain and close body so the HTTP transport can reuse the connection.
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
newStorage, err := refreshAccessToken(ctx, storage.RefreshToken)
if err != nil {
if err == tui.ErrRefreshTokenExpired {
return tui.ErrRefreshTokenExpired
}
return fmt.Errorf("refresh failed: %w", err)
}
*storage = *newStorage
req, err = http.NewRequestWithContext(
ctx,
http.MethodGet,
serverURL+"/oauth/tokeninfo",
nil,
)
if err != nil {
return fmt.Errorf("failed to create retry request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+storage.AccessToken)
resp, err = retryClient.DoWithContext(ctx, req)
if err != nil {
return fmt.Errorf("retry failed: %w", err)
}
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("API call failed with status %d: %s", resp.StatusCode, string(body))
}
return nil
}
// -----------------------------------------------------------------------
// main
// -----------------------------------------------------------------------
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
initConfig()
clientMode := "public (PKCE)"
if !isPublicClient() {
clientMode = "confidential"
}
deps := tui.Deps{
LoadTokens: func() (*tui.TokenStorage, error) {
tok, err := tokenStore.Load(clientID)
if err != nil {
return nil, err
}
return &tok, nil
},
RefreshToken: func(ctx context.Context, refreshToken string) (*tui.TokenStorage, string, error) {
storage, err := refreshAccessToken(ctx, refreshToken)
if err != nil {
return nil, "", err
}
saveWarning := ""
if saveErr := tokenStore.Save(storage.ClientID, *storage); saveErr != nil {
saveWarning = fmt.Sprintf("Warning: Failed to save refreshed tokens: %v", saveErr)
}
return storage, saveWarning, nil
},
GenerateState: generateState,
GeneratePKCE: GeneratePKCE,
BuildAuthURL: buildAuthURL,
OpenBrowser: openBrowser,
StartCallback: startCallbackServer,
ExchangeCode: exchangeCode,
SaveTokens: func(storage *tui.TokenStorage) error {
return tokenStore.Save(storage.ClientID, *storage)
},
VerifyToken: verifyToken,
MakeAPICall: makeAPICallWithAutoRefresh,
CallbackPort: callbackPort,
}
p := tea.NewProgram(
tui.NewOAuthModel(ctx, deps, clientMode, serverURL, clientID, configWarnings),
)
finalRaw, err := p.Run()
if err != nil {
stop()
fmt.Fprintf(os.Stderr, "TUI error: %v\n", err)
os.Exit(1)
}
stop()
if m, ok := finalRaw.(tui.OAuthModel); ok && m.ExitCode != 0 {
os.Exit(m.ExitCode)
}
}