oauth

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oauth implements the interactive OAuth 2.1 browser login flow against VibeXP's embedded authorization server: RFC 8414 discovery, RFC 7591 dynamic client registration, authorization-code + PKCE (S256) over a loopback callback, RFC 8707 resource-indicated token exchange, and transparent rotating refresh serialized across processes with a file lock.

Index

Constants

View Source
const PKCEMethod = "S256"

PKCEMethod is the only code challenge method the server accepts.

Variables

View Source
var ErrInvalidGrant = errors.New("refresh token rejected (expired or already used)")

ErrInvalidGrant is returned when the authorization server rejects a refresh token (expired, revoked, or a rotation-reuse detection). Callers should wipe the stored session and prompt re-login.

View Source
var ErrNoAuthServer = errors.New("no OAuth authorization server on this deployment")

ErrNoAuthServer indicates the deployment does not expose an OAuth authorization server (discovery endpoint missing) — callers should fall back to API-key guidance.

View Source
var ErrReauthRequired = errors.New("session expired; run 'vibexp auth login' to sign in again")

ErrReauthRequired signals that the stored OAuth session cannot be renewed (refresh token expired, revoked, or reuse-detected) and the user must run `vibexp auth login` again. Commands map this to exit code 4.

Functions

func DiscoverResource

func DiscoverResource(ctx context.Context, hc *http.Client, baseURL string) string

DiscoverResource best-effort fetches the protected-resource identifier to use as the RFC 8707 `resource` value. On any failure it returns the trimmed base URL, a sensible default.

func GenerateState

func GenerateState() (string, error)

GenerateState creates a random anti-CSRF state nonce.

func Headless

func Headless(getenv func(string) string) bool

Headless reports whether the environment has no usable browser (so the CLI should fail fast toward API-key auth). VIBEXP_NO_BROWSER forces headless.

func Listen

func Listen() (net.Listener, string, error)

Listen binds a single-use loopback callback listener on a random port and returns it along with the redirect URI to register and authorize against.

func NegotiateScopes

func NegotiateScopes(preferred, supported, override []string) []string

NegotiateScopes decides which scopes to request on the authorization request.

An explicit override (from a flag or env var) wins outright and is returned verbatim (trimmed and de-duplicated) — it is the escape hatch for deployments whose authorization server uses non-standard scope names that negotiation could not discover.

Otherwise the result is the intersection of the CLI's preferred scopes with the server-advertised scopes_supported (RFC 8414), preserving preferred order. This means an unadvertised scope is never requested — some authorization servers reject an unknown scope with invalid_scope.

When nothing preferred is advertised but the server does advertise scopes, the full advertised set is requested instead of nothing. A scope-enforcing authorization server that advertises only non-preferred scopes (e.g. ["read","write"]) would otherwise get an empty request — and an empty scope declared at registration — so browser login could never succeed there. The server-advertised set is a safe superset to request and to declare at DCR.

An empty result (the server advertises nothing) tells the flow to omit the scope parameter entirely.

func OpenBrowser

func OpenBrowser(rawURL string) error

OpenBrowser opens rawURL in the platform's default browser. The launcher is invoked by absolute path (never resolved through $PATH) so a hijacked PATH cannot substitute the browser opener.

func Register

func Register(ctx context.Context, hc *http.Client, registrationEndpoint, redirectURI string, scopes []string) (string, error)

Register performs RFC 7591 dynamic client registration for a public client and returns the issued client_id. The scopes the client intends to request are declared as the RFC 7591 `scope` field so a scope-enforcing authorization server grants them to this client; an empty set omits the field.

Types

type AuthzError

type AuthzError struct {
	Code        string
	Description string
}

AuthzError is an RFC 6749 §4.1.2.1 error delivered on the authorization callback (`?error=…&error_description=…`). Callers branch on Code; the message keeps the historical wording.

func (*AuthzError) Error

func (e *AuthzError) Error() string

type BrowserOpener

type BrowserOpener func(rawURL string) error

BrowserOpener opens a URL in the user's browser. Injectable for tests and for the login command's manual-URL fallback.

type CodeExchange

type CodeExchange struct {
	TokenEndpoint string
	ClientID      string
	Code          string
	Verifier      string // PKCE code_verifier
	RedirectURI   string
	Resource      string // RFC 8707 resource indicator; empty omits it
	// RequestedScopes are the scopes the authorization request carried. They
	// are the RFC 6749 §5.1 fallback for Token.Scopes when the token response
	// omits `scope`.
	RequestedScopes []string
}

CodeExchange describes one authorization-code exchange. It is a struct rather than a parameter list because the call carries seven interchangeable strings, and at that width a transposed pair (redirect_uri and resource, say) compiles cleanly and fails only against a live server.

