Documentation
¶
Overview ¶
Package oauthserver provides the protocol pieces of an OAuth 2.1 authorization server for third-party apps callers own storage, consent and authorization, and must give NewClientResolver a dialer that refuses non-public addresses
Index ¶
- Constants
- Variables
- func FormatScope(scopes []string) string
- func IsAccessToken(raw string) bool
- func NoStore(h http.Header)
- func ParseScope(scope string) []string
- func RedirectURL(redirectURI, issuer string, params url.Values) (string, error)
- func ResolveResource(allowed, requested []string) (string, error)
- func ResourceAllowed(allowed []string, resource string) bool
- func ResourceMetadataURL(resource string) (string, error)
- func SingleValued(form url.Values, names ...string) error
- func ValidChallenge(challenge, method string) bool
- func ValidRedirect(raw string) bool
- func VerifyPKCE(verifier, challenge string) bool
- type Client
- type ClientResolver
- type DialContextFunc
- type Metadata
- type OAuthError
- type ResolverOption
- type StoredToken
- type Token
- type TokenIssuer
- type TokenKind
- type TokenResponse
Constants ¶
const ( // ErrCodeInvalidRequest is for a malformed request or a missing or repeated parameter ErrCodeInvalidRequest = "invalid_request" // ErrCodeInvalidClient is for an unknown client or failed client authentication ErrCodeInvalidClient = "invalid_client" // ErrCodeInvalidGrant is for an invalid, expired, revoked, or reused code or refresh token ErrCodeInvalidGrant = "invalid_grant" // ErrCodeInvalidScope is for a scope that is unknown or exceeds what was granted ErrCodeInvalidScope = "invalid_scope" // ErrCodeUnsupportedGrantType is for a grant type the server does not support ErrCodeUnsupportedGrantType = "unsupported_grant_type" // ErrCodeUnsupportedResponse is for a response type the server does not support ErrCodeUnsupportedResponse = "unsupported_response_type" // ErrCodeAccessDenied is for a user denying consent ErrCodeAccessDenied = "access_denied" // ErrCodeServerError is for an unexpected failure on the server ErrCodeServerError = "server_error" // ErrCodeInvalidTarget is for a resource indicator that is missing, repeated, or not allowed (RFC 8707) ErrCodeInvalidTarget = "invalid_target" )
Standard error codes
const ( // AuthorizePath is where clients send users to approve a connection AuthorizePath = "/oauth2/authorize" // TokenPath is where clients exchange codes and refresh tokens TokenPath = "/oauth2/token" //nolint:gosec // RevokePath is where clients revoke tokens (RFC 7009) RevokePath = "/oauth2/revoke" // MetadataPath is the RFC 8414 well-known path of the metadata document MetadataPath = "/.well-known/oauth-authorization-server" )
Endpoint paths served by the authorization server, unversioned because clients discover them from metadata
const ( // ResponseTypeCode is the only response type, the authorization code flow ResponseTypeCode = "code" // GrantTypeAuthorizationCode exchanges an authorization code for tokens GrantTypeAuthorizationCode = "authorization_code" // GrantTypeRefreshToken exchanges a refresh token for new tokens GrantTypeRefreshToken = "refresh_token" // AuthMethodNone is the only client authentication method, since every client is public AuthMethodNone = "none" // TokenTypeBearer is the token_type of issued access tokens TokenTypeBearer = "Bearer" )
Protocol values the server supports
const ( // ParamClientID is the client's identifier ParamClientID = "client_id" // ParamRedirectURI is where the authorization response is sent ParamRedirectURI = "redirect_uri" // ParamResponseType is the requested authorization response type ParamResponseType = "response_type" // ParamCodeChallenge is the PKCE code challenge (RFC 7636) ParamCodeChallenge = "code_challenge" // ParamCodeChallengeMethod is the PKCE code challenge method (RFC 7636) ParamCodeChallengeMethod = "code_challenge_method" // ParamCodeVerifier is the PKCE code verifier (RFC 7636) ParamCodeVerifier = "code_verifier" // ParamState is the client's opaque value echoed back on the redirect ParamState = "state" // ParamScope is the space-delimited requested scopes ParamScope = "scope" // ParamResource is the resource indicator (RFC 8707) ParamResource = "resource" // ParamGrantType is the token endpoint grant type ParamGrantType = "grant_type" // ParamCode is the authorization code ParamCode = "code" // ParamRefreshToken is the refresh token ParamRefreshToken = "refresh_token" // ParamToken is the token to revoke (RFC 7009) ParamToken = "token" // ParamError is the authorization response error code ParamError = "error" // ParamIssuer is the authorization response parameter naming the issuer (RFC 9207) ParamIssuer = "iss" )
Request and response parameter names
const ( // AccessTokenPrefix prefixes access tokens AccessTokenPrefix = "tolo_" // RefreshTokenPrefix prefixes refresh tokens RefreshTokenPrefix = "tolr_" // CodePrefix prefixes authorization codes CodePrefix = "tolc_" // RequestPrefix prefixes authorization requests RequestPrefix = "tolq_" )
const ( // AccessTokenTTL is how long an access token is valid AccessTokenTTL = time.Hour // RefreshTokenTTL is how long a refresh token is valid, refresh tokens rotate on use RefreshTokenTTL = 30 * 24 * time.Hour // CodeTTL is how long an authorization code is valid CodeTTL = 5 * time.Minute // RequestTTL is how long a user has to complete the consent screen RequestTTL = 15 * time.Minute )
const MethodS256 = "S256"
MethodS256 is the only PKCE method accepted (OAuth 2.1 drops "plain")
Variables ¶
var ( // ErrDialerRequired is returned when a resolver is built without a dialer ErrDialerRequired = errors.New("a dialer that only reaches public addresses is required") // ErrInvalidClientID is returned when a client_id is not an acceptable metadata URL ErrInvalidClientID = errors.New("client_id must be an https URL with a path") // ErrClientMetadata is returned when the client metadata document can't be fetched or is invalid ErrClientMetadata = errors.New("unable to load client metadata document") // ErrInvalidRedirectURI is returned when a redirect_uri is not registered for the client ErrInvalidRedirectURI = errors.New("redirect_uri is not registered for this client") // ErrFetchRateLimited is returned when a metadata document is needed but the fetch budget is spent ErrFetchRateLimited = errors.New("metadata fetch rate limit exceeded, try again shortly") // ErrResourceMetadata is returned when a resource's protected resource metadata can't be loaded ErrResourceMetadata = errors.New("unable to load protected resource metadata") // ErrInvalidTarget is returned when a resource indicator is missing, repeated, or not allowed ErrInvalidTarget = errors.New("resource is not an allowed target") // ErrKeyringRequired is returned when the token manager has no usable API token keyring ErrKeyringRequired = errors.New("oauth tokens require an api token keyring with an active key") // ErrTokenInvalid is returned when a presented token is malformed or does not verify ErrTokenInvalid = errors.New("invalid oauth token") // ErrTokenKindMismatch is returned when a presented token's prefix doesn't match its stored record's kind ErrTokenKindMismatch = errors.New("oauth token kind does not match its stored record") // ErrInvalidTokenKind is returned when a value is not a known token kind ErrInvalidTokenKind = errors.New("invalid oauth token kind") )
var AuthorizeParams = []string{ParamClientID, ParamRedirectURI, ParamResponseType, ParamCodeChallenge, ParamCodeChallengeMethod, ParamState, ParamScope}
AuthorizeParams are the authorize endpoint parameters that must not be repeated (RFC 6749 §3.1)
var TokenParams = []string{ParamGrantType, ParamCode, ParamRedirectURI, ParamClientID, ParamCodeVerifier, ParamRefreshToken, ParamResource}
TokenParams are the token endpoint parameters that must not be repeated (RFC 6749 §3.1)
Functions ¶
func FormatScope ¶
FormatScope joins scopes into an OAuth scope parameter
func IsAccessToken ¶
IsAccessToken reports whether a bearer token is an OAuth access token
func ParseScope ¶
ParseScope splits an OAuth scope parameter (space-delimited) into a deduplicated list
func RedirectURL ¶
RedirectURL adds the non-empty params and the issuer (RFC 9207) to a client redirect URI, keeping its query
func ResolveResource ¶
ResolveResource returns the one resource a token is issued for, defaulting to the only allowed resource when none is requested
func ResourceAllowed ¶
ResourceAllowed reports whether resource exactly matches one of the allowed resource URLs
func ResourceMetadataURL ¶
ResourceMetadataURL returns a resource's RFC 9728 metadata URL, the well-known path inserted before the resource's path
func SingleValued ¶
SingleValued returns an invalid_request error when a named parameter is repeated (RFC 6749 §3.1)
func ValidChallenge ¶
ValidChallenge reports whether a code_challenge is well formed for S256
func ValidRedirect ¶
ValidRedirect reports whether a redirect URI is safe to send a browser to
func VerifyPKCE ¶
VerifyPKCE checks a code_verifier's RFC 7636 grammar and that it matches the stored S256 code_challenge
Types ¶
type Client ¶
type Client struct {
// ID is the client_id, the URL of its metadata document, whose host the consent screen must show
ID string `json:"client_id"`
// Name is shown to the user on the consent screen
Name string `json:"client_name"`
// URI is the client's home page
URI string `json:"client_uri,omitempty"`
// LogoURI is shown on the consent screen
LogoURI string `json:"logo_uri,omitempty"`
// RedirectURIs are the allowed redirect URIs
RedirectURIs []string `json:"redirect_uris"`
// TokenEndpointAuthMethod must be "none": only public clients are supported
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
}
Client is a resolved OAuth client
func (*Client) ValidateRedirectURI ¶
ValidateRedirectURI checks redirectURI against the registered list, and errors may only be redirected to a URI it accepts
type ClientResolver ¶
type ClientResolver struct {
// contains filtered or unexported fields
}
ClientResolver loads and caches client metadata documents and protected resource metadata
func NewClientResolver ¶
func NewClientResolver(dial DialContextFunc, opts ...ResolverOption) (*ClientResolver, error)
NewClientResolver returns a resolver whose metadata fetches connect through dial, which must refuse non-public addresses
func (*ClientResolver) Close ¶
func (r *ClientResolver) Close()
Close stops the resolver's cache maintenance
func (*ClientResolver) Resolve ¶
Resolve returns a copy of the client for a client_id, fetching its metadata document if needed
func (*ClientResolver) ResourceScopes ¶
ResourceScopes returns a copy of a resource's RFC 9728 scopes_supported, and callers must only pass resources ResourceAllowed accepts
type DialContextFunc ¶
DialContextFunc dials a network address, matching http.Transport.DialContext
type Metadata ¶
type Metadata struct {
// Issuer is the authorization server's identifier, which clients compare against iss
Issuer string `json:"issuer"`
// AuthorizationEndpoint is the URL of the authorize endpoint
AuthorizationEndpoint string `json:"authorization_endpoint"`
// TokenEndpoint is the URL of the token endpoint
TokenEndpoint string `json:"token_endpoint"`
// RevocationEndpoint is the URL of the revocation endpoint
RevocationEndpoint string `json:"revocation_endpoint"`
// ResponseTypesSupported lists the response types, only code
ResponseTypesSupported []string `json:"response_types_supported"`
// GrantTypesSupported lists the grant types, authorization_code and refresh_token
GrantTypesSupported []string `json:"grant_types_supported"`
// CodeChallengeMethodsSupported lists the PKCE methods, only S256
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
// TokenEndpointAuthMethodsSupported lists how clients authenticate at the token endpoint, only none for public clients
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
// RevocationEndpointAuthMethodsSupported lists how clients authenticate at the revocation endpoint, only none
RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported"`
// ScopesSupported lists the scopes clients may request
ScopesSupported []string `json:"scopes_supported,omitempty"`
// ClientIDMetadataDocumentSupported tells clients they can use a metadata document URL as their client_id
ClientIDMetadataDocumentSupported bool `json:"client_id_metadata_document_supported"`
// AuthorizationResponseIssParameterSupported tells clients the authorize response carries iss (RFC 9207)
AuthorizationResponseIssParameterSupported bool `json:"authorization_response_iss_parameter_supported"`
}
Metadata is the RFC 8414 authorization server metadata document
func NewMetadata ¶
NewMetadata builds the metadata document for an issuer serving the endpoint paths above with the given scopes
type OAuthError ¶
type OAuthError struct {
// Code is the RFC 6749 error code
Code string `json:"error"`
// Description is a human-readable explanation for the client developer
Description string `json:"error_description,omitempty"`
}
OAuthError is an RFC 6749 §5.2 error response
func ParseForm ¶
func ParseForm(r *http.Request) (url.Values, *OAuthError)
ParseForm returns a form-encoded request body, the only body format the token and revocation endpoints accept
func (*OAuthError) Status ¶
func (e *OAuthError) Status() int
Status returns the HTTP status for the error: 401 for invalid_client, 500 for server_error, and 400 otherwise
type ResolverOption ¶
type ResolverOption func(*resolverOptions)
ResolverOption configures a ClientResolver
func WithCacheSize ¶
func WithCacheSize(n int) ResolverOption
WithCacheSize bounds each metadata cache to n entries (default 1024)
func WithFetchRate ¶
func WithFetchRate(r rate.Limit, burst int) ResolverOption
WithFetchRate limits metadata fetches to each registrable domain to r per second with bursts of burst (default 1/s, burst 5)
func WithGlobalFetchRate ¶
func WithGlobalFetchRate(r rate.Limit, burst int) ResolverOption
WithGlobalFetchRate limits metadata fetches across all domains to r per second with bursts of burst (default 20/s, burst 50)
func WithInsecureClientIDs ¶
func WithInsecureClientIDs() ResolverOption
WithInsecureClientIDs accepts http client IDs for local development without changing which addresses the dialer reaches
type StoredToken ¶
type StoredToken struct {
// ID is the stored token ID
ID string
// Kind must come from the stored row, never from Lookup, or a token renamed to another kind's prefix verifies
Kind TokenKind
// Hash is the stored keyed digest
Hash string
// KeyVersion is the stored keyring version
KeyVersion string
}
StoredToken is the record a service persisted for a token
type Token ¶
type Token struct {
// Kind is what the token represents
Kind TokenKind
// ID identifies the token's stored record
ID ulid.ULID
// Value is the opaque token returned to the client
Value string
// Hash is the keyed digest to store
Hash string
// KeyVersion is the keyring version the hash was computed with, to store
KeyVersion string
// ExpiresAt is when the token stops being valid, from its kind's TTL
ExpiresAt time.Time
}
Token is a newly issued token, Value goes to the client once and only Kind, ID, Hash and KeyVersion are stored
type TokenIssuer ¶
type TokenIssuer struct {
// contains filtered or unexported fields
}
TokenIssuer issues and verifies opaque OAuth tokens with an iam/tokens API token keyring
func NewTokenIssuer ¶
func NewTokenIssuer(tm *tokens.TokenManager) (*TokenIssuer, error)
NewTokenIssuer returns an issuer backed by the token manager's API token keyring, failing if it has no active key
func (*TokenIssuer) Issue ¶
func (i *TokenIssuer) Issue(kind TokenKind) (*Token, error)
Issue returns a new token of the given kind
func (*TokenIssuer) Lookup ¶
Lookup returns the kind and ID to load a presented token's stored record by
func (*TokenIssuer) Verify ¶
func (i *TokenIssuer) Verify(raw string, stored StoredToken) error
Verify checks a presented token against its stored record, leaving expiry, single use and revocation to the caller
type TokenKind ¶
type TokenKind string
TokenKind identifies what an opaque OAuth token represents
const ( // KindRequest is a pending authorization request awaiting the user's consent KindRequest TokenKind = "REQUEST" // KindCode is a single-use authorization code KindCode TokenKind = "CODE" // KindAccess is an access token presented as a bearer token KindAccess TokenKind = "ACCESS" // KindRefresh is a refresh token exchanged at the token endpoint KindRefresh TokenKind = "REFRESH" )
func (TokenKind) MarshalGQL ¶
MarshalGQL implements the gqlgen Marshaler interface, which ent requires of enum field types
func (*TokenKind) UnmarshalGQL ¶
UnmarshalGQL implements the gqlgen Unmarshaler interface, which ent requires of enum field types
type TokenResponse ¶
type TokenResponse struct {
// AccessToken is the issued access token
AccessToken string `json:"access_token"`
// TokenType is always Bearer
TokenType string `json:"token_type"`
// ExpiresIn is the access token lifetime in seconds
ExpiresIn int64 `json:"expires_in"`
// RefreshToken is the issued refresh token
RefreshToken string `json:"refresh_token"`
// Scope is the space-delimited scopes the tokens carry
Scope string `json:"scope"`
}
TokenResponse is the RFC 6749 §5.1 token response