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
- Variables
- func DiscoverResource(ctx context.Context, hc *http.Client, baseURL string) string
- func GenerateState() (string, error)
- func Headless(getenv func(string) string) bool
- func Listen() (net.Listener, string, error)
- func NegotiateScopes(preferred, supported, override []string) []string
- func OpenBrowser(rawURL string) error
- func Register(ctx context.Context, hc *http.Client, registrationEndpoint, redirectURI string, ...) (string, error)
- type AuthzError
- type BrowserOpener
- type CodeExchange
- type Flow
- type Metadata
- type PKCE
- type ProtectedResource
- type Refresher
- type Token
Constants ¶
const PKCEMethod = "S256"
PKCEMethod is the only code challenge method the server accepts.
Variables ¶
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.
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.
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 ¶
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 ¶
GenerateState creates a random anti-CSRF state nonce.
func Headless ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
type PKCE ¶
PKCE holds a generated verifier/challenge pair.
func GeneratePKCE ¶
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.
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 ¶
ExchangeCode swaps an authorization code for tokens (with PKCE verifier and RFC 8707 resource indicator).