oauth

package
v1.20210819.9 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2021 License: MIT Imports: 21 Imported by: 4

Documentation

Overview

Package oauth implements some helper wrappers ontop of the existing google implementation of oauth.

Index

Constants

View Source
const (
	// GoogleKeysURL is the url we fetch google's public verification keys in JWK form.
	GoogleKeysURL = "https://www.googleapis.com/oauth2/v3/certs"
	// GoogleIssuer is the expected `iss` field on JWTs from google.
	GoogleIssuer = "https://accounts.google.com"
	// GoogleIssuerAlternate is the alternate expected `iss` field on JWTs from google.
	GoogleIssuerAlternate = "accounts.google.com"
)

Variables

View Source
var (
	// DefaultScopes is the default oauth scopes.
	DefaultScopes = []string{
		"openid",
		"email",
		"profile",
	}
)

Functions

func MustSerializeState added in v1.20201204.1

func MustSerializeState(state State) string

MustSerializeState serializes a state value but panics if there is an error.

func SerializeState

func SerializeState(state State) (output string, err error)

SerializeState serializes the oauth state.

Types

type Any

type Any = interface{}

Any is a loose type alias to interface{}

type Config

type Config struct {
	// Secret is an encryption key used to verify oauth state.
	Secret string `json:"secret,omitempty" yaml:"secret,omitempty" env:"OAUTH_SECRET"`
	// RedirectURI is the oauth return url.
	RedirectURI string `json:"redirectURI,omitempty" yaml:"redirectURI,omitempty" env:"OAUTH_REDIRECT_URI"`
	// HostedDomain is a specific domain we want to filter identities to.
	HostedDomain string `json:"hostedDomain,omitempty" yaml:"hostedDomain,omitempty" env:"OAUTH_HOSTED_DOMAIN"`
	// AllowedDomains is a strict list of hosted domains to allow authenticated users from.
	// If it is unset or empty, it will allow users from *any* hosted domain.
	AllowedDomains []string `json:"allowedDomains,omitempty" yaml:"allowedDomains,omitempty"`
	// Scopes are oauth scopes to request.
	Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
	// ClientID is part of the oauth credential pair.
	ClientID string `json:"clientID,omitempty" yaml:"clientID,omitempty" env:"OAUTH_CLIENT_ID"`
	// ClientSecret is part of the oauth credential pair.
	ClientSecret string `json:"clientSecret,omitempty" yaml:"clientSecret,omitempty" env:"OAUTH_CLIENT_SECRET"`
}

Config is the config options.

func (Config) DecodeSecret added in v1.20201204.1

func (c Config) DecodeSecret() ([]byte, error)

DecodeSecret decodes the secret if set from base64 encoding.

func (Config) IsZero

func (c Config) IsZero() bool

IsZero returns if the config is set or not.

func (*Config) Resolve added in v1.20201204.1

func (c *Config) Resolve(ctx context.Context) error

Resolve adds extra steps to perform during `configutil.Read(...)`.

func (Config) ScopesOrDefault added in v1.20201204.1

func (c Config) ScopesOrDefault() []string

ScopesOrDefault gets oauth scopes to authenticate with or a default set of scopes.

type Error

type Error string

Error is an error string.

const (
	// ErrCodeMissing is returned if the code was missing from an oauth return request.
	ErrCodeMissing Error = "state missing from request"
	// ErrStateMissing is returned if the state was missing from an oauth return request.
	ErrStateMissing Error = "state missing from request"
	// ErrInvalidHostedDomain is an error returned if the JWT hosted zone doesn't match any of the whitelisted domains.
	ErrInvalidHostedDomain Error = "hosted domain validation failed"
	// ErrInvalidAntiforgeryToken is an error returns on oauth finish that indicates we didn't originate the auth request.
	ErrInvalidAntiforgeryToken Error = "invalid anti-forgery token"

	// ErrInvalidJWTAudience is an error in validing the token jwt.
	ErrInvalidJWTAudience Error = "invalid jwt audience; should match clientID"
	// ErrInvalidJWTIssuer is an error in validing the token jwt.
	ErrInvalidJWTIssuer Error = "invalid jwt issuer; should be a valid google issuer"
	// ErrInvalidJWTHostedDomain is an error in validing the token jwt.
	ErrInvalidJWTHostedDomain Error = "invalid jwt hosted domain; must be in the allowed domain list"
	// ErrInvalidJWT is returned when we fail to decode or verify the token jwt.
	ErrInvalidJWT Error = "invalid jwt; failed to decode or verify"

	// ErrProfileJSONUnmarshal is an error returned if the json unmarshal failed.
	ErrProfileJSONUnmarshal Error = "profile json unmarshal failed"

	// ErrFailedCodeExchange happens if the code exchange for an access token fails.
	ErrFailedCodeExchange Error = "oauth code exchange failed"
	// ErrGoogleResponseStatus is an error that can occur when querying the google apis.
	ErrGoogleResponseStatus Error = "google returned a non 2xx response"

	// ErrSecretRequired is a configuration error indicating we did not provide a secret.
	ErrSecretRequired Error = "manager secret required"
	// ErrClientIDRequired is a self validation error.
	ErrClientIDRequired Error = "clientID is required"
	// ErrClientSecretRequired is a self validation error.
	ErrClientSecretRequired Error = "clientSecret is required"
	// ErrRedirectURIRequired is a self validation error.
	ErrRedirectURIRequired Error = "redirectURI is required"
	// ErrInvalidRedirectURI is an error in validating the redirect uri.
	ErrInvalidRedirectURI Error = "invalid redirectURI"
)

