auth

package
v0.0.0-...-1b51d53 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2017 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const CookieName = "SyncGatewaySession"
View Source
const RoleKeyPrefix = "_sync:role:"

Key prefix reserved for role documents in the bucket

View Source
const SessionKeyPrefix = "_sync:session:"
View Source
const UserKeyPrefix = "_sync:user:"

Key prefix reserved for user documents in the bucket

Variables

This section is empty.

Functions

func CalculateRoleChannelGrant

func CalculateRoleChannelGrant(roleGrant base.VbSeq, roleChannelGrant base.VbSeq, sinceClock base.SequenceClock) (preSinceGrant bool, grantSeq base.VbSeq, secondaryTrigger base.VbSeq)

Identifies whether the specified role grant or roleChannelGrant are new to the user (occured after the specified since clock). If only one is post-since, returns that value If both are pre-since or both are post-since, returns the higher vb.seq

func GetJWTExpiry

func GetJWTExpiry(jwt jose.JWT) (expiresAt time.Time, err error)

Returns the "exp" claim (Identity.ExpiresAt) for the JWT, as a time.Time.

func GetJWTIdentity

func GetJWTIdentity(jwt jose.JWT) (identity *oidc.Identity, err error)

Extracts the JWT Identity Claims (includes ID, Email, Expiry) from a JWT.

func GetJWTIssuer

func GetJWTIssuer(jwt jose.JWT) (issuer string, audiences []string, err error)

func GetOIDCUsername

func GetOIDCUsername(provider *OIDCProvider, subject string) string

func IsValidEmail

func IsValidEmail(email string) bool

func IsValidPrincipalName

func IsValidPrincipalName(name string) bool

Is this string a valid name for a User/Role? (Valid chars are alphanumeric and any of "_-+.@")

func OIDCToHTTPError

func OIDCToHTTPError(err error) error

Converts an OpenID Connect / OAuth2 error to an HTTP error

func ValidateJWT

func ValidateJWT(idToken string, client *oidc.Client) (jose.JWT, error)

Parses and validates a JWT token, based on the client definition provided.

Types

type Authenticator

type Authenticator struct {
	// contains filtered or unexported fields
}

* Manages user authentication for a database.

func NewAuthenticator

func NewAuthenticator(bucket base.Bucket, channelComputer ChannelComputer) *Authenticator

Creates a new Authenticator that stores user info in the given Bucket.

func (*Authenticator) AuthenticateCookie

func (auth *Authenticator) AuthenticateCookie(rq *http.Request, response http.ResponseWriter) (User, error)

func (*Authenticator) AuthenticateTrustedJWT

func (auth *Authenticator) AuthenticateTrustedJWT(token string, provider *OIDCProvider, callbackURLFunc OIDCCallbackURLFunc) (User, jose.JWT, error)

Authenticates a user based on a JWT token obtained directly from a provider (auth code flow, refresh flow). Verifies the token claims, but doesn't require signature verification. If the token is validated but the user for the username defined in the subject claim doesn't exist, creates the user when autoRegister=true.

func (*Authenticator) AuthenticateUntrustedJWT

func (auth *Authenticator) AuthenticateUntrustedJWT(token string, providers OIDCProviderMap, callbackURLFunc OIDCCallbackURLFunc) (User, jose.JWT, error)

Authenticates a user based on a JWT token string and a set of providers. Attempts to match the issuer in the token with a provider. Used to authenticate a JWT token coming from an insecure source (e.g. client request) If the token is validated but the user for the username defined in the subject claim doesn't exist, creates the user when autoRegister=true.

func (*Authenticator) AuthenticateUser

func (auth *Authenticator) AuthenticateUser(username string, password string) User

Authenticates a user given the username and password. If the username and password are both "", it will return a default empty User object, not nil.

func (*Authenticator) CreateSession

func (auth *Authenticator) CreateSession(username string, ttl time.Duration) (*LoginSession, error)

func (*Authenticator) Delete

func (auth *Authenticator) Delete(p Principal) error

Deletes a user/role.

func (Authenticator) DeleteSession

func (auth Authenticator) DeleteSession(sessionid string) error

func (Authenticator) DeleteSessionForCookie

func (auth Authenticator) DeleteSessionForCookie(rq *http.Request) *http.Cookie

func (*Authenticator) GetPrincipal

func (auth *Authenticator) GetPrincipal(name string, isUser bool) (Principal, error)

func (*Authenticator) GetRole

func (auth *Authenticator) GetRole(name string) (Role, error)

Looks up the information for a role.

func (*Authenticator) GetSession

func (auth *Authenticator) GetSession(sessionid string) (*LoginSession, error)

func (*Authenticator) GetUser

