Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 18 additions & 4 deletions docs/src/api/gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,23 @@ type Info struct {
| `""` or `"none"` | `AuthModeNone` | `v1.NoAuth()` |
| `"plaintext"` | `AuthModePlaintext` | `v1.NoAuth()` + insecure TLS |
| `"cloudflare_jwt"` | `AuthModeCloudflareJWT` | Lazy edge token auth |
| `"oidc"` | `AuthModeOIDC` | `v1.RefreshableToken` that reads `oidc_token.json` near expiry and fails once the token has expired |
| `"oidc"` | `AuthModeOIDC` | `v1.RefreshableToken` that reads `oidc_token.json` near expiry and renews the token with its refresh token |
| `"mtls"` | `AuthModeMTLS` | Unsupported (use `WithAuth`) |

With `AuthModeCloudflareJWT`, the SDK rereads the edge token file on each request, so a token refreshed by `openshell gateway login` takes effect without a restart. Keep the token file readable.

With `AuthModeOIDC`, the SDK renews the token in `oidc_token.json` with its refresh token when the token is within 30 seconds of expiry, as the CLI does, and rewrites the file in the CLI's format (owner-only on Unix), so the CLI and other SDKs pick up a rotated refresh token. For tokens valid for less than a minute, renewal starts at half the token's lifetime once the client has renewed one. Renewal needs `oidc_issuer` and `oidc_client_id` in `metadata.json` and a token issued for them; tokens without a refresh token or an expiry are not renewed. The SDK sends `oidc_scopes` with `openid` first, or no scope when `oidc_scopes` is not set.

RPCs that find the token due while it has not expired wait for the renewal until 2 seconds after it started, then send the current token and let the renewal finish in the background. An RPC with a deadline waits at most half the time it has left and then sends the token the client already holds; if the client holds none yet, the RPC fails with DeadlineExceeded when its deadline ends first. If renewal fails while the token is still usable, the source returns that token to the client and waits at least 5 seconds before trying again. Returning a usable token resets the client's backoff.

An RPC that finds the token expired, or sees it expire while waiting, waits for the renewal, at most 30 seconds for the lock and discovery and then for each token request. If the renewal fails, the RPC fails as described in [Error Handling](#error-handling), with the reason in the message, such as the provider's error code or HTTP status, and later RPCs retry with the client's backoff of 1 second, doubling up to 30 seconds; in between, they fail at once with the last error. Every failed renewal also goes to the logger set with `gateway.WithLogger`.

If a renewed token cannot be written, for example on a full disk, the client keeps it in memory and uses it, since a provider that rotates refresh tokens has already revoked the one in the file, and the write error goes to the logger. The next renewal writes it first. While that write fails and the refresh token was rotated, renewals send no token request, because a provider may end the session when it sees a revoked refresh token; the client then works until the token expires. A login or a token written by another process replaces it.

A renewal is not tied to the client: closing the client does not stop it, and a renewal still running when the process exits is cut off. With a provider that rotates refresh tokens, the stored refresh token may then no longer work. A process killed while it writes the file can leave a `.oidc-token-*` temporary file in the gateway directory.

The SDK does not lock `oidc_token.json` against other processes, as the CLI and the Python SDK do not. With a provider that rotates refresh tokens, two processes that renew at the same moment spend the same refresh token, and one gets `invalid_grant`. It uses the token the other wrote if that is already in the file, and otherwise fails that renewal and picks the token up on a later one. A provider that revokes all tokens of a session on refresh token reuse ends the session instead.

The SDK tries `edge_token` first and falls back to the legacy `cf_token` only when `edge_token` is absent. Logout takes effect for a running client once neither token file remains. Removing only `edge_token` still permits authentication if a legacy `cf_token` remains.

### ClientOption
Expand All @@ -153,15 +165,17 @@ if errors.Is(err, gateway.ErrGatewayNotFound) {
```

Tokens load lazily, so `NewClient` does not return `ErrTokenLoad`. For `oidc`
gateways, a missing, malformed, or expired `oidc_token.json` surfaces on RPCs as
gateways, a missing, malformed, or expired `oidc_token.json`, or a failed renewal
of an expired token, surfaces on RPCs as
an error for which `v1.IsUnauthenticated(err)` is true, and its message includes
``run `openshell gateway login <name>` ``.
``run `openshell gateway login <name>` ``. An RPC whose context ends while it
waits for the renewal fails with DeadlineExceeded or Canceled instead.

| Error | Meaning |
|-------|---------|
| `ErrGatewayNotFound` | No gateway directory in user or system paths |
| `ErrConfigParse` | metadata.json missing or malformed |
| `ErrTokenLoad` | Token file missing, unreadable, malformed, or expired; RPCs report it as Unauthenticated |
| `ErrTokenLoad` | Token file missing, unreadable, malformed, or expired, or an expired OIDC token could not be renewed; RPCs report it as Unauthenticated |
| `ErrUnsupportedAuthMode` | Unrecognized auth_mode value |
| `ErrInvalidGatewayName` | Name fails validation |
| `ErrNoActiveGateway` | No active gateway configured |
Expand Down
160 changes: 121 additions & 39 deletions openshell/v1/auth_refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import (

"golang.org/x/oauth2"
"golang.org/x/sync/singleflight"
"google.golang.org/grpc/status"

"github.com/ai-openshell/sdk-go/openshell/v1/internal/oidctoken"
"github.com/ai-openshell/sdk-go/openshell/v1/internal/options"
"github.com/ai-openshell/sdk-go/openshell/v1/types"
)
Expand Down Expand Up @@ -69,6 +71,33 @@ type refreshableAuth struct {
lastErr error
}

// refreshWaitError is returned when a call's context ends while it waits for
// a refresh and no cached token is usable. It wraps the context's error
// and carries the matching gRPC status, so the call fails with
// DeadlineExceeded or Canceled rather than Unauthenticated.
type refreshWaitError struct{ err error }

func (e refreshWaitError) Error() string {
return "openshell: waiting for a token refresh: " + e.err.Error()
}

func (e refreshWaitError) Unwrap() error { return e.err }

func (e refreshWaitError) GRPCStatus() *status.Status {
return status.New(status.FromContextError(e.err).Code(), e.Error())
}

// cached returns the authorization metadata for the cached token if it
// has not expired.
func (r *refreshableAuth) cached() (map[string]string, bool) {
r.mu.Lock()
defer r.mu.Unlock()
if !r.usableCached() {
return nil, false
}
return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, true
}

// usableCached reports whether the cached token has not yet expired.
// Callers must hold r.mu.
func (r *refreshableAuth) usableCached() bool {
Expand All @@ -82,7 +111,13 @@ func (r *refreshableAuth) isTokenValid() bool {
if r.tok.Expiry.IsZero() {
return true
}
return time.Now().Before(r.tok.Expiry.Add(-r.leeway))
leeway := r.leeway
if source, ok := r.source.(interface {
RefreshWindow() oidctoken.RefreshWindow
}); ok {
leeway = time.Duration(source.RefreshWindow())
}
return time.Now().Before(r.tok.Expiry.Add(-leeway))
}

func (r *refreshableAuth) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) {
Expand All @@ -103,58 +138,98 @@ func (r *refreshableAuth) GetRequestMetadata(ctx context.Context, _ ...string) (
r.mu.Unlock()
return nil, err
}
usable := r.usableCached()
r.mu.Unlock()

resultCh := r.group.DoChan("refresh", func() (any, error) {
return r.source.Token()
tok, err := r.source.Token()
Comment thread
rhuss marked this conversation as resolved.
Resolved
if err == nil && tok == nil {
err = errNilToken
}
// Record the outcome here rather than in the callers: with a
// deadline, every caller may have stopped waiting for it.
r.record(tok, err)
return tok, err
})

// A cached token that has not expired is still good for this call, so
// a call with a deadline waits for the refresh for at most half the
// time it has left and keeps the rest for the call itself. The refresh
// keeps running, and its outcome is recorded for later calls.
var giveUp <-chan time.Time
if deadline, ok := ctx.Deadline(); ok && usable {
timer := time.NewTimer(time.Until(deadline) / 2)
defer timer.Stop()
giveUp = timer.C
}
var val any
var err error
select {
case <-ctx.Done():
return nil, ctx.Err()
case result := <-resultCh:
val = result.Val
err = result.Err
wait:
for {
select {
case <-ctx.Done():
if md, ok := r.cached(); ok {
return md, nil
}
return nil, refreshWaitError{ctx.Err()}
case <-giveUp:
if md, ok := r.cached(); ok {
return md, nil
}
giveUp = nil
case result := <-resultCh:
val = result.Val
err = result.Err
break wait
}
}

r.mu.Lock()
defer r.mu.Unlock()

if err != nil {
if r.nextRetry.IsZero() || !time.Now().Before(r.nextRetry) {
bo := r.backoff
if bo == 0 {
bo = initialBackoff
} else {
bo *= 2
if bo > maxBackoff {
bo = maxBackoff
}
}
r.backoff = bo
r.nextRetry = time.Now().Add(bo)
if md, ok := r.cached(); ok {
return md, nil
}
r.lastErr = err
return nil, err
}
return map[string]string{"authorization": "Bearer " + val.(*oauth2.Token).AccessToken}, nil
}

if r.usableCached() {
if r.logger != nil {
r.logger.Error(err, "token refresh failed, using cached token")
// errNilToken is recorded when the source returns neither a token nor an
// error.
var errNilToken = errors.New("openshell: token source returned nil token without error")

// record stores a token or advances backoff on failure. A source that
// returns a still-valid token with no error resets this backoff and owns
// any cooldown for retries it makes. A failure with a usable cached token
// is logged once.
func (r *refreshableAuth) record(tok *oauth2.Token, err error) {
r.mu.Lock()
if err == nil {
r.tok = tok
r.backoff = 0
r.nextRetry = time.Time{}
r.lastErr = nil
r.mu.Unlock()
return
}
if r.nextRetry.IsZero() || !time.Now().Before(r.nextRetry) {
bo := r.backoff
if bo == 0 {
bo = initialBackoff
} else {
bo *= 2
if bo > maxBackoff {
bo = maxBackoff
}
return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, nil
}
return nil, err
r.backoff = bo
r.nextRetry = time.Now().Add(bo)
}

tok, ok := val.(*oauth2.Token)
if !ok || tok == nil {
return nil, errors.New("openshell: token source returned nil token without error")
r.lastErr = err
logIt := r.logger != nil && r.usableCached()
r.mu.Unlock()
if logIt {
r.logger.Error(err, "token refresh failed, using cached token")
}
r.tok = tok
r.backoff = 0
r.nextRetry = time.Time{}
r.lastErr = nil
return map[string]string{"authorization": "Bearer " + r.tok.AccessToken}, nil
}

func (r *refreshableAuth) RequireTransportSecurity() bool {
Expand All @@ -166,7 +241,14 @@ func (r *refreshableAuth) RequireTransportSecurity() bool {
// in-flight refresh via singleflight. Failed refreshes trigger exponential
// backoff (1s, 2s, 4s, ..., 30s cap) to avoid amplifying token endpoint outages.
// After a failed refresh, the cached token is used only until it expires;
// after that, requests fail with the last refresh error.
// after that, requests fail with the last refresh error. A source that
// returns neither a token nor an error is treated as a failed refresh.
// While a refresh runs and the cached token has not expired, a request with a deadline
// waits for the refresh for at most half the time it has left, then uses
// the cached token. A request whose context ends while it waits uses the
// cached token if it has not expired, and otherwise fails with an error
// that wraps the context's error and that gRPC reports as DeadlineExceeded
// or Canceled.
func RefreshableToken(src oauth2.TokenSource, opts ...RefreshOption) (AuthProvider, error) {
if src == nil {
return nil, errNilTokenSource
Expand Down
Loading