auth

package
v0.0.0-...-202847b Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2023 License: Apache-2.0 Imports: 18 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BasicAuthFunc

type BasicAuthFunc func(string, string) bool

BasicAuthFunc defines a function to validate basic auth credentials.

type Option

type Option func(*Service) error

Option can be used as an argument in NewService to configure it with different settings.

func OptionsError

func OptionsError(err error) []Option

OptionsError helper function to be used within the backend package or other sub-packages whose functions may return an OptionFactoryFunc.

func WithBasicAuth

func WithBasicAuth(baf BasicAuthFunc, realm string, scopeIDs ...scope.TypeID) Option

WithBasicAuth provides the basic authentication header but allows to set a custom function to compare the input data of username and password.

func WithCombineTriggers

func WithCombineTriggers(combine bool, scopeIDs ...scope.TypeID) Option

WithCombineTriggers setting to true forces all authentication triggers to return true. Otherwise the first trigger which returns true, triggers the authentication providers. Default value: false.

func WithDebugLog

func WithDebugLog(w io.Writer) Option

WithDebugLog creates a new standard library based logger with debug mode enabled. The passed writer must be thread safe.

func WithDefaultConfig

func WithDefaultConfig(scopeIDs ...scope.TypeID) Option

WithDefaultConfig applies the default configuration settings for a specific scope.

Default values are:

  • authentication returns always access denied
  • all resources protected

func WithDisable

func WithDisable(isDisabled bool, scopeIDs ...scope.TypeID) Option

WithDisable disables the current service and calls the next HTTP handler.

The variadic "scopeIDs" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no "scopeIDs" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.

func WithErrorHandler

func WithErrorHandler(eh mw.ErrorHandler, scopeIDs ...scope.TypeID) Option

WithErrorHandler adds a custom error handler. Gets called in the http.Handler after the scope can be extracted from the context.Context and the configuration has been found and is valid. The default error handler prints the error to the user and returns a http.StatusServiceUnavailable.

The variadic "scopeIDs" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no "scopeIDs" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.

func WithInvalidAuth

func WithInvalidAuth(callNext bool, scopeIDs ...scope.TypeID) Option

WithInvalidAuth authentication will always fail. Mainly used for testing ;-)

func WithLogger

func WithLogger(l log.Logger) Option

WithLogger convenient helper function to apply a logger to the Service type.

func WithMarkPartiallyApplied

func WithMarkPartiallyApplied(partially bool, scopeIDs ...scope.TypeID) Option

WithMarkPartiallyApplied if set to true marks a configuration for a scope as partially applied with functional options set via source code. The internal service knows that it must trigger additionally the OptionFactoryFunc to load configuration from a backend. Useful in the case where parts of the configurations are coming from backend storages and other parts like http handler have been set via code. This function should only be applied in case you work with WithOptionFactory().

The variadic "scopeIDs" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no "scopeIDs" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.

func WithOptionFactory

func WithOptionFactory(f OptionFactoryFunc) Option

WithOptionFactory applies a function which lazily loads the options from a slow backend (config.Getter) depending on the incoming scope within a request. For example applies the backend configuration to the service.

Once this option function has been set all other manually set option functions, which accept a scope and a scope ID as an argument, will NOT be overwritten by the new values retrieved from the configuration service.

cfgStruct, err := backendauth.NewConfigStructure()
if err != nil {
	panic(err)
}
be := backendauth.New(cfgStruct)

srv := auth.MustNewService(
	auth.WithOptionFactory(be.PrepareOptions()),
)

func WithProvider

func WithProvider(pf ProviderFunc, priority int, scopeIDs ...scope.TypeID) Option

WithProvider sets the authentication provider function which checks if a request should be considered valid to call the next HTTP handler on err == nil or even call the next provider. Subsequent calls of this functions will add more ProviderFuncs to the internal list. This internal list cannot yet be cleared or reset.