func (auth *Authenticator) GetUser(name string) (User, error)

Looks up the information for a user. If the username is "" it will return the default (guest) User object, not nil. By default the guest User has access to everything, i.e. Admin Party! This can be changed by altering its list of channels and saving the changes via SetUser.

func (*Authenticator) GetUserByEmail

func (auth *Authenticator) GetUserByEmail(email string) (User, error)

Looks up a User by email address.

func (*Authenticator) InvalidateChannels

func (auth *Authenticator) InvalidateChannels(p Principal) error

Invalidates the channel list of a user/role by saving its Channels() property as nil.

func (*Authenticator) InvalidateRoles

func (auth *Authenticator) InvalidateRoles(user User) error

Invalidates the role list of a user by saving its Roles() property as nil.

func (*Authenticator) MakeSessionCookie

func (auth *Authenticator) MakeSessionCookie(session *LoginSession) *http.Cookie

func (*Authenticator) NewRole

func (auth *Authenticator) NewRole(name string, channels base.Set) (Role, error)

Creates a new Role object.

func (*Authenticator) NewUser

func (auth *Authenticator) NewUser(username string, password string, channels base.Set) (User, error)

Creates a new User object.

func (*Authenticator) RegisterNewUser

func (auth *Authenticator) RegisterNewUser(username, email string) (User, error)

Registers a new user account based on the given verified email address. Username will be the same as the verified email address. Password will be random. The user will have access to no channels.

func (*Authenticator) Save

func (auth *Authenticator) Save(p Principal) error

Saves the information for a user/role.

func (*Authenticator) UnmarshalPrincipal

func (auth *Authenticator) UnmarshalPrincipal(data []byte, defaultName string, defaultSeq uint64, isUser bool) (Principal, error)

func (*Authenticator) UnmarshalRole

func (auth *Authenticator) UnmarshalRole(data []byte, defaultName string, defaultSeq uint64) (Role, error)

func (*Authenticator) UnmarshalUser

func (auth *Authenticator) UnmarshalUser(data []byte, defaultName string, defaultSequence uint64) (User, error)

func (*Authenticator) UpdateRoleVbucketSequences

func (auth *Authenticator) UpdateRoleVbucketSequences(docID string, sequence uint64) error

func (*Authenticator) UpdateUserVbucketSequences

func (auth *Authenticator) UpdateUserVbucketSequences(docID string, sequence uint64) error

type ChannelComputer

type ChannelComputer interface {
	ComputeChannelsForPrincipal(Principal) (ch.TimedSet, error)
	ComputeRolesForUser(User) (ch.TimedSet, error)
	UseGlobalSequence() bool
}

Interface for deriving the set of channels and roles a User/Role has access to. The instantiator of an Authenticator must provide an implementation.

type JWTOptions

type JWTOptions struct {
	ValidationKey *string `json:"validation_key"`           // Key used to validate signed tokens
	SigningMethod *string `json:"signing_method,omitempty"` // Algorithm used for signing.  Can be specified for additional security to handle scenario described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
}

Config options for Json Web Token validation

type LoginSession

type LoginSession struct {
	ID         string        `json:"id"`
	Username   string        `json:"username"`
	Expiration time.Time     `json:"expiration"`
	Ttl        time.Duration `json:"ttl"`
}

A user login session (used with cookie-based auth.)

type OIDCCallbackURLFunc

type OIDCCallbackURLFunc func() string

type OIDCOptions

type OIDCOptions struct {
	Providers       OIDCProviderMap `json:"providers,omitempty"`        // List of OIDC issuers
	DefaultProvider *string         `json:"default_provider,omitempty"` // Issuer used when not specified by client
}

Options for OpenID Connect

type OIDCProvider

type OIDCProvider struct {
	JWTOptions
	Issuer                  string   `json:"issuer"`                           // OIDC Issuer
	Register                bool     `json:"register"`                         // If true, server will register new user accounts
	ClientID                *string  `json:"client_id,omitempty"`              // Client ID
	ValidationKey           *string  `json:"validation_key,omitempty"`         // Client secret
	CallbackURL             *string  `json:"callback_url,omitempty"`           // Sync Gateway redirect URL.  Needs to be specified to handle load balancer endpoints?  Or can we lazy load on first client use, based on request
	DisableSession          bool     `json:"disable_session,omitempty"`        // Disable Sync Gateway session creation on successful OIDC authentication
	Scope                   []string `json:"scope,omitempty"`                  // Scope sent for openid request
	IncludeAccessToken      bool     `json:"include_access,omitempty"`         // Whether the _oidc_callback response should include OP access token and associated fields (token_type, expires_in)
	UserPrefix              string   `json:"user_prefix,omitempty"`            // Username prefix for users created for this provider
	DiscoveryURI            string   `json:"discovery_url,omitempty"`          // Non-standard discovery endpoints
	DisableConfigValidation bool     `json:"disable_cfg_validation,omitempty"` // Bypasses config validation based on the OIDC spec.  Required for some OPs that don't strictly adhere to spec (eg. Yahoo)
	OIDCClient              *oidc.Client
	OIDCClientOnce          sync.Once
	IsDefault               bool
	Name                    string
}