func (Error) Error

func (e Error) Error() string

Error returns the error as a string.

type GoogleClaims added in v1.20201204.1

type GoogleClaims struct {
	jwt.StandardClaims

	Email         string `json:"email"`
	EmailVerified string `json:"email-verified"`
	HD            string `json:"hd"`
	Nonce         string `json:"nonce"`

	FamilyName string `json:"family_name"`
	GivenName  string `json:"given_name"`
	Locale     string `json:"locale"`
	Picture    string `json:"picture"`
	Profile    string `json:"profile"`
}

GoogleClaims are extensions to the jwt standard claims for google oauth.

See additional documentation here: https://developers.google.com/identity/sign-in/web/backend-auth

func ParseTokenJWT added in v1.20201204.1

func ParseTokenJWT(tok *oauth2.Token, keyfunc jwt.Keyfunc) (*GoogleClaims, error)

ParseTokenJWT parses a jwt from a given oauth2 token.

type Labels

type Labels = map[string]string

Labels is a loose type alias to map[string]string

type Manager

type Manager struct {
	oauth2.Config
	Tracer Tracer

	Secret []byte

	HostedDomain   string
	AllowedDomains []string

	FetchProfileDefaults []r2.Option
	PublicKeyCache       *PublicKeyCache
}

Manager is the oauth manager.

func MustNew added in v1.20201204.1

func MustNew(options ...Option) *Manager

MustNew returns a new manager mutated by a given set of options and will panic on error.

func New

func New(options ...Option) (*Manager, error)

New returns a new manager mutated by a given set of options.

func (*Manager) CreateState

func (m *Manager) CreateState(options ...StateOption) (state State)

CreateState creates auth state.

func (*Manager) FetchProfile

func (m *Manager) FetchProfile(ctx context.Context, accessToken string) (profile Profile, err error)

FetchProfile gets a google profile for an access token.

func (*Manager) Finish

func (m *Manager) Finish(r *http.Request) (result *Result, err error)

Finish processes the returned code, exchanging for an access token, and fetches the user profile.

func (*Manager) OAuthURL

func (m *Manager) OAuthURL(r *http.Request, stateOptions ...StateOption) (oauthURL string, err error)

OAuthURL is the auth url for google with a given clientID. This is typically the link that a user will click on to start the auth process.

func (*Manager) ValidateJWT added in v1.20201204.1

func (m *Manager) ValidateJWT(jwtClaims *GoogleClaims) error

ValidateJWT returns if the jwt is valid or not.

func (*Manager) ValidateState

func (m *Manager) ValidateState(state State) error

ValidateState validates oauth state.

type Option added in v1.20201204.1

type Option func(*Manager) error

Option is an option for oauth managers.

func OptAllowedDomains added in v1.20201204.1

func OptAllowedDomains(allowedDomains ...string) Option

OptAllowedDomains sets the manager allowedDomains.

func OptClientID added in v1.20201204.1

func OptClientID(cliendID string) Option

OptClientID sets the manager cliendID.

func OptClientSecret added in v1.20201204.1

func OptClientSecret(clientSecret string) Option

OptClientSecret sets the manager clientSecret.

func OptConfig added in v1.20201204.1

func OptConfig(cfg Config) Option

OptConfig sets a manager based on a config.

