Skip to content
OpenShell
These docs are for the development version. Go to the latest released version (0.1.8).

OIDC

Package: openshell/v1/oidc

The oidc package provides OIDC authentication for OpenShell gateways. It supports four OAuth2 flows: browser-based authorization code with PKCE, keyboard fallback, device code (RFC 8628), and client credentials.

import "github.com/ai-openshell/sdk-go/openshell/v1/oidc"
// Gateway-aware login (reads OIDC config from gateway metadata)
token, err := oidc.Login(ctx, "my-gateway")
if err != nil {
log.Fatal(err)
}
Function Description
Login(ctx, gatewayName, opts...) Interactive login via browser or keyboard flow
DeviceLogin(ctx, opts...) Device authorization grant (RFC 8628)
ClientCredentials(ctx, opts...) Non-interactive client credentials grant
func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth2.Token, error)

Performs an interactive OIDC login. When gatewayName is provided, the OIDC issuer and client ID are read from the gateway’s metadata.json. The default flow opens a browser for authorization code exchange with PKCE. If the provider does not support PKCE (S256), the flow proceeds without it.

Tokens are persisted to the gateway’s config directory as oidc_token.json, in the same format as openshell gateway login, so CLI commands against that gateway can use them. Subsequent calls reuse the stored token only when it is valid and was issued for the gateway’s issuer and client ID; otherwise Login runs the flow again and rewrites the file.

For standalone use (no gateway), pass an empty gatewayName with WithIssuer and WithClientID. Combine with WithInMemory to skip disk persistence.

func DeviceLogin(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error)

Performs an OAuth2 device authorization grant (RFC 8628). The flow requests a device code and user code from the provider, displays them via WithDisplayFunc (or stdout), and polls the token endpoint until the user completes authorization.

Requires WithIssuer and WithClientID, or WithGateway.

func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error)

Performs a non-interactive OAuth2 client credentials grant. Requires WithIssuer, WithClientID, and WithClientSecret (or WithGateway combined with WithClientSecret). The client secret is never included in error messages.

func NewClientCredentialsAuth(opts ...LoginOption) (types.AuthProvider, error)

Returns a lazy renewable auth provider for v1.Config.Auth or gateway.WithAuth. It caches access tokens in memory, renews within 30 seconds of expiry, coalesces concurrent exchanges, and fails closed if renewal fails. Use WithClientSecretProvider when the application rotates secret material.

Option Description
WithIssuer(url) OIDC provider issuer URL
WithClientID(id) OAuth2 client ID
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...) Replace the default scopes (openid profile email); see Scopes
WithCallbackPort(port) Fixed port for localhost callback (default: tries 8000, then 18000)
WithTimeout(d) Flow timeout (default: 2 minutes); see 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 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.

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.

The package defines sentinel errors for errors.Is() matching:

Error Description
ErrDiscovery OIDC discovery document fetch failed
ErrAuthCode Authorization code exchange failed
ErrDeviceCode Device code flow failed
ErrClientCredentials Client credentials exchange failed
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
token, err := oidc.Login(ctx, "my-gateway")
if errors.Is(err, oidc.ErrDiscovery) {
// Provider unreachable
}
if errors.Is(err, oidc.ErrTimeout) {
// User did not complete login in time
}

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

// Login reads OIDC config from the gateway
token, err := oidc.Login(ctx, "my-gateway")
// Then use the token with the SDK client
client, err := v1.NewClient(v1.Config{
Address: "gateway.example.com:443",
Auth: v1.StaticToken(token.AccessToken),
})
  1. Discovers OIDC endpoints from issuer
  2. Generates PKCE code verifier and S256 challenge
  3. Opens browser to authorization URL
  4. Starts localhost callback server to receive the auth code
  5. Exchanges code for tokens with PKCE verification
  6. Persists tokens to disk

Same as browser flow, but prints the authorization URL for the user to copy manually. The user pastes the authorization code back into the terminal. Use WithKeyboardFlow() to enable.

  1. Requests a device code and user code from the provider
  2. Displays the verification URL and user code
  3. Polls the token endpoint at the provider’s requested interval
  4. Handles slow_down responses by increasing the poll interval
  1. Discovers OIDC endpoints from issuer
  2. Exchanges client ID and secret for an access token
  3. No user interaction required

We are a Cloud Native Computing Foundation sandbox project.