Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
16 changes: 8 additions & 8 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func refreshAccessToken(
cfg *AppConfig,
refreshToken string,
) (*credstore.Token, error) {
ctx, cancel := context.WithTimeout(ctx, refreshTokenTimeout)
ctx, cancel := context.WithTimeout(ctx, cfg.RefreshTokenTimeout)
defer cancel()

data := url.Values{}
Expand All @@ -74,7 +74,7 @@ func refreshAccessToken(
data.Set("client_secret", cfg.ClientSecret)
}

tokenResp, err := doTokenExchange(ctx, cfg, cfg.ServerURL+"/oauth/token", data,
tokenResp, err := doTokenExchange(ctx, cfg, cfg.Endpoints.TokenURL, data,
func(errResp ErrorResponse, _ []byte) error {
if errResp.Error == "invalid_grant" || errResp.Error == "invalid_token" {
return ErrRefreshTokenExpired
Expand All @@ -101,18 +101,18 @@ func refreshAccessToken(

// verifyToken verifies an access token with the OAuth server.
func verifyToken(ctx context.Context, cfg *AppConfig, accessToken string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, tokenVerificationTimeout)
ctx, cancel := context.WithTimeout(ctx, cfg.TokenVerificationTimeout)
defer cancel()

resp, err := cfg.RetryClient.Get(ctx, cfg.ServerURL+"/oauth/tokeninfo",
resp, err := cfg.RetryClient.Get(ctx, cfg.Endpoints.TokenInfoURL,
retry.WithHeader("Authorization", "Bearer "+accessToken),
)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()

body, err := readResponseBody(resp)
body, err := readResponseBody(resp, cfg.MaxResponseBodySize)
if err != nil {
return "", err
}
Expand All @@ -131,7 +131,7 @@ func makeAPICallWithAutoRefresh(
storage *credstore.Token,
ui tui.Manager,
) error {
resp, err := cfg.RetryClient.Get(ctx, cfg.ServerURL+"/oauth/tokeninfo",
resp, err := cfg.RetryClient.Get(ctx, cfg.Endpoints.TokenInfoURL,
retry.WithHeader("Authorization", "Bearer "+storage.AccessToken),
)
if err != nil {
Expand All @@ -156,7 +156,7 @@ func makeAPICallWithAutoRefresh(

ui.ShowStatus(tui.StatusUpdate{Event: tui.EventTokenRefreshedRetrying})

resp, err = cfg.RetryClient.Get(ctx, cfg.ServerURL+"/oauth/tokeninfo",
resp, err = cfg.RetryClient.Get(ctx, cfg.Endpoints.TokenInfoURL,
retry.WithHeader("Authorization", "Bearer "+storage.AccessToken),
)
if err != nil {
Expand All @@ -165,7 +165,7 @@ func makeAPICallWithAutoRefresh(
defer resp.Body.Close()
}

body, err := readResponseBody(resp)
body, err := readResponseBody(resp, cfg.MaxResponseBodySize)
if err != nil {
return err
}
Expand Down
12 changes: 6 additions & 6 deletions browser_flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func buildAuthURL(cfg *AppConfig, state string, pkce *PKCEParams) string {
params.Set("state", state)
params.Set("code_challenge", pkce.Challenge)
params.Set("code_challenge_method", pkce.Method)
return cfg.ServerURL + "/oauth/authorize?" + params.Encode()
return cfg.Endpoints.AuthorizeURL + "?" + params.Encode()
}

// exchangeCode exchanges an authorization code for access + refresh tokens.
Expand All @@ -30,7 +30,7 @@ func exchangeCode(
cfg *AppConfig,
code, codeVerifier string,
) (*credstore.Token, error) {
ctx, cancel := context.WithTimeout(ctx, tokenExchangeTimeout)
ctx, cancel := context.WithTimeout(ctx, cfg.TokenExchangeTimeout)
defer cancel()

data := url.Values{}
Expand All @@ -44,7 +44,7 @@ func exchangeCode(
data.Set("client_secret", cfg.ClientSecret)
}

tokenResp, err := doTokenExchange(ctx, cfg, cfg.ServerURL+"/oauth/token", data, nil)
tokenResp, err := doTokenExchange(ctx, cfg, cfg.Endpoints.TokenURL, data, nil)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -144,7 +144,7 @@ func performBrowserFlowWithUpdates(
return
case <-ticker.C:
elapsed := time.Since(startTime)
progress := float64(elapsed) / float64(callbackTimeout)
progress := float64(elapsed) / float64(cfg.CallbackTimeout)
if progress > 1.0 {
progress = 1.0
}
Expand All @@ -153,7 +153,7 @@ func performBrowserFlowWithUpdates(
Progress: progress,
Data: map[string]any{
"elapsed": elapsed,
"timeout": callbackTimeout,
"timeout": cfg.CallbackTimeout,
},
}
select {
Expand All @@ -167,7 +167,7 @@ func performBrowserFlowWithUpdates(
}
}()

storage, err := startCallbackServer(ctx, cfg.CallbackPort, state,
storage, err := startCallbackServer(ctx, cfg.CallbackPort, state, cfg.CallbackTimeout,
func(callbackCtx context.Context, code string) (*credstore.Token, error) {
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Expand Down
12 changes: 4 additions & 8 deletions callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,7 @@ func sanitizeTokenExchangeError(_ error) string {
return "Token exchange failed. Please try again."
}

const (
// callbackTimeout is how long we wait for the browser to deliver the code.
callbackTimeout = 2 * time.Minute
)

// ErrCallbackTimeout is returned when no browser callback is received within callbackTimeout.
// ErrCallbackTimeout is returned when no browser callback is received within the callback timeout.
// Callers can use errors.Is to distinguish a timeout from other authorization errors
// and decide whether to fall back to Device Code Flow.
var ErrCallbackTimeout = errors.New("browser authorization timed out")
Expand All @@ -76,6 +71,7 @@ type callbackResult struct {
//
// The server shuts itself down after the first request.
func startCallbackServer(ctx context.Context, port int, expectedState string,
cbTimeout time.Duration,
exchangeFn func(context.Context, string) (*credstore.Token, error),
) (*credstore.Token, error) {
resultCh := make(chan callbackResult, 1)
Expand Down Expand Up @@ -158,7 +154,7 @@ func startCallbackServer(ctx context.Context, port int, expectedState string,
_ = srv.Shutdown(shutdownCtx)
}()

timer := time.NewTimer(callbackTimeout)
timer := time.NewTimer(cbTimeout)
defer timer.Stop()

select {
Expand All @@ -172,7 +168,7 @@ func startCallbackServer(ctx context.Context, port int, expectedState string,
return result.Storage, nil

case <-timer.C:
return nil, fmt.Errorf("%w after %s", ErrCallbackTimeout, callbackTimeout)
return nil, fmt.Errorf("%w after %s", ErrCallbackTimeout, cbTimeout)

case <-ctx.Done():
return nil, ctx.Err()
Expand Down
2 changes: 1 addition & 1 deletion callback_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func startCallbackServerAsync(
t.Helper()
ch := make(chan callbackServerResult, 1)
go func() {
storage, err := startCallbackServer(ctx, port, state, exchangeFn)
storage, err := startCallbackServer(ctx, port, state, defaultCallbackTimeout, exchangeFn)
ch <- callbackServerResult{storage, err}
}()
// Give the server a moment to bind.
Expand Down
168 changes: 162 additions & 6 deletions config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"context"
"crypto/tls"
"errors"
"fmt"
Expand All @@ -13,6 +14,7 @@ import (
"time"

"github.com/go-authgate/sdk-go/credstore"
"github.com/go-authgate/sdk-go/discovery"

retry "github.com/appleboy/go-httpretry"
"github.com/google/uuid"
Expand All @@ -34,17 +36,38 @@ var (
flagTokenFile string
flagTokenStore string
flagDevice bool

flagTokenExchangeTimeout string
flagTokenVerificationTimeout string
flagRefreshTokenTimeout string
flagDeviceCodeRequestTimeout string
flagCallbackTimeout string
flagUserInfoTimeout string
flagMaxResponseBodySize string
)

const (
tokenExchangeTimeout = 10 * time.Second
tokenVerificationTimeout = 10 * time.Second
refreshTokenTimeout = 10 * time.Second
deviceCodeRequestTimeout = 10 * time.Second
maxResponseBodySize = 1 * 1024 * 1024 // 1 MB — guards against oversized server responses
defaultKeyringService = "authgate-cli"
defaultTokenExchangeTimeout = 10 * time.Second
defaultTokenVerificationTimeout = 10 * time.Second
defaultRefreshTokenTimeout = 10 * time.Second
defaultDeviceCodeRequestTimeout = 10 * time.Second
defaultCallbackTimeout = 2 * time.Minute
defaultUserInfoTimeout = 10 * time.Second
defaultMaxResponseBodySize = 1 * 1024 * 1024 // 1 MB — guards against oversized server responses
defaultKeyringService = "authgate-cli"
)

// ResolvedEndpoints holds the absolute URLs for all OAuth endpoints.
// Populated from OIDC Discovery or from hardcoded fallback paths.
type ResolvedEndpoints struct {
AuthorizeURL string
TokenURL string
DeviceAuthorizationURL string
TokenInfoURL string
UserinfoURL string
RevocationURL string
}

// AppConfig holds all resolved configuration for the CLI application.
type AppConfig struct {
ServerURL string
Expand All @@ -57,6 +80,20 @@ type AppConfig struct {
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 ResolvedEndpoints

// 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
MaxResponseBodySize int64
}

// IsPublicClient returns true when no client secret is configured —
Expand Down Expand Up @@ -85,6 +122,20 @@ func registerFlags(cmd *cobra.Command) {
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(&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
Expand Down Expand Up @@ -180,6 +231,25 @@ func loadConfig() *AppConfig {
panic(fmt.Sprintf("failed to create retry client: %v", err))
}

// 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.MaxResponseBodySize = getInt64Config(
flagMaxResponseBodySize, "MAX_RESPONSE_BODY_SIZE", defaultMaxResponseBodySize)

if cfg.TokenStoreMode == "auto" {
if ss, ok := cfg.Store.(*credstore.SecureStore[credstore.Token]); ok && !ss.UseKeyring() {
fmt.Fprintln(
Expand Down Expand Up @@ -239,6 +309,92 @@ func validateServerURL(rawURL string) error {
return nil
}

// defaultEndpoints returns hardcoded endpoint paths appended to serverURL.
// Used as fallback when OIDC Discovery is unavailable.
func defaultEndpoints(serverURL string) ResolvedEndpoints {
return ResolvedEndpoints{
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, 10*time.Second)
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
}

ep := meta.Endpoints()
cfg.Endpoints = ResolvedEndpoints{
AuthorizeURL: ep.AuthorizeURL,
TokenURL: ep.TokenURL,
DeviceAuthorizationURL: ep.DeviceAuthorizationURL,
TokenInfoURL: ep.TokenInfoURL,
UserinfoURL: ep.UserinfoURL,
RevocationURL: ep.RevocationURL,
}
}

// 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
Comment thread
appleboy marked this conversation as resolved.
}
if d <= 0 {
fmt.Fprintf(os.Stderr, "WARNING: %s must be positive, got %s, using default %s\n",
envKey, d, defaultValue)
return defaultValue
}
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
Comment thread
appleboy marked this conversation as resolved.
}

// getVersion returns the build version, preferring the ldflags-injected value
// and falling back to debug.ReadBuildInfo().
func getVersion() string {
Expand Down
Loading
Loading