func WithResourceACLs

func WithResourceACLs(blockList, allowList []string, scopeIDs ...scope.TypeID) Option

WithResourceACLs enables to define specific URL paths to be black- and/or white listed. Matching for black- and white lists checks if the URL path has the provided string of a list as a prefix.

auth.WithResources(nil,nil) // blocks everything
auth.WithResources([]string{"/"}, []string{}) // blocks everything
auth.WithResources([]string{"/"}, []string{"/catalog"}) // blocks everything except the routes starting with /catalog.

Providing no scopeIDs applies the resource ACL to the default scope ID. The string based ACL checks will always be executed before REGEX based ACL checks, if both functional options have been provided.

func WithResourceRegexpACLs

func WithResourceRegexpACLs(blockList, allowList []string, scopeIDs ...scope.TypeID) Option

WithResourceRegexpACLs same as WithResourceACLs but uses the slow pre-compiled and more powerful regexes.

func WithServiceErrorHandler

func WithServiceErrorHandler(eh mw.ErrorHandler) Option

WithServiceErrorHandler sets the error handler on the Service object. Convenient helper function.

func WithSimpleBasicAuth

func WithSimpleBasicAuth(username, password, realm string, scopeIDs ...scope.TypeID) Option

WithSimpleBasicAuth sets a single username/password for a scope. Username and password must be provided as "plain text" arguments. This basic auth handler calls the next authentication provider if the authentication fails. Username and password will be compared in constant time.

func WithTraceAttributes

func WithTraceAttributes(attrs ...trace.Attribute) Option

WIP

func WithTrigger

func WithTrigger(tf TriggerFunc, priority int, scopeIDs ...scope.TypeID) Option

WithTrigger sets the authentication trigger function which implements a condition to check if the list of authentication providers should be called. Subsequent calls of this functional option will add more TriggerFuncs to the internal list. If not trigger has been applied the authentication providers will always be called.

func WithUnauthorizedHandler

func WithUnauthorizedHandler(uah mw.ErrorHandler, scopeIDs ...scope.TypeID) Option

WithUnauthorizedHandler sets the handler which calls the interface to request data from a user after the authentication failed.

func WithUnauthorizedRedirect

func WithUnauthorizedRedirect(url string, code int, scopeIDs ...scope.TypeID) Option

WithUnauthorizedRedirect redirects if the authorization fails.

func WithValidAuth

func WithValidAuth(scopeIDs ...scope.TypeID) Option

WithValidAuth authentication will always succeed. Mainly used for testing ;-)

type OptionFactories

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

OptionFactories allows to register multiple OptionFactoryFunc identified by their names. Those OptionFactoryFuncs will be loaded in the backend package depending on the configured name under a certain path. This type is embedded in the backendauth.Configuration type.

func NewOptionFactories

func NewOptionFactories() *OptionFactories

NewOptionFactories creates a new struct and initializes the internal map for the registration of different option factories.

func (*OptionFactories) Deregister

func (of *OptionFactories) Deregister(name string)

Deregister removes a functional option factory from the internal register.

func (*OptionFactories) Lookup

func (of *OptionFactories) Lookup(name string) (OptionFactoryFunc, error)

Lookup returns a functional option factory identified by name or an error if the entry doesn't exists. May return a NotFound error behaviour.

func (*OptionFactories) Names

func (of *OptionFactories) Names() []string

Names returns an unordered list of names of all registered functional option factories.

func (*OptionFactories) Register

func (of *OptionFactories) Register(name string, factory OptionFactoryFunc)

Register adds another functional option factory to the internal register. Overwrites existing entries.

type OptionFactoryFunc

type OptionFactoryFunc func(config.Scoped) []Option

OptionFactoryFunc a closure around a scoped configuration to figure out which options should be returned depending on the scope brought to you during a request.

type ProviderFunc

