Documentation
¶
Index ¶
- Variables
- func ClientIDFromContext(ctx context.Context) (string, bool)
- func ContextWithClaims[T any](ctx context.Context, claims UserClaims[T]) context.Context
- func ContextWithClientID(ctx context.Context, clientID string) context.Context
- func EncodeSecretID(id string) string
- func GenerateSelfSignedCert(dnsNames []string, subject pkix.Name, expiresIn time.Duration) (certPEM []byte, keyPEM []byte, err error)
- func NewClient(ctx context.Context, conf oauth2.Config, visitURLCallback func(string) error, ...) (*http.Client, oauth2.TokenSource, error)
- func NewClientWithPorts(ctx context.Context, conf oauth2.Config, visitURLCallback func(string) error, ...) (*http.Client, oauth2.TokenSource, error)
- func SignToken[T any](key Key, userID, email string, extraClaims T, expiry time.Duration) (string, error)
- func TokenHTTPHandler[T any](keys Keys, secretStore SecretStore, granter Granter[T], expiry time.Duration) http.Handler
- func WithMiddleware[T any](next http.Handler, config MiddlewareConfig[T]) http.Handler
- type Authorizer
- type ClientOption
- type Granter
- type Key
- type Keys
- type MiddlewareConfig
- type ProviderClaims
- type SecretStore
- type UserClaims
Constants ¶
This section is empty.
Variables ¶
var ( // ErrForbidden is returned by Authorizer when a user's privileges do not allow // access to the underlying resource. ErrForbidden = errors.New("user is not authorized to access resource") )
Functions ¶
func ClientIDFromContext ¶ added in v1.85.1
ClientIDFromContext returns the OAuth2 client a Granter is granting for. TokenHTTPHandler sets it only after the provider's ID token was validated with that client as its audience, so it names the client the provider issued the tokens to, not merely the one the request claimed. It is absent outside of a Granter called by TokenHTTPHandler.
func ContextWithClaims ¶
ContextWithClaims returns a new Context that holds claims.
func ContextWithClientID ¶ added in v1.85.1
ContextWithClientID returns a new Context that holds clientID for ClientIDFromContext, as TokenHTTPHandler hands it to a Granter.
func EncodeSecretID ¶
EncodeSecretID encodes the given ID to be compatible with SecretStore implementations.
func GenerateSelfSignedCert ¶
func GenerateSelfSignedCert( dnsNames []string, subject pkix.Name, expiresIn time.Duration, ) (certPEM []byte, keyPEM []byte, err error)
GenerateSelfSignedCert returns a PEM‑encoded private key and a PEM‑encoded X.509 certificate that are mutually compatible.
func NewClient ¶
func NewClient( ctx context.Context, conf oauth2.Config, visitURLCallback func(string) error, opts ...ClientOption, ) (*http.Client, oauth2.TokenSource, error)
NewClient starts an oauth2 like NewClientWithPorts but will setup a callback listener on a random port. See NewClientWithPorts for more details.
func NewClientWithPorts ¶
func NewClientWithPorts( ctx context.Context, conf oauth2.Config, visitURLCallback func(string) error, tryPorts []int, opts ...ClientOption, ) (*http.Client, oauth2.TokenSource, error)
NewClientWithPorts starts a oauth2 flow with the given oaut2 config and returns an *http.Client that will refresh the token as necessary, or an error if there's an error completing the oauth2 flow.
This client can be used against WithMiddleware if configured to use a Token endpoint managed by the handler returned by TokenHTTPHandler.
Oftentimes oauth2 providers want the callback url to be in a whitelist so listening on a random port won't work. The parameter tryPorts is designed to enable users to whitelist a (hopefully long) list of known ports and pass them to this constructor.
func SignToken ¶
func SignToken[T any](key Key, userID, email string, extraClaims T, expiry time.Duration) (string, error)
SignToken creates a new JWT token with the given user, email and role claims.
func TokenHTTPHandler ¶
func TokenHTTPHandler[T any]( keys Keys, secretStore SecretStore, granter Granter[T], expiry time.Duration, ) http.Handler
TokenHTTPHandler returns a http.Handler that handles oauth2 token requests by forwarding the request to an upstream channel and intercepting an id token to associate with the returned access token. This function returns an error if the given upstreamURL could not be parsed as a url.URL.
It uses the given granter to grant extra claims to the user.
If client secret is not present in the request (i.e. PCKE) then a client secret is fetched from secretStore with the client id as the base64 encoded (url encoded, no padding) as the secret id.
func WithMiddleware ¶
WithMiddleware wraps next with a middleware that expects an oauth2 Authorization header to authenticate and extract user details to authorize a user. The Authorizer set in the config determines to what resources each user role has access to.
Types ¶
type Authorizer ¶
type Authorizer[T any] interface { Authorize(ctx context.Context, user UserClaims[T], resource string) error }
Authorizer abstract the ability to authorize a user for a resource.
func AuthorizeAll ¶
func AuthorizeAll[T any]() Authorizer[T]
AuthorizeAll returns an Authorizer that authorizes access to all resources to any user.
func FuncAuthorizer ¶
func FuncAuthorizer[T any]( fn func(context.Context, UserClaims[T], string) error, ) Authorizer[T]
FuncAuthorizer returns an authorizer that calls fn to Authorize a user.
type ClientOption ¶
type ClientOption func(*clientConfig)
ClientOption configures the OAuth2 client flow.
func WithAuthCodeOptions ¶
func WithAuthCodeOptions(opts ...oauth2.AuthCodeOption) ClientOption
WithAuthCodeOptions appends extra parameters to the authorization URL (e.g. oauth2.SetAuthURLParam("prompt", "consent")).
func WithRedirectPath ¶
func WithRedirectPath(path string) ClientOption
WithRedirectPath overrides the default callback path ("/o/oauth2/redirect") used in the redirect URL. Use this when the OAuth provider has a specific redirect URI registered (e.g. "/auth/callback").
func WithSuccessHTML ¶
func WithSuccessHTML(html string) ClientOption
WithSuccessHTML overrides the HTML body shown to the user's browser once the OAuth2 redirect handler has received the callback. The default is a plain "Success! Please close this tab." message; pass a fully-formed HTML document here to brand the page.
type Granter ¶
type Granter[T any] interface { Grant(context.Context, *ProviderClaims) (T, error) }
Granter abstracts the ability to grant claims to a user based on its userID and email.
func FuncGranter ¶
FuncGranter uses fn to satisfy Granter.
type Key ¶
type Key struct {
// contains filtered or unexported fields
}
Key is one of the signing key types used by go-jose.
func LoadPrivateKey ¶
LoadPrivateKey loads a private key from PEM/DER/JWK-encoded data.
func LoadPublicKey ¶
LoadPublicKey loads a public key from PEM/DER/JWK-encoded data.
func SymmetricKey ¶
SymmetricKey returns a symmetric Key with str set as the key.
type Keys ¶
Keys abstracts the ability to fetch signing/verification keys.
func CombineKeys ¶
CombineKeys combines a set of Keys, tipically used in calls to Verify. Sign will return the key in k.
func FetchPublicJWKS ¶
FetchPublicJWKS returns a set of Keys that are fetched over http as public jwks. This is performed in this method call and the results are cached forever or an error is returned.
func GenerateKeys ¶
GenerateKeys generates cryptographic key pair, and packages it as a set of Keys.
func StaticAsymmetricKeys ¶
StaticAsymmetricKeys returns an implementation of Keys that returns the given key pair in calls to Sign and Verify.
func StaticSymmetricKeys ¶
StaticSymmetricKeys returns an implementation of Keys that returns the given key in calls to Sign and Verify.
type MiddlewareConfig ¶
type MiddlewareConfig[T any] struct { VerifyKeys Keys Authorizer Authorizer[T] SuccessLevel log.Level FailureLevel log.Level }
MiddlewareConfig configures the middleware returned by WithMiddleware.
type ProviderClaims ¶
ProviderClaims represents the ID token claims as part of an oauth2 flow.
func ValidateProviderIDWithCertsURL ¶
func ValidateProviderIDWithCertsURL( ctx context.Context, certsURL, clientID, idToken string, ) (*ProviderClaims, error)
ValidateProviderIDWithCertsURL fetches a set of certs in JWT format from the given URL and uses them to validate the given token ID. See ValidateIDWithCerts for more details.
func ValidateProviderIDWithJWKS ¶
func ValidateProviderIDWithJWKS( ctx context.Context, jwks *jose.JSONWebKeySet, clientID, idToken string, ) *ProviderClaims
ValidateProviderIDWithJWKS verifies that the given id token is valid, with the given JWKS. We do not return the error details to avoid bubbling it up to the user by mistake.
type SecretStore ¶
type SecretStore interface {
GetSecretMetadata(ctx context.Context, ID string) (map[string]string, error)
AccessSecret(ctx context.Context, ID string) ([]byte, error)
}
SecretStore abstracts the ability to retrieve secret metadata and access secret data.
func MapSecretStore ¶
func MapSecretStore(data map[string][]byte, metadata ...string) SecretStore
MapSecretStore returns a SecretStore of secrets with metadata. The argument metadata is expected to be pairs of key values and it is returned to all secrets.
type UserClaims ¶
type UserClaims[T any] struct { jwt.Claims Email string `json:"email"` UserID string `json:"user_id"` Extra T `json:"extra"` }
UserClaims represent the user claims.
func ClaimsFromContext ¶
func ClaimsFromContext[T any](ctx context.Context) (UserClaims[T], bool)
ClaimsFromContext returns the claims value stored in ctx, if any.
func VerifyToken ¶
func VerifyToken[T any](key Key, token string) (UserClaims[T], error)
VerifyToken verifies that the given token was signed by key.