type Flow

type Flow struct {
	HTTPClient  *http.Client
	Meta        *Metadata
	ClientID    string
	RedirectURI string
	Resource    string
	Scopes      []string
	OpenBrowser BrowserOpener
	Listener    net.Listener
	Timeout     time.Duration

	// Notify, when set, receives short user-facing notices — currently only the
	// warning before the no-scope retry reopens the browser. Nil is a no-op, so
	// the package stays usable without a printer.
	Notify func(string)
	// contains filtered or unexported fields
}

Flow runs the authorization-code + PKCE leg over a pre-bound loopback listener.

func (*Flow) Run

func (f *Flow) Run(ctx context.Context) (*Token, error)

Run drives the browser authorization and exchanges the returned code for tokens. It always closes the listener.

An `invalid_scope` callback gets exactly one retry with the scope parameter omitted, letting the authorization server apply its own default grant. The retry reuses the same listener, port, redirect URI and client_id — the redirect URI is pinned by the dynamic client registration, so re-binding would mean re-registering — but generates a fresh state nonce and PKCE pair. A callback arriving for the abandoned first attempt is ignored (neutral page, nothing delivered) rather than treated as CSRF, so reloading the stale browser tab cannot abort the retry.

type Metadata

type Metadata struct {
	Issuer                string   `json:"issuer"`
	AuthorizationEndpoint string   `json:"authorization_endpoint"`
	TokenEndpoint         string   `json:"token_endpoint"`
	RegistrationEndpoint  string   `json:"registration_endpoint"`
	ScopesSupported       []string `json:"scopes_supported"`
}

Metadata is the subset of RFC 8414 authorization-server metadata the flow needs.

func Discover

func Discover(ctx context.Context, hc *http.Client, baseURL string) (*Metadata, error)

Discover fetches RFC 8414 authorization-server metadata for baseURL. A 404 yields ErrNoAuthServer.

type PKCE

type PKCE struct {
	Verifier  string
	Challenge string
	Method    string
}

PKCE holds a generated verifier/challenge pair.

func GeneratePKCE

func GeneratePKCE() (PKCE, error)

GeneratePKCE creates a 32-byte high-entropy verifier and its S256 challenge.

type ProtectedResource

type ProtectedResource struct {
	Resource             string   `json:"resource"`
	AuthorizationServers []string `json:"authorization_servers"`
}

ProtectedResource is the subset of RFC 9728 protected-resource metadata used to derive the RFC 8707 resource indicator.

type Refresher

type Refresher struct {
	HTTPClient    *http.Client
	Store         *cred.Store
	ContextName   string
	TokenEndpoint string
	ClientID      string
	Resource      string
	// LockPath defaults to credentials.lock beside the credential store.
	LockPath string
	// Leeway defaults to defaultLeeway.
	Leeway time.Duration
	// Now defaults to time.Now (injectable for tests).
	Now func() time.Time
}

Refresher produces valid access tokens for an OAuth context, transparently refreshing expired tokens. Refresh is serialized across concurrent processes with a file lock and persists rotated refresh tokens atomically before releasing the lock, so exactly one process refreshes.

func (*Refresher) AccessToken

func (r *Refresher) AccessToken(ctx context.Context) (string, error)

AccessToken returns a valid access token, refreshing under a cross-process lock if the stored token is expired.

type Token

type Token struct {
	AccessToken  string
	RefreshToken string
	TokenType    string
	Expiry       time.Time
	// Scopes are the scopes the authorization server actually GRANTED, from the
	// RFC 6749 §5.1 `scope` response parameter — not the ones requested. When
	// the response omits it, §5.1 defines that as "identical to the request", so
	// this falls back to the scopes that request carried. Callers persist this
	// rather than what they asked for, because a server may narrow the grant.
	Scopes []string
}

Token is a resolved token set with a computed absolute expiry.

func ExchangeCode

func ExchangeCode(ctx context.Context, hc *http.Client, ex CodeExchange) (*Token, error)

ExchangeCode swaps an authorization code for tokens (with PKCE verifier and RFC 8707 resource indicator).

func Refresh

func Refresh(ctx context.Context, hc *http.Client, tokenEndpoint, clientID, refreshToken, resource string) (*Token, error)

Refresh exchanges a refresh token for a new token set. A rotated server returns a new refresh token which callers must persist.

func (*Token) Valid

func (t *Token) Valid(now time.Time, leeway time.Duration) bool

Valid reports whether the access token is present and not within leeway of expiry at the given time. A zero Expiry is treated as non-expiring.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL