Skip to content
Merged
41 changes: 37 additions & 4 deletions docs/src/api/oidc.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,45 @@ Use `WithClientSecretProvider` when the application rotates secret material.
| `WithClientSecret(secret)` | OAuth2 client secret (for client credentials) |
| `WithClientSecretProvider(provider)` | Resolve the client secret for each exchange |
| `WithAudience(audience)` | Optional OAuth2 resource-server audience |
| `WithScopes(scopes...)` | Custom scopes (client credentials has no implicit scopes) |
| `WithScopes(scopes...)` | Replace the default scopes (`openid profile email`); see [Scopes](#scopes) |
| `WithCallbackPort(port)` | Fixed port for localhost callback (default: tries 8000, then 18000) |
| `WithTimeout(d)` | Auth flow timeout (default: 2 minutes) |
| `WithTimeout(d)` | Flow timeout (default: 2 minutes); see [Timeouts](#timeouts) |
| `WithKeyboardFlow()` | Use keyboard flow instead of browser |
| `WithInMemory()` | Skip token persistence to disk |
| `WithDisplayFunc(fn)` | Custom display for device code flow |
| `WithGateway(name)` | Resolve OIDC config from gateway metadata |

### Scopes

Scopes come from `WithScopes` if set, then from the gateway's
`oidc_scopes` (when the flow reads gateway metadata), then from the
defaults.

- `Login` and `DeviceLogin` authenticate a user, so they always request
`openid`: `WithScopes("sandbox:read")` sends `openid sandbox:read`, and
`WithScopes()` sends only `openid`.
- `ClientCredentials` and `NewClientCredentialsAuth` have no user, so they
send exactly the scopes set by `WithScopes` or the gateway, with no
defaults. Without scopes, the token request carries no `scope`
parameter.

### Timeouts

`Login`, `DeviceLogin` and `ClientCredentials` apply `WithTimeout` only
when the context has no deadline; a context deadline always wins. For
these flows, a zero or negative duration means no deadline, so the flow
runs until it completes or the context is cancelled.

`NewClientCredentialsAuth` renews tokens in the background, where no
caller context can cancel the exchange. It always bounds each exchange:
by `WithTimeout` when positive, otherwise by the 2 minute default.

`ErrTimeout` covers only the interactive flows. When a client credentials
exchange runs out of time or its context is cancelled, the error matches
both `ErrClientCredentials` and the context error, so
`errors.Is(err, context.DeadlineExceeded)` tells a timeout apart from a
provider failure.

## Error Handling

The package defines sentinel errors for `errors.Is()` matching:
Expand All @@ -110,7 +141,7 @@ The package defines sentinel errors for `errors.Is()` matching:
| `ErrAuthCode` | Authorization code exchange failed |
| `ErrDeviceCode` | Device code flow failed |
| `ErrClientCredentials` | Client credentials exchange failed |
| `ErrTimeout` | Authentication flow timed out |
| `ErrTimeout` | Interactive flow (browser, keyboard or device code) timed out |
| `ErrCallbackServer` | Localhost callback server failed |
| `ErrTokenPersist` | Token read/write failed |
| `ErrOIDCConfig` | Missing or invalid OIDC configuration |
Expand All @@ -129,7 +160,9 @@ if errors.Is(err, oidc.ErrTimeout) {

When a gateway's `metadata.json` contains `oidc_issuer` and
`oidc_client_id` fields, `Login` and `DeviceLogin` can resolve
configuration automatically:
configuration automatically. An `oidc_scopes` field (space-separated)
sets the scopes for every flow that reads the gateway, unless
`WithScopes` is set:

```go
// Login reads OIDC config from the gateway
Expand Down
29 changes: 22 additions & 7 deletions openshell/v1/oidc/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token,
if err != nil {
return nil, err
}
// Same rule as Login and DeviceLogin: a caller deadline wins, and a
// non-positive timeout means no deadline.
if _, hasDeadline := ctx.Deadline(); !hasDeadline && cfg.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cfg.timeout)
defer cancel()
}
return exchangeClientCredentials(ctx, cfg, false)
}

Expand Down Expand Up @@ -66,10 +73,7 @@ func resolveClientCredentialsConfig(opts ...LoginOption) (*loginConfig, error) {
if !cfg.audienceSet {
cfg.audience = gwCfg.OIDCAudience
}
if !cfg.scopesSet && gwCfg.OIDCScopes != "" {
cfg.scopes = strings.Fields(gwCfg.OIDCScopes)
cfg.scopesSet = true
}
cfg.applyGatewayScopes(gwCfg)
}

// Validate required configuration.
Expand All @@ -88,12 +92,23 @@ func resolveClientCredentialsConfig(opts ...LoginOption) (*loginConfig, error) {
return cfg, nil
}

// clientCredentialsError wraps ErrClientCredentials and, once ctx has ended,
// the context error too, so callers can tell a timeout or cancellation from
// a provider failure. The underlying cause is left out on purpose: it may
// carry secret material (FR-014), the context error never does.
func clientCredentialsError(ctx context.Context, msg string) error {
if ctxErr := ctx.Err(); ctxErr != nil {
return fmt.Errorf("%w: %s: %w", ErrClientCredentials, msg, ctxErr)
}
return fmt.Errorf("%w: %s", ErrClientCredentials, msg)
}

func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePositiveExpiry bool) (*oauth2.Token, error) {
secret := cfg.clientSecret
if cfg.secretProvider != nil {
value, err := cfg.secretProvider(ctx)
if err != nil {
return nil, fmt.Errorf("%w: client secret provider failed", ErrClientCredentials)
return nil, clientCredentialsError(ctx, "client secret provider failed")
}
secret = value
}
Expand Down Expand Up @@ -135,14 +150,14 @@ func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePos
}
resp, err := noRedirectClient.Do(req)
if err != nil {
return nil, fmt.Errorf("%w: token request failed", ErrClientCredentials)
return nil, clientCredentialsError(ctx, "token request failed")
}
defer func() { _ = resp.Body.Close() }()

const maxResponseBytes = 1 << 20
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1))
if err != nil {
return nil, fmt.Errorf("%w: failed to read token response", ErrClientCredentials)
return nil, clientCredentialsError(ctx, "failed to read token response")
}
if len(body) > maxResponseBytes {
return nil, fmt.Errorf("%w: token response is too large", ErrClientCredentials)
Expand Down
11 changes: 10 additions & 1 deletion openshell/v1/oidc/credentials_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,16 @@ func (a *clientCredentialsAuth) accessTokenForExchange() (string, error) {
return accessToken, nil
}

exchangeCtx, cancel := context.WithTimeout(context.Background(), a.cfg.timeout)
// The exchange is detached from caller contexts on purpose, so no caller
// can cancel it. Always bound it, or a secret provider that blocks would
// hold the singleflight key forever and wedge every later request. A
// non-positive timeout falls back to the default here instead of meaning
// "no deadline" as it does for the caller-driven flows.
timeout := a.cfg.timeout
if timeout <= 0 {
timeout = defaultTimeout
}
exchangeCtx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
token, err := exchangeClientCredentials(exchangeCtx, a.cfg, true)
if err != nil {
Expand Down
Loading
Loading