func (*OIDCProvider) DiscoverConfig

func (op *OIDCProvider) DiscoverConfig() (config *oidc.ProviderConfig, shouldSync bool, err error)

func (*OIDCProvider) FetchCustomProviderConfig

func (op *OIDCProvider) FetchCustomProviderConfig(discoveryURL string) (*oidc.ProviderConfig, error)

func (*OIDCProvider) GetClient

func (op *OIDCProvider) GetClient(buildCallbackURLFunc OIDCCallbackURLFunc) *oidc.Client

func (*OIDCProvider) InitOIDCClient

func (op *OIDCProvider) InitOIDCClient() error

func (*OIDCProvider) InitUserPrefix

func (op *OIDCProvider) InitUserPrefix() error

To support multiple providers referencing the same issuer, the user prefix used to build the SG usernames for a provider is based on the issuer

type OIDCProviderMap

type OIDCProviderMap map[string]*OIDCProvider

func (OIDCProviderMap) GetDefaultProvider

func (opm OIDCProviderMap) GetDefaultProvider() *OIDCProvider

func (OIDCProviderMap) GetProviderForIssuer

func (opm OIDCProviderMap) GetProviderForIssuer(issuer string, audiences []string) *OIDCProvider

type OidcProviderConfiguration

type OidcProviderConfiguration struct {
	Issuer                 string   `json:"issuer"`
	AuthEndpoint           string   `json:"authorization_endpoint"`
	TokenEndpoint          string   `json:"token_endpoint"`
	JwksUri                string   `json:"jwks_uri"`
	UserInfoEndpoint       string   `json:"userinfo_endpoint,omitempty"`
	RegistrationEndpoint   string   `json:"registration_endpoint,omitempty"`
	ResponseTypesSupported []string `json:"response_types_supported,omitempty"`
	SubjectTypesSupported  []string `json:"subject_types_supported,omitempty"`
	ScopesSupported        []string `json:"scopes_supported,omitempty"`
	ClaimsSupported        []string `json:"claims_supported,omitempty"`

	ResponseModesSupported []string `json:"response_modes_supported,omitempty"`
	GrantTypesSupported    []string `json:"grant_types_supported,omitempty"`
	ACRValuesSupported     []string `json:"acr_values_supported,omitempty"`

	IDTokenSigningAlgValues     []string `json:"id_token_signing_alg_values_supported,omitempty"`
	IDTokenEncryptionAlgValues  []string `json:"id_token_encryption_alg_values_supported,omitempty"`
	IDTokenEncryptionEncValues  []string `json:"id_token_encryption_enc_values_supported,omitempty"`
	UserInfoSigningAlgValues    []string `json:"userinfo_signing_alg_values_supported,omitempty"`
	UserInfoEncryptionAlgValues []string `json:"userinfo_encryption_alg_values_supported,omitempty"`
	UserInfoEncryptionEncValues []string `json:"userinfo_encryption_enc_values_supported,omitempty"`
	ReqObjSigningAlgValues      []string `json:"request_object_signing_alg_values_supported,omitempty"`
	ReqObjEncryptionAlgValues   []string `json:"request_object_encryption_alg_values_supported,omitempty"`
	ReqObjEncryptionEncValues   []string `json:"request_object_encryption_enc_values_supported,omitempty"`

	TokenEndpointAuthMethodsSupported          []string `json:"token_endpoint_auth_methods_supported,omitempty"`
	TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported,omitempty"`

	DisplayValuesSupported        []string `json:"display_values_supported,omitempty"`
	ClaimTypesSupported           []string `json:"claim_types_supported,omitempty"`
	ServiceDocs                   string   `json:"service_documentation,omitempty"`
	ClaimsLocalsSupported         []string `json:"claims_locales_supported,omitempty"`
	UILocalsSupported             []string `json:"ui_locales_supported,omitempty"`
	ClaimsParameterSupported      bool     `json:"claims_parameter_supported,omitempty"`
	RequestParameterSupported     bool     `json:"request_parameter_supported,omitempty"`
	RequestURIParamaterSupported  bool     `json:"request_uri_parameter_supported,omitempty"`
	RequireRequestURIRegistration bool     `json:"require_request_uri_registration,omitempty"`

	Policy         string `json:"op_policy_uri,omitempty"`
	TermsOfService string `json:"op_tos_uri,omitempty"`
}