func OptHostedDomain added in v1.20201204.1

func OptHostedDomain(hostedDomain string) Option

OptHostedDomain sets the manager hostedDomain.

func OptRedirectURI added in v1.20201204.1

func OptRedirectURI(redirectURI string) Option

OptRedirectURI sets the manager redirectURI.

func OptScopes added in v1.20201204.1

func OptScopes(scopes ...string) Option

OptScopes sets the manager scopes.

func OptSecret added in v1.20201204.1

func OptSecret(secret []byte) Option

OptSecret sets the manager secret.

func OptTracer added in v1.20201204.1

func OptTracer(tracer Tracer) Option

OptTracer sets the manager tracer.

type Profile

type Profile struct {
	ID            string `json:"id"`
	Email         string `json:"email"`
	VerifiedEmail bool   `json:"verified_email"`
	Name          string `json:"name"`
	GivenName     string `json:"given_name"`
	FamilyName    string `json:"family_name"`
	Link          string `json:"link"`
	Gender        string `json:"gender"`
	Locale        string `json:"locale"`
	PictureURL    string `json:"picture"`
}

Profile is a profile with google.

func (Profile) Username

func (p Profile) Username() string

Username returns the <username>@fqdn component of the email address.

type PublicKeyCache added in v1.20201204.1

type PublicKeyCache struct {
	FetchPublicKeysDefaults []r2.Option
	// contains filtered or unexported fields
}

PublicKeyCache holds cached signing certs.

func (*PublicKeyCache) FetchPublicKeys added in v1.20210615.7

func (pkc *PublicKeyCache) FetchPublicKeys(ctx context.Context, opts ...r2.Option) (*PublicKeysResponse, error)

FetchPublicKeys gets the google signing certs.

func (*PublicKeyCache) Get added in v1.20201204.1

func (pkc *PublicKeyCache) Get(ctx context.Context, id string) (*rsa.PublicKey, error)

Get gets a cert by id.

func (*PublicKeyCache) Keyfunc added in v1.20201204.1

func (pkc *PublicKeyCache) Keyfunc(ctx context.Context) jwt.Keyfunc

Keyfunc returns a jwt keyfunc for a specific exchange tied to context.

type PublicKeysResponse added in v1.20201204.1

type PublicKeysResponse struct {
	CacheControl string
	Expires      time.Time
	Keys         map[string]jwt.JWK
}

PublicKeysResponse is a response for the google certs api.

func (PublicKeysResponse) IsExpired added in v1.20201204.1

func (pkr PublicKeysResponse) IsExpired() bool

IsExpired returns if the cert response is expired.

type Response

type Response struct {
	AccessToken  string
	TokenType    string
	RefreshToken string
	Expiry       time.Time
	HostedDomain string
}

Response is the response details from the oauth exchange.

type Result

type Result struct {
	Response Response
	Profile  Profile
	State    State
}

Result is the final result of the oauth exchange. It is the user profile of the user and the state information.

type State

type State struct {
	// Token is a plaintext random token.
	Token string
	// SecureToken is the hashed version of the token.
	// If a key is set, it validates that our app created the oauth state.
	SecureToken string
	// RedirectURI is the redirect uri.
	RedirectURI string
	// Extra includes other state you might need to encode.
	Extra map[string]interface{}
}

State is the oauth state.

func DeserializeState

func DeserializeState(raw string) (state State, err error)

DeserializeState deserializes the oauth state.

type StateOption added in v1.20201204.1

type StateOption func(*State)

StateOption is an option for state objects

func OptStateExtra added in v1.20201204.1

func OptStateExtra(key string, value interface{}) StateOption

OptStateExtra sets the redirect uri on the stae.

func OptStateRedirectURI added in v1.20201204.1

func OptStateRedirectURI(redirectURI string) StateOption

OptStateRedirectURI sets the redirect uri on the stae.

func OptStateSecureToken added in v1.20201204.1

func OptStateSecureToken(secureToken string) StateOption

OptStateSecureToken sets the secure token on the state.

type TraceFinisher

type TraceFinisher interface {
	Finish(context.Context, *oauth2.Config, *Result, error)
}

TraceFinisher is a finisher for a trace.

type Tracer

type Tracer interface {
	Start(context.Context, *oauth2.Config) TraceFinisher
}

Tracer is a trace shim.

type Values

type Values = map[string]interface{}

Values is a loose type alias to map[string]interface{}

Jump to

Keyboard shortcuts

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