type ProviderFunc func(scopeID scope.TypeID, r *http.Request) (callNext bool, err error)

ProviderFunc checks if a request is allowed to proceed. It returns nil on success. If you compare usernames and passwords make sure to use subtle.ConstantTimeCompare(). If callNext returns true the next authenticator gets called despite an occurred error, which gets dropped silently. If all ProviderFuncs return true to call the next, then the last function call gets a force checked error.

type ScopedConfig

type ScopedConfig struct {
	UnauthorizedHandler mw.ErrorHandler
	// contains filtered or unexported fields
}

ScopedConfig contains the configuration for a specific scope.

func (ScopedConfig) Authenticate

func (sc ScopedConfig) Authenticate(r *http.Request) error

Authenticate validates if a request is allowed to pass.

type Service

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

Service implements authentication middleware and scoped based authorization.

func MustNew

func MustNew(cfg config.Scoper, opts ...Option) *Service

MustNew same as New() but panics on error. Use only during app start up process.

func New

func New(cfg config.Scoper, opts ...Option) (*Service, error)

New creates a new authentication service to be used as a middleware or standalone.

func (*Service) ClearCache

func (s *Service) ClearCache() error

ClearCache clears the internal map storing all scoped configurations. You must reapply all functional options. TODO(CyS) all previously applied options will be automatically reapplied.

func (*Service) ConfigByScope

func (s *Service) ConfigByScope(websiteID, storeID int64) (ScopedConfig, error)

ConfigByScope creates a new scoped configuration depending on the Service.useWebsite flag. If useWebsite==true the scoped configuration contains only the website->default scope despite setting a store scope. If an OptionFactory is set the configuration gets loaded from the backend. A nil root config causes a panic.

func (*Service) ConfigByScopeID

func (s *Service) ConfigByScopeID(current scope.TypeID, parent scope.TypeID) (scpCfg ScopedConfig, _ error)

ConfigByScopeID returns the correct configuration for a scope and may fall back to the next higher scope: store -> website -> default. If `current` TypeID is Store, then the `parent` can only be Website or Default. If an entry for a scope cannot be found the next higher scope gets looked up and the pointer of the next higher scope gets assigned to the current scope. This prevents redundant configurations and enables us to change one scope configuration with an impact on all other scopes which depend on the parent scope. A zero `parent` triggers no further look ups. This function does not load any configuration (config.Getter related) from the backend and accesses the internal map of the Service directly.

Important: a "current" scope cannot have multiple "parent" scopes.

func (*Service) ConfigByScopedGetter

func (s *Service) ConfigByScopedGetter(scpGet config.Scoped) (ScopedConfig, error)

ConfigByScopedGetter returns the internal configuration depending on the ScopedGetter. Mainly used within the middleware. If you have applied the option WithOptionFactory() the configuration will be pulled out only one time from the backend configuration service. The field optionInflight handles the guaranteed atomic single loading for each scope.

func (*Service) DebugCache

func (s *Service) DebugCache(w io.Writer) error

DebugCache uses Sprintf to write an ordered list (by scope.TypeID) into a writer. Only usable for debugging.

func (*Service) Options

func (s *Service) Options(opts ...Option) error

Options applies option at creation time or refreshes them.

func (*Service) WithAuthentication

func (s *Service) WithAuthentication(next http.Handler) http.Handler

WithAuthentication to be used as a middleware for net.Handler. The applied configuration is used for the all store scopes or if the PkgBackend has been provided then on a website specific level. Middleware expects to find in a context a store.FromContextProvider().

type TriggerFunc

type TriggerFunc func(r *http.Request) bool

TriggerFunc defines the condition if the ProviderFunc should be executed. An trigger can be for example a certain path or an IP address.

Directories

Path Synopsis
Package backendauth (TODO) defines the backend configuration options and element slices.
Package backendauth (TODO) defines the backend configuration options and element slices.

Jump to

Keyboard shortcuts

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