func (OidcProviderConfiguration) AsProviderConfig

func (pc OidcProviderConfiguration) AsProviderConfig() (oidc.ProviderConfig, error)

Converts a provider config (based on the OpenID Connect spec) to the type used by coreos/go-oidc. Used to handle scenarios where the provider doesn't adhere to spec.

type Principal

type Principal interface {
	// The Principal's identifier.
	Name() string

	// The database sequence at which this Principal last changed
	Sequence() uint64
	SetSequence(sequence uint64)

	// The set of channels the Principal belongs to, and what sequence access was granted.
	Channels() ch.TimedSet

	// The channels the Principal was explicitly granted access to thru the admin API.
	ExplicitChannels() ch.TimedSet

	// Sets the explicit channels the Principal has access to.
	SetExplicitChannels(ch.TimedSet)

	// The previous set of channels the Principal was granted.  Used to maintain sequence history.
	PreviousChannels() ch.TimedSet

	// Sets the previous set of channels the Principal has access to.
	SetPreviousChannels(ch.TimedSet)

	// Returns true if the Principal has access to the given channel.
	CanSeeChannel(channel string) bool

	// If the Principal has access to the given channel, returns the sequence number at which
	// access was granted; else returns zero.
	CanSeeChannelSince(channel string) uint64

	// If the Principal has access to the given channel, returns the vb and sequence number at which
	// access was granted; else returns zero.
	CanSeeChannelSinceVbSeq(channel string, hashFunction VBHashFunction) (base.VbSeq, bool)

	// Validate that the specified vbSeq has a non-zero sequence, and populate the vbucket for
	// admin grants.
	ValidateGrant(vbseq *ch.VbSequence, hashFunction VBHashFunction) bool

	// Returns an error if the Principal does not have access to all the channels in the set.
	AuthorizeAllChannels(channels base.Set) error

	// Returns an error if the Principal does not have access to any of the channels in the set.
	AuthorizeAnyChannel(channels base.Set) error

	// Returns an appropriate HTTPError for unauthorized access -- a 401 if the receiver is
	// the guest user, else 403.
	UnauthError(message string) error

	DocID() string
	// contains filtered or unexported methods
}

A Principal is an abstract object that can have access to channels.

type Role

type Role interface {
	Principal
}

Role is basically the same as Principal, just concrete. Users can inherit channels from Roles.

type User

type User interface {
	Principal

	// The user's email address.
	Email() string

	// Sets the user's email address.
	SetEmail(string) error

	// If true, the user is unable to authenticate.
	Disabled() bool

	// Sets the disabled property
	SetDisabled(bool)

	// Authenticates the user's password.
	Authenticate(password string) bool

	// Changes the user's password.
	SetPassword(password string)

	// The set of Roles the user belongs to (including ones given to it by the sync function)
	RoleNames() ch.TimedSet

	// The roles the user was explicitly granted access to thru the admin API.
	ExplicitRoles() ch.TimedSet

	// Sets the explicit roles the user belongs to.
	SetExplicitRoles(ch.TimedSet)

	// Every channel the user has access to, including those inherited from Roles.
	InheritedChannels() ch.TimedSet

	// If the input set contains the wildcard "*" channel, returns the user's InheritedChannels;
	// else returns the input channel list unaltered.
	ExpandWildCardChannel(channels base.Set) base.Set

	// Returns a TimedSet containing only the channels from the input set that the user has access
	// to, annotated with the sequence number at which access was granted.
	FilterToAvailableChannels(channels base.Set) ch.TimedSet

	// Every channel the user has access to, including those inherited from Roles.
	InheritedChannelsForClock(since base.SequenceClock) (channels ch.TimedSet, secondaryTriggers ch.TimedSet)

	// If the input set contains the wildcard "*" channel, returns the user's InheritedChannels, restricted
	// by the since value;
	// else returns the input channel list unaltered.
	ExpandWildCardChannelSince(channels base.Set, since base.SequenceClock) base.Set

	// Returns a TimedSet containing only the channels from the input set that the user has access
	// to, annotated with the sequence number at which access was granted.  When there are multiple grants
	// to the same channel, priority is given to values prior to the specified since.
	FilterToAvailableChannelsForSince(channels base.Set, since base.SequenceClock) (ch.TimedSet, ch.TimedSet)

	// Returns a Set containing channels that the user has access to, that aren't present in the
	// input set
	GetAddedChannels(channels ch.TimedSet) base.Set
	// contains filtered or unexported methods
}

A User is a Principal that can log in and have multiple Roles.

type VBHashFunction

type VBHashFunction func(string) uint32

Jump to

Keyboard shortcuts

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