-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
427 lines (384 loc) · 14.8 KB
/
config.go
File metadata and controls
427 lines (384 loc) · 14.8 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
package main
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/go-authgate/sdk-go/credstore"
"github.com/go-authgate/sdk-go/discovery"
"github.com/go-authgate/sdk-go/oauth"
retry "github.com/appleboy/go-httpretry"
"github.com/google/uuid"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
)
// version is set at build time via -ldflags "-X main.version=...".
var version string
// Flag variables — Cobra binding targets, read once in loadConfig/loadStoreConfig.
var (
flagServerURL string
flagClientID string
flagClientSecret string
flagRedirectURI string
flagCallbackPort int
flagScope string
flagTokenFile string
flagTokenStore string
flagDevice bool
flagTokenExchangeTimeout string
flagTokenVerificationTimeout string
flagRefreshTokenTimeout string
flagDeviceCodeRequestTimeout string
flagCallbackTimeout string
flagUserInfoTimeout string
flagDiscoveryTimeout string
flagRevocationTimeout string
flagMaxResponseBodySize string
)
const (
defaultTokenExchangeTimeout = 10 * time.Second
defaultTokenVerificationTimeout = 10 * time.Second
defaultRefreshTokenTimeout = 10 * time.Second
defaultDeviceCodeRequestTimeout = 10 * time.Second
defaultCallbackTimeout = 2 * time.Minute
defaultUserInfoTimeout = 10 * time.Second
defaultDiscoveryTimeout = 10 * time.Second
defaultRevocationTimeout = 10 * time.Second
defaultMaxResponseBodySize = 1 * 1024 * 1024 // 1 MB — guards against oversized server responses
defaultKeyringService = "authgate-cli"
// maxDurationConfig caps user-supplied timeout values to prevent the CLI
// from hanging indefinitely on misconfiguration.
maxDurationConfig = 10 * time.Minute
// maxResponseBodySizeCap prevents users from setting an excessively large
// response body limit that could cause OOM via io.ReadAll.
maxResponseBodySizeCap int64 = 100 * 1024 * 1024 // 100 MB
)
// AppConfig holds all resolved configuration for the CLI application.
type AppConfig struct {
ServerURL string
ClientID string
ClientSecret string
RedirectURI string
CallbackPort int
Scope string
ForceDevice bool
TokenStoreMode string // "auto", "file", or "keyring"
RetryClient *retry.Client
Store credstore.Store[credstore.Token]
// Endpoints holds the resolved OAuth endpoint URLs.
// Populated by resolveEndpoints after loadConfig.
Endpoints oauth.Endpoints
// Timeout configuration (resolved from flag → env → default).
// Only populated by loadConfig; zero in loadStoreConfig paths.
TokenExchangeTimeout time.Duration
TokenVerificationTimeout time.Duration
RefreshTokenTimeout time.Duration
DeviceCodeRequestTimeout time.Duration
CallbackTimeout time.Duration
UserInfoTimeout time.Duration
DiscoveryTimeout time.Duration
RevocationTimeout time.Duration
MaxResponseBodySize int64
}
// IsPublicClient returns true when no client secret is configured —
// i.e., this is a public client that must use PKCE.
func (c *AppConfig) IsPublicClient() bool {
return c.ClientSecret == ""
}
func registerFlags(cmd *cobra.Command) {
_ = godotenv.Load()
cmd.PersistentFlags().
StringVar(&flagServerURL, "server-url", "", "OAuth server URL (default: http://localhost:8080 or SERVER_URL env)")
cmd.PersistentFlags().
StringVar(&flagClientID, "client-id", "", "OAuth client ID (required, or set CLIENT_ID env)")
cmd.PersistentFlags().
StringVar(&flagClientSecret, "client-secret", "", "OAuth client secret (confidential clients only; omit for public/PKCE clients)")
cmd.PersistentFlags().
StringVar(&flagRedirectURI, "redirect-uri", "", "Redirect URI registered with the OAuth server (default: http://localhost:PORT/callback)")
cmd.PersistentFlags().
IntVar(&flagCallbackPort, "port", 0, "Local callback port for browser flow (default: 8888 or CALLBACK_PORT env)")
cmd.PersistentFlags().
StringVar(&flagScope, "scope", "", "Space-separated OAuth scopes (default: \"email profile\")")
cmd.PersistentFlags().
StringVar(&flagTokenFile, "token-file", "", "Token storage file (default: .authgate-tokens.json or TOKEN_FILE env)")
cmd.PersistentFlags().
StringVar(&flagTokenStore, "token-store", "", "Token storage backend: auto, file, keyring (default: auto or TOKEN_STORE env)")
cmd.PersistentFlags().
BoolVar(&flagDevice, "device", false, "Force Device Code Flow (skip browser detection)")
cmd.PersistentFlags().
StringVar(&flagTokenExchangeTimeout, "token-exchange-timeout", "", "Timeout for token exchange requests (e.g. 10s, 1m)")
cmd.PersistentFlags().
StringVar(&flagTokenVerificationTimeout, "token-verification-timeout", "", "Timeout for token verification requests (e.g. 10s, 1m)")
cmd.PersistentFlags().
StringVar(&flagRefreshTokenTimeout, "refresh-token-timeout", "", "Timeout for token refresh requests (e.g. 10s, 1m)")
cmd.PersistentFlags().
StringVar(&flagDeviceCodeRequestTimeout, "device-code-request-timeout", "", "Timeout for device code requests (e.g. 10s, 1m)")
cmd.PersistentFlags().
StringVar(&flagCallbackTimeout, "callback-timeout", "", "Timeout waiting for browser callback (e.g. 2m, 5m)")
cmd.PersistentFlags().
StringVar(&flagUserInfoTimeout, "userinfo-timeout", "", "Timeout for UserInfo requests (e.g. 10s, 1m)")
cmd.PersistentFlags().
StringVar(&flagDiscoveryTimeout, "discovery-timeout", "", "Timeout for OIDC Discovery requests (e.g. 10s, 30s)")
cmd.PersistentFlags().
StringVar(&flagRevocationTimeout, "revocation-timeout", "", "Timeout for token revocation requests (e.g. 10s, 1m)")
cmd.PersistentFlags().
StringVar(&flagMaxResponseBodySize, "max-response-body-size", "", "Maximum response body size in bytes (e.g. 1048576)")
}
// loadStoreConfig initialises only the token store and client ID — the minimum
// needed for commands like `token get` that read local credentials without
// making any network calls.
func loadStoreConfig() *AppConfig {
cfg := &AppConfig{}
cfg.ClientID = getConfig(flagClientID, "CLIENT_ID", "")
cfg.TokenStoreMode = getConfig(flagTokenStore, "TOKEN_STORE", "auto")
tokenFile := getConfig(flagTokenFile, "TOKEN_FILE", ".authgate-tokens.json")
if cfg.ClientID == "" {
fmt.Fprintln(os.Stderr, "Error: CLIENT_ID not set. Please provide it via:")
fmt.Fprintln(os.Stderr, " 1. Command-line flag: --client-id=<your-client-id>")
fmt.Fprintln(os.Stderr, " 2. Environment variable: CLIENT_ID=<your-client-id>")
fmt.Fprintln(os.Stderr, " 3. .env file: CLIENT_ID=<your-client-id>")
fmt.Fprintln(os.Stderr, "\nYou can find the client_id in the server startup logs.")
os.Exit(1)
}
var storeErr error
cfg.Store, storeErr = newTokenStore(cfg.TokenStoreMode, tokenFile, defaultKeyringService)
if storeErr != nil {
fmt.Fprintln(os.Stderr, storeErr)
os.Exit(1)
}
return cfg
}
// loadConfig resolves all configuration from flags, environment, and defaults.
func loadConfig() *AppConfig {
cfg := loadStoreConfig()
cfg.ForceDevice = flagDevice
cfg.ServerURL = getConfig(flagServerURL, "SERVER_URL", "http://localhost:8080")
cfg.ClientSecret = getConfig(flagClientSecret, "CLIENT_SECRET", "")
cfg.Scope = getConfig(flagScope, "SCOPE", "email profile")
// Resolve callback port (int flag needs special handling).
portStr := ""
if flagCallbackPort != 0 {
portStr = strconv.Itoa(flagCallbackPort)
}
portStr = getConfig(portStr, "CALLBACK_PORT", "8888")
if port, err := strconv.Atoi(portStr); err != nil || port <= 0 {
cfg.CallbackPort = 8888
} else {
cfg.CallbackPort = port
}
// Resolve redirect URI (depends on port, so compute after port is known).
defaultRedirectURI := fmt.Sprintf("http://localhost:%d/callback", cfg.CallbackPort)
cfg.RedirectURI = getConfig(flagRedirectURI, "REDIRECT_URI", defaultRedirectURI)
if err := validateServerURL(cfg.ServerURL); err != nil {
fmt.Fprintf(os.Stderr, "Error: Invalid SERVER_URL: %v\n", err)
os.Exit(1)
}
if strings.HasPrefix(strings.ToLower(cfg.ServerURL), "http://") {
fmt.Fprintln(
os.Stderr,
"WARNING: Using HTTP instead of HTTPS. Tokens will be transmitted in plaintext!",
)
fmt.Fprintln(
os.Stderr,
"WARNING: This is only safe for local development. Use HTTPS in production.",
)
fmt.Fprintln(os.Stderr)
}
if _, err := uuid.Parse(cfg.ClientID); err != nil {
fmt.Fprintf(
os.Stderr,
"WARNING: CLIENT_ID doesn't appear to be a valid UUID: %s\n",
cfg.ClientID,
)
fmt.Fprintln(os.Stderr)
}
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
cfg.RetryClient, err = retry.NewBackgroundClient(retry.WithHTTPClient(baseHTTPClient))
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to create retry HTTP client: %v\n", err)
os.Exit(1)
}
// Resolve timeout configuration.
cfg.TokenExchangeTimeout = getDurationConfig(
flagTokenExchangeTimeout, "TOKEN_EXCHANGE_TIMEOUT", defaultTokenExchangeTimeout)
cfg.TokenVerificationTimeout = getDurationConfig(
flagTokenVerificationTimeout, "TOKEN_VERIFICATION_TIMEOUT", defaultTokenVerificationTimeout)
cfg.RefreshTokenTimeout = getDurationConfig(
flagRefreshTokenTimeout, "REFRESH_TOKEN_TIMEOUT", defaultRefreshTokenTimeout)
cfg.DeviceCodeRequestTimeout = getDurationConfig(
flagDeviceCodeRequestTimeout,
"DEVICE_CODE_REQUEST_TIMEOUT",
defaultDeviceCodeRequestTimeout,
)
cfg.CallbackTimeout = getDurationConfig(
flagCallbackTimeout, "CALLBACK_TIMEOUT", defaultCallbackTimeout)
cfg.UserInfoTimeout = getDurationConfig(
flagUserInfoTimeout, "USERINFO_TIMEOUT", defaultUserInfoTimeout)
cfg.DiscoveryTimeout = getDurationConfig(
flagDiscoveryTimeout, "DISCOVERY_TIMEOUT", defaultDiscoveryTimeout)
cfg.RevocationTimeout = getDurationConfig(
flagRevocationTimeout, "REVOCATION_TIMEOUT", defaultRevocationTimeout)
cfg.MaxResponseBodySize = getInt64Config(
flagMaxResponseBodySize, "MAX_RESPONSE_BODY_SIZE", defaultMaxResponseBodySize)
if cfg.MaxResponseBodySize > maxResponseBodySizeCap {
fmt.Fprintf(os.Stderr,
"WARNING: MAX_RESPONSE_BODY_SIZE exceeds %d, capping\n", maxResponseBodySizeCap)
cfg.MaxResponseBodySize = maxResponseBodySizeCap
}
if cfg.TokenStoreMode == "auto" {
if ss, ok := cfg.Store.(*credstore.SecureStore[credstore.Token]); ok && !ss.UseKeyring() {
fmt.Fprintln(
os.Stderr,
"WARNING: OS keyring unavailable, falling back to file-based token storage",
)
}
}
return cfg
}
// newTokenStore creates a token store backend based on the given mode.
func newTokenStore(
mode, tokenFilePath, keyringService string,
) (credstore.Store[credstore.Token], error) {
switch mode {
case "file":
return credstore.NewTokenFileStore(tokenFilePath), nil
case "keyring":
return credstore.NewTokenKeyringStore(keyringService), nil
case "auto":
return credstore.DefaultTokenSecureStore(keyringService, tokenFilePath), nil
default:
return nil, fmt.Errorf("invalid token store mode: %q (valid: auto, file, 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
}
// defaultEndpoints returns hardcoded endpoint paths appended to serverURL.
// Used as fallback when OIDC Discovery is unavailable.
func defaultEndpoints(serverURL string) oauth.Endpoints {
return oauth.Endpoints{
AuthorizeURL: serverURL + "/oauth/authorize",
TokenURL: serverURL + "/oauth/token",
DeviceAuthorizationURL: serverURL + "/oauth/device/code",
TokenInfoURL: serverURL + "/oauth/tokeninfo",
UserinfoURL: serverURL + "/oauth/userinfo",
RevocationURL: serverURL + "/oauth/revoke",
}
}
// resolveEndpoints attempts OIDC Discovery and falls back to hardcoded paths.
func resolveEndpoints(ctx context.Context, cfg *AppConfig) {
disco, err := discovery.NewClient(
cfg.ServerURL,
discovery.WithHTTPClient(cfg.RetryClient),
)
if err != nil {
fmt.Fprintf(os.Stderr,
"WARNING: OIDC Discovery init failed: %v (using default endpoints)\n", err)
cfg.Endpoints = defaultEndpoints(cfg.ServerURL)
return
}
fetchCtx, cancel := context.WithTimeout(ctx, cfg.DiscoveryTimeout)
defer cancel()
meta, err := disco.Fetch(fetchCtx)
if err != nil {
fmt.Fprintf(os.Stderr,
"WARNING: OIDC Discovery fetch failed: %v (using default endpoints)\n", err)
cfg.Endpoints = defaultEndpoints(cfg.ServerURL)
return
}
cfg.Endpoints = meta.Endpoints()
}
// getDurationConfig resolves a time.Duration from flag → env → default.
// The value is parsed with time.ParseDuration (e.g. "10s", "2m", "1m30s").
// On parse error or non-positive value, it falls back to the default and prints a warning.
func getDurationConfig(flagValue, envKey string, defaultValue time.Duration) time.Duration {
raw := getConfig(flagValue, envKey, "")
if raw == "" {
return defaultValue
}
d, err := time.ParseDuration(raw)
if err != nil {
fmt.Fprintf(os.Stderr, "WARNING: invalid duration %q for %s, using default %s\n",
raw, envKey, defaultValue)
return defaultValue
}
if d <= 0 {
fmt.Fprintf(os.Stderr, "WARNING: %s must be positive, got %s, using default %s\n",
envKey, d, defaultValue)
return defaultValue
}
if d > maxDurationConfig {
fmt.Fprintf(os.Stderr, "WARNING: %s exceeds maximum %s, capping at %s\n",
envKey, maxDurationConfig, maxDurationConfig)
return maxDurationConfig
}
return d
}
// getInt64Config resolves an int64 from flag → env → default.
// On parse error or non-positive value, it falls back to the default and prints a warning.
func getInt64Config(flagValue, envKey string, defaultValue int64) int64 {
raw := getConfig(flagValue, envKey, "")
if raw == "" {
return defaultValue
}
v, err := strconv.ParseInt(raw, 10, 64)
if err != nil || v <= 0 {
fmt.Fprintf(os.Stderr, "WARNING: invalid value %q for %s, using default %d\n",
raw, envKey, defaultValue)
return defaultValue
}
return v
}
// getVersion returns the build version, preferring the ldflags-injected value
// and falling back to debug.ReadBuildInfo().
func getVersion() string {
if version != "" {
return version
}
if build, ok := debug.ReadBuildInfo(); ok &&
build.Main.Version != "" &&
build.Main.Version != "(devel)" {
return build.Main.Version
}
return "unknown version"
}