security

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 27 Imported by: 0

README

Security

The security module is organized into sub packages each corresponding to a security features. The top level security.Use() does nothing on its own. It simply provides a mechanism where application code can express its security requirements through configuration.

The security module does this by providing a Initializer and a Registrar.

The registrar's job is to keep list of two things:

  1. WebSecurity Configurer

    A WebSecurity struct holds information on security configuration. This is expressed through a combination of Route (the path and method pattern which this WebSecurity applies), Condition (additional conditions of incoming requests, which this WebSecurity applies to) and Features (security features to apply).

    To define the desired security configuration, calling code provides implementation of the security.Configurer interface. It requires a Configure(WebSecurity) method in which the calling code can configure the WebSecurity instance. Usually this is provided by application code.

  2. Feature Configurer

    A security.FeatureConfigurer is internal to the security package, and it's not meant to be used by application code. It defines how a particular feature needs to modify WebSecurity. Usually in terms of what middleware handler functions need to be added. For example, the Session feature's configurer will add a couple of middlewares handler functions to the WebSecurity to load and persist session.

The initializer's job is to apply the security configuration expressed by all the WebSecurity configurers. It does so by looping through the configurers. Each configurer is given a new WebSecurity instance, so that the configurer can express its security configuration on this WebSecurity instance. Then the features specified on this WebSecurity instance is resolved using the corresponding feature configurer. At this point the WebSecurity is expressed in request patterns and middleware handler functions. The initializer then adds the pattern and handler functions as mappings to the web registrar. The initializer repeats this process until all the WebSecurity configurers are processed.

Documentation

Index

Constants

View Source
const (
	// CompatibilityReference
	/**
	 * Note about compatibility reference:
	 *
	 * Whenever an incompatible security model changes (in terms of serialization) is made to the class,
	 * we should update the version tag.
	 *
	 * For now we use project version + incremental number as tag, but we could also use timestamp or date
	 */
	CompatibilityReference    = "4000"
	CompatibilityReferenceTag = "SMCR" // SMCR = Security Model Compatibility Ref
)
View Source
const (
	// SpecialPermissionAccessAllTenant
	// Deprecated: this permission is no longer sufficient to determine tenancy access
	// in the case of an oauth2 authentication where the client is also tenanted.
	// We are deprecating the use case where a user does not select a tenant.
	SpecialPermissionAccessAllTenant = "ACCESS_ALL_TENANTS"
	SpecialPermissionAPIAdmin        = "IS_API_ADMIN"
	SpecialPermissionSwitchTenant    = "SWITCH_TENANT"
	SpecialPermissionSwitchUser      = "VIEW_OPERATOR_LOGIN_AS_CUSTOMER"
)
View Source
const (
	DetailsKeyAuthWarning = "AuthWarning"
	DetailsKeyAuthTime    = "AuthTime"
	DetailsKeyAuthMethod  = "AuthMethod"
	DetailsKeyMFAApplied  = "MFAApplied"
	DetailsKeySessionId   = "SessionId"
)
View Source
const (
	AuthMethodPassword       = "Password"
	AuthMethodExternalSaml   = "ExtSAML"
	AuthMethodExternalOpenID = "ExtOpenID"
)
View Source
const (
	WSSharedKeyCompositeAuthSuccessHandler  = "CompositeAuthSuccessHandler"
	WSSharedKeyCompositeAuthErrorHandler    = "CompositeAuthErrorHandler"
	WSSharedKeyCompositeAccessDeniedHandler = "CompositeAccessDeniedHandler"
	WSSharedKeySessionStore                 = "SessionStore"
	WSSharedKeyRequestPreProcessors         = "RequestPreProcessors"
)
View Source
const (
	MWOrderSessionHandling
	MWOrderAuthPersistence
	MWOrderErrorHandling
	MWOrderCsrfHandling
	MWOrderOAuth2AuthValidation
	MWOrderSAMLMetadataRefresh
	MWOrderPreAuth
	MWOrderBasicAuth
	MWOrderFormLogout
	MWOrderFormAuth
	MWOrderOAuth2TokenAuth
	// ... more MW goes here
	MWOrderAccessControl     = LowestMiddlewareOrder - 200
	MWOrderOAuth2Endpoints   = MWOrderAccessControl + 100
	MWOrderSamlAuthEndpoints = MWOrderAccessControl + 100
)

Middleware Orders

View Source
const (
	FeatureOrderOAuth2ClientAuth
	FeatureOrderAuthenticator
	FeatureOrderBasicAuth
	FeatureOrderFormLogin
	FeatureOrderSamlLogin
	FeatureOrderSamlLogout
	FeatureOrderLogout
	FeatureOrderOAuth2TokenEndpoint
	FeatureOrderOAuth2AuthorizeEndpoint
	FeatureOrderSamlAuthorizeEndpoint
	FeatureOrderOAuth2TokenAuth
	FeatureOrderCsrf
	FeatureOrderAccess
	FeatureOrderSession
	FeatureOrderRequestCache
	// ... more Feature goes here
	FeatureOrderErrorHandling = order.Lowest - 200
)

Feature Orders, if feature is not listed here, it's unordered. Unordered features are applied at last

View Source
const (
	HandlerOrderChangeSession = iota * 100
	HandlerOrderConcurrentSession
)

AuthenticationSuccessHandler Orders, if not listed here, it's unordered. Unordered handlers are applied at last

View Source
const (
	CsrfParamName  = "_csrf"
	CsrfHeaderName = "X-CSRF-TOKEN"
)

CSRF headers and parameter names - shared by CSRF feature and session feature's request cache

View Source
const (
	HighestMiddlewareOrder = int(-1<<18 + 1)                 // -0x3ffff = -262143
	LowestMiddlewareOrder  = HighestMiddlewareOrder + 0xffff // -0x30000 = -196608
)
View Source
const (
	StateAnonymous = AuthenticationState(iota)
	StatePrincipalKnown
	StateAuthenticated
)
View Source
const (
	ErrorTypeCodeAuthentication = Reserved + iota<<errorutils.ErrorTypeOffset
	ErrorTypeCodeAccessControl
	ErrorTypeCodeInternal
	ErrorTypeCodeOAuth2
	ErrorTypeCodeSaml
	ErrorTypeCodeOidc
	ErrorTypeCodeTenancy
)

All "Type" values are used as mask

View Source
const (
	ErrorSubTypeCodeInternal = ErrorTypeCodeAuthentication + iota<<errorutils.ErrorSubTypeOffset
	ErrorSubTypeCodeUsernamePasswordAuth
	ErrorSubTypeCodeExternalSamlAuth
	ErrorSubTypeCodeAuthWarning
)

All "SubType" values are used as mask sub types of ErrorTypeCodeAuthentication

View Source
const (
	ErrorCodeUsernameNotFound = ErrorSubTypeCodeUsernamePasswordAuth + iota
	ErrorCodeBadCredentials
	ErrorCodeCredentialsExpired
	ErrorCodeMaxAttemptsReached
	ErrorCodeAccountStatus
)

ErrorSubTypeCodeUsernamePasswordAuth

View Source
const (
	ErrorSubTypeCodeAccessDenied = ErrorTypeCodeAccessControl + iota<<errorutils.ErrorSubTypeOffset
	ErrorSubTypeCodeInsufficientAuth
	ErrorSubTypeCodeCsrf
)

All "SubType" values are used as mask sub types of ErrorTypeCodeAccessControl

View Source
const (
	ErrorSubTypeCodeTenantInvalid = ErrorTypeCodeTenancy + iota<<errorutils.ErrorSubTypeOffset
	ErrorSubTypeCodeTenantAccessDenied
)

All "SubType" values are used as mask sub types of ErrorTypeCodeTenancy

View Source
const (
	ErrorCodeMissingCsrfToken = ErrorSubTypeCodeCsrf + iota
	ErrorCodeInvalidCsrfToken
)
View Source
const (
	ErrorCodeAuthenticatorNotAvailable = ErrorSubTypeCodeInternal + iota
)

ErrorSubTypeCodeInternal

View Source
const (
	// security reserved
	Reserved = 11 << errorutils.ReservedOffset
)
View Source
const SessionPropertiesPrefix = "security.session"
View Source
const (
	SpecialTenantIdWildcard = "*"
)
View Source
const TimeoutPropertiesPrefix = "security.timeout-support"

Variables

View Source
var (
	ErrorTypeSecurity       = NewErrorCategory(Reserved, errors.New("error type: security"))
	ErrorTypeAuthentication = NewErrorType(ErrorTypeCodeAuthentication, errors.New("error type: authentication"))
	ErrorTypeAccessControl  = NewErrorType(ErrorTypeCodeAccessControl, errors.New("error type: access control"))
	ErrorTypeInternal       = NewErrorType(ErrorTypeCodeInternal, errors.New("error type: internal"))
	ErrorTypeSaml           = NewErrorType(ErrorTypeCodeSaml, errors.New("error type: saml"))
	ErrorTypeOidc           = NewErrorType(ErrorTypeCodeOidc, errors.New("error type: oidc"))

	ErrorSubTypeInternalError        = NewErrorSubType(ErrorSubTypeCodeInternal, errors.New("error sub-type: internal"))
	ErrorSubTypeUsernamePasswordAuth = NewErrorSubType(ErrorSubTypeCodeUsernamePasswordAuth, errors.New("error sub-type: internal"))
	ErrorSubTypeExternalSamlAuth     = NewErrorSubType(ErrorSubTypeCodeExternalSamlAuth, errors.New("error sub-type: external saml"))
	ErrorSubTypeAuthWarning          = NewErrorSubType(ErrorSubTypeCodeAuthWarning, errors.New("error sub-type: auth warning"))

	ErrorSubTypeAccessDenied     = NewErrorSubType(ErrorSubTypeCodeAccessDenied, errors.New("error sub-type: access denied"))
	ErrorSubTypeInsufficientAuth = NewErrorSubType(ErrorSubTypeCodeInsufficientAuth, errors.New("error sub-type: insufficient auth"))
	ErrorSubTypeCsrf             = NewErrorSubType(ErrorSubTypeCodeCsrf, errors.New("error sub-type: csrf"))
)

ErrorTypes, can be used in errors.Is

View Source
var (
	ErrorInvalidTenantId    = NewCodedError(ErrorSubTypeCodeTenantInvalid, "Invalid tenant Id")
	ErrorTenantAccessDenied = NewCodedError(ErrorSubTypeCodeTenantAccessDenied, "No Access to the tenant")
)

Concrete error, can be used in errors.Is for exact match

View Source
var Module = &bootstrap.Module{
	Name:       "security",
	Precedence: MaxSecurityPrecedence,
	Options: []fx.Option{
		fx.Provide(provideSecurityInitialization),
		fx.Invoke(initialize),
	},
}

Functions

func Clear

func Clear(ctx context.Context) error

Clear attempt to set security context as "unauthenticated". Return error if not possible

func DetermineAuthenticationTime

func DetermineAuthenticationTime(_ context.Context, userAuth Authentication) (authTime time.Time)

func GetUsername

func GetUsername(userAuth Authentication) (string, error)

func GobRegister

func GobRegister()

func HasAccessToTenant

func HasAccessToTenant(ctx context.Context, tenantId string) bool

HasAccessToTenant if no error return true, otherwise return false

func HasErrorAccessingTenant

func HasErrorAccessingTenant(ctx context.Context, tenantId string) error

HasErrorAccessingTenant

if the tenantId is not valid, this method will return false, otherwise the following checks are applied in order

1. If the user has ACCESS_ALL_TENANT permission, this method will return true

2. If the user's designated tenants include the give tenant, this method will return true

3. If the tenant hierarchy is loaded, this method will also check if any of the given tenant's ancestor
is in the user's designated tenant. If yes, this method will return true.

otherwise, this method return false.

func HasPermissions

func HasPermissions(auth Authentication, permissions ...string) bool

func IsBeingAuthenticated

func IsBeingAuthenticated(from, to Authentication) bool

func IsBeingUnAuthenticated

func IsBeingUnAuthenticated(from, to Authentication) bool

func IsFullyAuthenticated

func IsFullyAuthenticated(auth Authentication) bool

func IsResponseWritten

func IsResponseWritten(rw http.ResponseWriter) bool

func IsTenantValid

func IsTenantValid(ctx context.Context, tenantId string) bool

IsTenantValid In most cases, the HasAccessToTenant should be used instead. It checks both the tenant's validity and whether the user has access to it

func MustClear

func MustClear(ctx context.Context)

MustClear set security context as "unauthenticated".

func MustSet

func MustSet(ctx context.Context, auth Authentication)

MustSet is the panicking version of Set.

func NewAccessControlError

func NewAccessControlError(value interface{}, causes ...interface{}) error

func NewAccessDeniedError

func NewAccessDeniedError(value interface{}, causes ...interface{}) error

func NewAccountStatusError

func NewAccountStatusError(value interface{}, causes ...interface{}) error

func NewAuthenticationError

func NewAuthenticationError(value interface{}, causes ...interface{}) error

func NewAuthenticationWarningError

func NewAuthenticationWarningError(value interface{}, causes ...interface{}) error

func NewAuthenticatorNotAvailableError

func NewAuthenticatorNotAvailableError(value interface{}, causes ...interface{}) error

func NewBadCredentialsError

func NewBadCredentialsError(value interface{}, causes ...interface{}) error

func NewCredentialsExpiredError

func NewCredentialsExpiredError(value interface{}, causes ...interface{}) error

func NewErrorSubType

func NewErrorSubType(code int64, e error) error

func NewErrorType

func NewErrorType(code int64, e error) error

func NewExternalSamlAuthenticationError

func NewExternalSamlAuthenticationError(value interface{}, causes ...interface{}) error

func NewInsufficientAuthError

func NewInsufficientAuthError(value interface{}, causes ...interface{}) error

func NewInternalAuthenticationError

func NewInternalAuthenticationError(value interface{}, causes ...interface{}) error

func NewInternalError

func NewInternalError(text string, causes ...interface{}) error

func NewInvalidCsrfTokenError

func NewInvalidCsrfTokenError(value interface{}, causes ...interface{}) error

func NewMaxAttemptsReachedError

func NewMaxAttemptsReachedError(value interface{}, causes ...interface{}) error

func NewMissingCsrfTokenError

func NewMissingCsrfTokenError(value interface{}, causes ...interface{}) error

func NewUsernameNotFoundError

func NewUsernameNotFoundError(value interface{}, causes ...interface{}) error

func NoopHandlerFunc

func NoopHandlerFunc() gin.HandlerFunc

func Set

func Set(ctx context.Context, auth Authentication) error

Set security context, return error if the given context is not backed by utils.MutableContext.

func Use

func Use()

Use Maker func, does nothing. Allow service to include this module in main()

func WriteError

func WriteError(ctx context.Context, r *http.Request, rw http.ResponseWriter, code int, err error)

func WriteErrorAsHtml

func WriteErrorAsHtml(ctx context.Context, rw http.ResponseWriter, code int, err error)

func WriteErrorAsJson

func WriteErrorAsJson(ctx context.Context, rw http.ResponseWriter, code int, err error)

Types

type AccessDeniedHandler

type AccessDeniedHandler interface {
	HandleAccessDenied(context.Context, *http.Request, http.ResponseWriter, error)
}

AccessDeniedHandler handles ErrorSubTypeAccessDenied

type Account

type Account interface {
	ID() interface{}
	Type() AccountType
	Username() string
	Credentials() interface{}
	Permissions() []string
	Disabled() bool
	Locked() bool
	UseMFA() bool
	// CacheableCopy should returns a copy of Account that suitable for putting into cache.
	// e.g. the CacheableCopy should be able to be serialized and shouldn't contains Credentials or any reloadable content
	CacheableCopy() Account
}

type AccountFinalizeOption

type AccountFinalizeOption struct {
	Tenant *Tenant // Tenant field can be nil
}

type AccountFinalizeOptions

type AccountFinalizeOptions func(option *AccountFinalizeOption)

func FinalizeWithTenant

func FinalizeWithTenant(tenant *Tenant) AccountFinalizeOptions

type AccountFinalizer

type AccountFinalizer interface {
	// Finalize is a function that will allow a service to modify the account before it
	// is put into the security context. An example usage of this is to allow for per-tenant
	// permissions where a user can have different permissions depending on which tenant is selected.
	//
	// Note that the Account.ID and Account.Username should not be changed. If those fields are changed
	// an error will be reported.
	Finalize(ctx context.Context, account Account, options ...AccountFinalizeOptions) (Account, error)
}

type AccountHistory

type AccountHistory interface {
	LastLoginTime() time.Time
	LoginFailures() []time.Time
	SerialFailedAttempts() int
	LockoutTime() time.Time
	PwdChangedTime() time.Time
	GracefulAuthCount() int
}

type AccountLockingRule

type AccountLockingRule interface {
	// LockoutPolicyName the name of locking rule
	LockoutPolicyName() string
	// LockoutEnabled indicate whether account locking is enabled
	LockoutEnabled() bool
	// LockoutDuration specify how long the account should be locked after consecutive login failures
	LockoutDuration() time.Duration
	// LockoutFailuresLimit specify how many consecutive login failures required to lock the account
	LockoutFailuresLimit() int
	// LockoutFailuresInterval specify how long between the first and the last login failures to be considered as consecutive login failures
	LockoutFailuresInterval() time.Duration
}

type AccountMetadata

type AccountMetadata interface {
	RoleNames() []string
	FirstName() string
	LastName() string
	Email() string
	LocaleCode() string
	CurrencyCode() string
	Value(key string) interface{}
}

type AccountPwdAgingRule

type AccountPwdAgingRule interface {
	// PwdAgingPolicyName the name of password polcy
	PwdAgingPolicyName() string
	// PwdAgingRuleEnforced indicate whether password policy is enabled
	PwdAgingRuleEnforced() bool
	// PwdMaxAge specify how long a password is valid before expiry
	PwdMaxAge() time.Duration
	// PwdExpiryWarningPeriod specify how long before password expiry the system should warn user
	PwdExpiryWarningPeriod() time.Duration
	// GracefulAuthLimit specify how many logins is allowed after password expiry
	GracefulAuthLimit() int
}

type AccountStore

type AccountStore interface {
	// LoadAccountById find account by its Domain
	LoadAccountById(ctx context.Context, id interface{}) (Account, error)
	// LoadAccountByUsername find account by its Username
	LoadAccountByUsername(ctx context.Context, username string) (Account, error)
	// LoadLockingRules load given account's locking rule. It's recommended to cache the result
	LoadLockingRules(ctx context.Context, acct Account) (AccountLockingRule, error)
	// LoadPwdAgingRules load given account's password policy. It's recommended to cache the result
	LoadPwdAgingRules(ctx context.Context, acct Account) (AccountPwdAgingRule, error)
	// Save save the account if necessary
	Save(ctx context.Context, acct Account) error
}

type AccountTenancy

type AccountTenancy interface {
	DefaultDesignatedTenantId() string
	DesignatedTenantIds() []string
	TenantId() string
}

type AccountType

type AccountType int
const (
	AccountTypeUnknown AccountType = iota
	AccountTypeDefault
	AccountTypeApp
	AccountTypeFederated
	AccountTypeSystem
)

func ParseAccountType

func ParseAccountType(value interface{}) AccountType

func (AccountType) String

func (t AccountType) String() string

type AccountUpdater

type AccountUpdater interface {
	IncrementGracefulAuthCount()
	ResetGracefulAuthCount()
	LockAccount()
	UnlockAccount()
	RecordFailure(failureTime time.Time, limit int)
	RecordSuccess(loginTime time.Time)
	ResetFailedAttempts()
}

type AcctDetails

type AcctDetails struct {
	ID                        string
	Type                      AccountType
	Username                  string
	Credentials               interface{}
	Permissions               []string
	Disabled                  bool
	Locked                    bool
	UseMFA                    bool
	DefaultDesignatedTenantId string
	DesignatedTenantIds       []string
	TenantId                  string
	LastLoginTime             time.Time
	LoginFailures             []time.Time
	SerialFailedAttempts      int
	LockoutTime               time.Time
	PwdChangedTime            time.Time
	GracefulAuthCount         int
	PolicyName                string
}

type AcctLockingRule

type AcctLockingRule struct {
	Name             string
	Enabled          bool
	LockoutDuration  time.Duration
	FailuresLimit    int
	FailuresInterval time.Duration
}

type AcctMetadata

type AcctMetadata struct {
	RoleNames    []string
	FirstName    string
	LastName     string
	Email        string
	LocaleCode   string
	CurrencyCode string
	Extra        map[string]interface{}
}

type AcctPasswordPolicy

type AcctPasswordPolicy struct {
	Name                string
	Enabled             bool
	MaxAge              time.Duration
	ExpiryWarningPeriod time.Duration
	GracefulAuthLimit   int
}

type AnonymousAuthentication

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

func (*AnonymousAuthentication) Details

func (aa *AnonymousAuthentication) Details() interface{}

func (*AnonymousAuthentication) Permissions

func (_ *AnonymousAuthentication) Permissions() Permissions

func (*AnonymousAuthentication) Principal

func (aa *AnonymousAuthentication) Principal() interface{}

func (*AnonymousAuthentication) State

type AnonymousAuthenticator

type AnonymousAuthenticator struct{}

func (*AnonymousAuthenticator) Authenticate

func (a *AnonymousAuthenticator) Authenticate(_ context.Context, candidate Candidate) (auth Authentication, err error)

type AnonymousCandidate

type AnonymousCandidate map[string]interface{}

func (AnonymousCandidate) Credentials

func (_ AnonymousCandidate) Credentials() interface{}

Credentials implements security.Candidate

func (AnonymousCandidate) Details

func (ac AnonymousCandidate) Details() interface{}

Details implements security.Candidate

func (AnonymousCandidate) Principal

func (ac AnonymousCandidate) Principal() interface{}

Principal implements security.Candidate

type Authentication

type Authentication interface {
	Principal() interface{}
	Permissions() Permissions
	State() AuthenticationState
	Details() interface{}
}

func Get

type AuthenticationDetails

type AuthenticationDetails interface {
	ExpiryTime() time.Time
	IssueTime() time.Time
	Roles() utils.StringSet
	Permissions() utils.StringSet
	AuthenticationTime() time.Time
}

type AuthenticationEntryPoint

type AuthenticationEntryPoint interface {
	Commence(context.Context, *http.Request, http.ResponseWriter, error)
}

AuthenticationEntryPoint kicks off authentication process

type AuthenticationErrorHandler

type AuthenticationErrorHandler interface {
	HandleAuthenticationError(context.Context, *http.Request, http.ResponseWriter, error)
}

AuthenticationErrorHandler handles ErrorTypeAuthentication

type AuthenticationState

type AuthenticationState int

type AuthenticationSuccessHandler

type AuthenticationSuccessHandler interface {
	HandleAuthenticationSuccess(c context.Context, r *http.Request, rw http.ResponseWriter, from, to Authentication)
}

AuthenticationSuccessHandler handles authentication success event The counterpart of this interface is AuthenticationErrorHandler

type Authenticator

type Authenticator interface {
	// Authenticate function takes the Candidate and authenticate it.
	// if the Candidate type is not supported, return nil,nil
	// if the Candidate is rejected, non-nil error, and the returned Authentication is ignored
	Authenticate(context.Context, Candidate) (Authentication, error)
}

func NewAuthenticator

func NewAuthenticator(authenticators ...Authenticator) Authenticator

type AuthenticatorBuilder

type AuthenticatorBuilder interface {
	Build(context.Context) (Authenticator, error)
}

type AutoCreateUserDetails

type AutoCreateUserDetails interface {
	IsEnabled() bool
	GetEmailWhiteList() []string
	GetAttributeMapping() map[string]string
	GetElevatedUserRoleNames() []string
	GetRegularUserRoleNames() []string
}

type Candidate

type Candidate interface {
	Principal() interface{}
	Credentials() interface{}
	Details() interface{}
}

type CodedError

type CodedError struct {
	errorutils.CodedError
}

CodedError implements errorutils.ErrorCoder, errorutils.ComparableErrorCoder, errorutils.NestedError

func NewCodedError

func NewCodedError(code int64, e interface{}, causes ...interface{}) *CodedError

NewCodedError creates concrete error. it cannot be used as ErrorType or ErrorSubType comparison supported item are string, error, fmt.Stringer

func NewErrorCategory

func NewErrorCategory(code int64, e error) *CodedError

type CompositeAccessDeniedHandler

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

CompositeAccessDeniedHandler implement AccessDeniedHandler interface

func NewAccessDeniedHandler

func NewAccessDeniedHandler(handlers ...AccessDeniedHandler) *CompositeAccessDeniedHandler

func (*CompositeAccessDeniedHandler) Add

func (*CompositeAccessDeniedHandler) HandleAccessDenied

func (h *CompositeAccessDeniedHandler) HandleAccessDenied(
	c context.Context, r *http.Request, rw http.ResponseWriter, err error)

func (*CompositeAccessDeniedHandler) Handlers

Handlers returns list of authentication handlers, any nested composite handlers are flattened

func (*CompositeAccessDeniedHandler) Merge

func (*CompositeAccessDeniedHandler) Size

type CompositeAuthenticationErrorHandler

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

CompositeAuthenticationErrorHandler implement AuthenticationErrorHandler interface

func (*CompositeAuthenticationErrorHandler) Add

func (*CompositeAuthenticationErrorHandler) HandleAuthenticationError

func (h *CompositeAuthenticationErrorHandler) HandleAuthenticationError(
	c context.Context, r *http.Request, rw http.ResponseWriter, err error)

func (*CompositeAuthenticationErrorHandler) Handlers

Handlers returns list of authentication handlers, any nested composite handlers are flattened

func (*CompositeAuthenticationErrorHandler) Merge

func (*CompositeAuthenticationErrorHandler) Size

type CompositeAuthenticationSuccessHandler

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

CompositeAuthenticationSuccessHandler implement AuthenticationSuccessHandler interface

func (*CompositeAuthenticationSuccessHandler) Add

func (*CompositeAuthenticationSuccessHandler) HandleAuthenticationSuccess

func (h *CompositeAuthenticationSuccessHandler) HandleAuthenticationSuccess(
	c context.Context, r *http.Request, rw http.ResponseWriter, from, to Authentication)

func (*CompositeAuthenticationSuccessHandler) Handlers

Handlers returns list of authentication handlers, any nested composite handlers are flattened

func (*CompositeAuthenticationSuccessHandler) Merge

type CompositeAuthenticator

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

CompositeAuthenticator implement Authenticator interface

func (*CompositeAuthenticator) Add

func (*CompositeAuthenticator) Authenticate

func (a *CompositeAuthenticator) Authenticate(ctx context.Context, candidate Candidate) (auth Authentication, err error)

func (*CompositeAuthenticator) Authenticators

func (a *CompositeAuthenticator) Authenticators() []Authenticator

Authenticators returns list of authenticators, any nested composite handlers are flattened

func (*CompositeAuthenticator) Merge

type CompositeAuthenticatorBuilder

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

CompositeAuthenticatorBuilder implements AuthenticatorBuilder

func NewAuthenticatorBuilder

func NewAuthenticatorBuilder() *CompositeAuthenticatorBuilder

func (*CompositeAuthenticatorBuilder) Build

type CompositeErrorHandler

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

*CompositeErrorHandler implement ErrorHandler interface

func NewErrorHandler

func NewErrorHandler(handlers ...ErrorHandler) *CompositeErrorHandler

func (*CompositeErrorHandler) Add

func (*CompositeErrorHandler) HandleError

func (h *CompositeErrorHandler) HandleError(
	c context.Context, r *http.Request, rw http.ResponseWriter, err error)

func (*CompositeErrorHandler) Merge

func (*CompositeErrorHandler) Size

func (h *CompositeErrorHandler) Size() int

type Configurer

type Configurer interface {
	Configure(WebSecurity)
}

Configurer can be registered to Registrar. Each Configurer will get a newly created WebSecurity and is responsible to configure for customized security

type ConfigurerFunc

type ConfigurerFunc func(ws WebSecurity)

func (ConfigurerFunc) Configure

func (f ConfigurerFunc) Configure(ws WebSecurity)

type ContextDetails

type ContextDetails interface {
	AuthenticationDetails
	KeyValueDetails
}

type ContextDetailsStore

type ContextDetailsStore interface {
	ReadContextDetails(ctx context.Context, key interface{}) (ContextDetails, error)
	SaveContextDetails(ctx context.Context, key interface{}, details ContextDetails) error
	RemoveContextDetails(ctx context.Context, key interface{}) error
	ContextDetailsExists(ctx context.Context, key interface{}) bool
}

type CookieProperties

type CookieProperties struct {
	Domain         string `json:"domain"`
	MaxAge         int    `json:"max-age"`
	Secure         bool   `json:"secure"`
	HttpOnly       bool   `json:"http-only"`
	SameSiteString string `json:"same-site"`
	Path           string `json:"path"`
}

func (CookieProperties) SameSite

func (cp CookieProperties) SameSite() http.SameSite

type DefaultAccessDeniedHandler

type DefaultAccessDeniedHandler struct {
}

DefaultAccessDeniedHandler implements AccessDeniedHandler

func (*DefaultAccessDeniedHandler) HandleAccessDenied

func (h *DefaultAccessDeniedHandler) HandleAccessDenied(ctx context.Context, r *http.Request, rw http.ResponseWriter, err error)

type DefaultAccount

func NewUsernamePasswordAccount

func NewUsernamePasswordAccount(details *AcctDetails) *DefaultAccount

func (*DefaultAccount) CacheableCopy

func (a *DefaultAccount) CacheableCopy() Account

func (*DefaultAccount) Credentials

func (a *DefaultAccount) Credentials() interface{}

func (*DefaultAccount) CurrencyCode

func (a *DefaultAccount) CurrencyCode() string

func (*DefaultAccount) DefaultDesignatedTenantId

func (a *DefaultAccount) DefaultDesignatedTenantId() string

func (*DefaultAccount) DesignatedTenantIds

func (a *DefaultAccount) DesignatedTenantIds() []string

func (*DefaultAccount) Disabled

func (a *DefaultAccount) Disabled() bool

func (*DefaultAccount) Email

func (a *DefaultAccount) Email() string

func (*DefaultAccount) FirstName

func (a *DefaultAccount) FirstName() string

func (*DefaultAccount) GracefulAuthCount

func (a *DefaultAccount) GracefulAuthCount() int

func (*DefaultAccount) GracefulAuthLimit

func (a *DefaultAccount) GracefulAuthLimit() int

func (*DefaultAccount) ID

func (a *DefaultAccount) ID() interface{}

func (*DefaultAccount) IncrementGracefulAuthCount

func (a *DefaultAccount) IncrementGracefulAuthCount()

func (*DefaultAccount) LastLoginTime

func (a *DefaultAccount) LastLoginTime() time.Time

func (*DefaultAccount) LastName

func (a *DefaultAccount) LastName() string

func (*DefaultAccount) LocaleCode

func (a *DefaultAccount) LocaleCode() string

func (*DefaultAccount) LockAccount

func (a *DefaultAccount) LockAccount()

func (*DefaultAccount) Locked

func (a *DefaultAccount) Locked() bool

func (*DefaultAccount) LockoutDuration

func (a *DefaultAccount) LockoutDuration() time.Duration

func (*DefaultAccount) LockoutEnabled

func (a *DefaultAccount) LockoutEnabled() bool

func (*DefaultAccount) LockoutFailuresInterval

func (a *DefaultAccount) LockoutFailuresInterval() time.Duration

func (*DefaultAccount) LockoutFailuresLimit

func (a *DefaultAccount) LockoutFailuresLimit() int

func (*DefaultAccount) LockoutPolicyName

func (a *DefaultAccount) LockoutPolicyName() string

func (*DefaultAccount) LockoutTime

func (a *DefaultAccount) LockoutTime() time.Time

func (*DefaultAccount) LoginFailures

func (a *DefaultAccount) LoginFailures() []time.Time

func (*DefaultAccount) Permissions

func (a *DefaultAccount) Permissions() []string

func (*DefaultAccount) PwdAgingPolicyName

func (a *DefaultAccount) PwdAgingPolicyName() string

func (*DefaultAccount) PwdAgingRuleEnforced

func (a *DefaultAccount) PwdAgingRuleEnforced() bool

func (*DefaultAccount) PwdChangedTime

func (a *DefaultAccount) PwdChangedTime() time.Time

func (*DefaultAccount) PwdExpiryWarningPeriod

func (a *DefaultAccount) PwdExpiryWarningPeriod() time.Duration

func (*DefaultAccount) PwdMaxAge

func (a *DefaultAccount) PwdMaxAge() time.Duration

func (*DefaultAccount) RecordFailure

func (a *DefaultAccount) RecordFailure(failureTime time.Time, limit int)

func (*DefaultAccount) RecordSuccess

func (a *DefaultAccount) RecordSuccess(loginTime time.Time)

func (*DefaultAccount) ResetFailedAttempts

func (a *DefaultAccount) ResetFailedAttempts()

func (*DefaultAccount) ResetGracefulAuthCount

func (a *DefaultAccount) ResetGracefulAuthCount()

func (*DefaultAccount) RoleNames

func (a *DefaultAccount) RoleNames() []string

func (*DefaultAccount) SerialFailedAttempts

func (a *DefaultAccount) SerialFailedAttempts() int

func (*DefaultAccount) TenantId

func (a *DefaultAccount) TenantId() string

func (*DefaultAccount) Type

func (a *DefaultAccount) Type() AccountType

func (*DefaultAccount) UnlockAccount

func (a *DefaultAccount) UnlockAccount()

func (*DefaultAccount) UseMFA

func (a *DefaultAccount) UseMFA() bool

func (*DefaultAccount) Username

func (a *DefaultAccount) Username() string

func (*DefaultAccount) Value

func (a *DefaultAccount) Value(key string) interface{}

type DefaultAuthenticationErrorHandler

type DefaultAuthenticationErrorHandler struct {
}

DefaultAuthenticationErrorHandler implements AuthenticationErrorHandler

func (*DefaultAuthenticationErrorHandler) HandleAuthenticationError

func (h *DefaultAuthenticationErrorHandler) HandleAuthenticationError(ctx context.Context, r *http.Request, rw http.ResponseWriter, err error)

type DefaultErrorHandler

type DefaultErrorHandler struct{}

DefaultErrorHandler implements ErrorHandler

func (*DefaultErrorHandler) HandleError

func (h *DefaultErrorHandler) HandleError(ctx context.Context, r *http.Request, rw http.ResponseWriter, err error)

type DefaultIssuer

type DefaultIssuer struct {
	DefaultIssuerDetails
}

func NewIssuer

func NewIssuer(opts ...func(*DefaultIssuerDetails)) *DefaultIssuer

func (DefaultIssuer) BuildUrl

func (i DefaultIssuer) BuildUrl(options ...UrlBuilderOptions) (*url.URL, error)

func (DefaultIssuer) ContextPath

func (i DefaultIssuer) ContextPath() string

func (DefaultIssuer) Domain

func (i DefaultIssuer) Domain() string

func (DefaultIssuer) Identifier

func (i DefaultIssuer) Identifier() string

func (DefaultIssuer) IsSecured

func (i DefaultIssuer) IsSecured() bool

func (DefaultIssuer) LevelOfAssurance

func (i DefaultIssuer) LevelOfAssurance(level int) string

func (DefaultIssuer) Port

func (i DefaultIssuer) Port() int

func (DefaultIssuer) Protocol

func (i DefaultIssuer) Protocol() string

type DefaultIssuerDetails

type DefaultIssuerDetails struct {
	Protocol    string
	Domain      string
	Port        int
	ContextPath string
	IncludePort bool
}

type EmptyAuthentication

type EmptyAuthentication string

EmptyAuthentication represent unauthenticated user. Note: anonymous user is considered authenticated

func (EmptyAuthentication) Details

func (EmptyAuthentication) Details() interface{}

func (EmptyAuthentication) Permissions

func (EmptyAuthentication) Permissions() Permissions

func (EmptyAuthentication) Principal

func (EmptyAuthentication) Principal() interface{}

func (EmptyAuthentication) State

type ErrorHandler

type ErrorHandler interface {
	HandleError(context.Context, *http.Request, http.ResponseWriter, error)
}

ErrorHandler handles any other type of errors

type Feature

type Feature interface {
	Identifier() FeatureIdentifier
}

Feature holds security settings of specific feature. Any Feature should have a corresponding FeatureConfigurer

type FeatureConfigurer

type FeatureConfigurer interface {
	Apply(Feature, WebSecurity) error
}

FeatureConfigurer not intended to be used directly in service

type FeatureIdentifier

type FeatureIdentifier interface {
	fmt.Stringer
	fmt.GoStringer
}

FeatureIdentifier is unique for each feature. Security initializer use this value to locate corresponding FeatureConfigurer or sort configuration order

func FeatureId

func FeatureId(id string, order int) FeatureIdentifier

FeatureId create an ordered FeatureIdentifier

func PriorityFeatureId

func PriorityFeatureId(id string, order int) FeatureIdentifier

PriorityFeatureId create a priority ordered FeatureIdentifier

func SimpleFeatureId

func SimpleFeatureId(id string) FeatureIdentifier

SimpleFeatureId create unordered FeatureIdentifier

type FeatureModifier

type FeatureModifier interface {
	// Enable kick off configuration of give Feature.
	// If the given Feature is not enabled yet, it's added to the receiver and returned
	// If the given Feature is already enabled, the already enabled Feature is returned
	Enable(Feature) Feature
	// Disable remove given feature using its FeatureIdentifier
	Disable(Feature)
}

FeatureModifier add or remove features. \ Should not used directly by service use corresponding feature's Configure(WebSecurity) instead

type FeatureRegistrar

type FeatureRegistrar interface {
	// RegisterFeature is typically used by feature packages, such as session, oauth, etc
	// not intended to be used directly in service
	RegisterFeature(featureId FeatureIdentifier, featureConfigurer FeatureConfigurer)

	// FindFeature is typically used by feature packages
	FindFeature(featureId FeatureIdentifier) FeatureConfigurer
}

type FederatedAccountStore

type FederatedAccountStore interface {
	LoadAccountByExternalId(ctx context.Context, externalIdName string, externalIdValue string, externalIdpName string, autoCreateUserDetails AutoCreateUserDetails, rawAssertion interface{}) (Account, error)
}

type GlobalSettingReader

type GlobalSettingReader interface {
	// Read setting of given key into "dest". Should support types:
	// 	- *[]byte
	// 	- *string
	// 	- *bool
	//	- *int
	Read(ctx context.Context, key string, dest interface{}) error
}

type Initializer

type Initializer interface {
	// Initialize is the entry point for all security configuration.
	// Microservice or other library packages typically call this in Provide or Invoke functions
	// Note: use this function inside fx.Lifecycle takes no effect
	Initialize(ctx context.Context, lc fx.Lifecycle, registrar *web.Registrar) error
}

Initializer is the entry point to bootstrap security

type Issuer

type Issuer interface {
	Protocol() string
	Domain() string
	Port() int
	ContextPath() string
	IsSecured() bool

	// Identifier is the unique identifier of the deployed auth server
	// Typeical implementation is to use base url of issuer's domain.
	Identifier() string

	// LevelOfAssurance construct level-of-assurance string with given string
	// level-of-assurance represent how confident the auth issuer is about user's identity
	// ref: https://developer.mobileconnect.io/level-of-assurance
	LevelOfAssurance(level int) string

	// BuildUrl build a URL with given url builder options
	// Implementation specs:
	// 	1. if UrlBuilderOption.FQDN is not specified, Issuer.Domain() should be used
	//  2. if UrlBuilderOption.FQDN is not a subdomain of Issuer.Domain(), an error should be returned
	//  3. should assume UrlBuilderOption.Path doesn't includes Issuer.ContextPath and the generated URL always
	//	   include Issuer.ContextPath
	//  4. if UrlBuilderOption.Path is not specified, the generated URL could be used as a base URL
	//	5. BuildUrl should not returns error when no options provided
	BuildUrl(...UrlBuilderOptions) (*url.URL, error)
}

type KeyValueDetails

type KeyValueDetails interface {
	Value(string) (interface{}, bool)
	Values() map[string]interface{}
}

type MiddlewareTemplate

type MiddlewareTemplate *middleware.MappingBuilder

MiddlewareTemplate is partially configured middleware.MappingBuilder. it holds the middleware's gin.HandlerFunc and order if its route matcher and condition is not set, WebSecurity would make it matches WebSecurity's own values

type Permissions

type Permissions map[string]interface{}

func (Permissions) Has

func (p Permissions) Has(permission string) bool

type Provider

type Provider struct {
	Id               string
	Name             string
	DisplayName      string
	Description      string
	LocaleCode       string
	NotificationType string
	Email            string
}

type ProviderDetails

type ProviderDetails interface {
	ProviderId() string
	ProviderName() string
	ProviderDisplayName() string
	ProviderDescription() string
	ProviderEmail() string
	ProviderNotificationType() string
}

ProviderDetails is available if tenant is selected (tenant dictates provider)

type ProviderStore

type ProviderStore interface {
	LoadProviderById(ctx context.Context, id string) (*Provider, error)
}

type ProxiedUserDetails

type ProxiedUserDetails interface {
	OriginalUsername() string
	Proxied() bool
}

type Registrar

type Registrar interface {
	// Register is the entry point for all security configuration.
	// Microservice or other library packages typically call this in Provide or Invoke functions
	// Note: use this function inside fx.Lifecycle takes no effect
	Register(...Configurer)
}

Registrar is the entry point to configure security

type SessionProperties

type SessionProperties struct {
	Cookie               CookieProperties
	IdleTimeout          utils.Duration `json:"idle-timeout"`
	AbsoluteTimeout      utils.Duration `json:"absolute-timeout"`
	MaxConcurrentSession int            `json:"max-concurrent-sessions"`
	DbIndex              int            `json:"db-index"`
}

func BindSessionProperties

func BindSessionProperties(ctx *bootstrap.ApplicationContext) SessionProperties

BindSessionProperties create and bind SessionProperties, with a optional prefix

func NewSessionProperties

func NewSessionProperties() *SessionProperties

NewSessionProperties create a SessionProperties with default values

type SimpleMappingTemplate

type SimpleMappingTemplate *mapping.MappingBuilder

SimpleMappingTemplate is partially configured mapping.MappingBuilder it holds the simple mapping's path, gin.HandlerFunc and order if its condition is not set, WebSecurity would make it matches WebSecurity's own values

type Tenant

type Tenant struct {
	Id           string
	ExternalId   string
	DisplayName  string
	Description  string
	ProviderId   string
	Suspended    bool
	CurrencyCode string
	LocaleCode   string
}

type TenantDetails

type TenantDetails interface {
	TenantId() string
	TenantExternalId() string
	TenantSuspended() bool
}

TenantDetails is available in the following scenarios:

user auth, tenant can be determined (either selected tenant, or there is a default tenant)
client auth, tenant can be determined (either selected tenant, or there is a default tenant)

type TenantStore

type TenantStore interface {
	LoadTenantById(ctx context.Context, id string) (*Tenant, error)
	LoadTenantByExternalId(ctx context.Context, name string) (*Tenant, error)
}

type TimeoutSupportProperties

type TimeoutSupportProperties struct {
	DbIndex int `json:"db-index"`
}

func NewTimeoutSupportProperties

func NewTimeoutSupportProperties() *TimeoutSupportProperties

type UrlBuilderOption

type UrlBuilderOption struct {
	FQDN string
	Path string
}

type UrlBuilderOptions

type UrlBuilderOptions func(opt *UrlBuilderOption)

type UserDetails

type UserDetails interface {
	UserId() string
	Username() string
	AccountType() AccountType
	// AssignedTenantIds
	// Deprecated: usage of this method is not encouraged. Designs that require user to select tenancy is preferred
	// i.e. design tenancy based on TenantDetails instead.
	AssignedTenantIds() utils.StringSet
	LocaleCode() string
	CurrencyCode() string
	FirstName() string
	LastName() string
	Email() string
}

UserDetails is available for user authentication

type WebSecurity

type WebSecurity interface {

	// Context returns the context associated with the WebSecurity.
	// It's typlically holds bootstrap.ApplicationContext or its derived context
	// this should not returns nil
	Context() context.Context

	// Route configure the path and method pattern which this WebSecurity applies to
	// Calling this method multiple times concatenate all given matchers with OR operator
	Route(web.RouteMatcher) WebSecurity

	// Condition sets additional conditions of incoming request which this WebSecurity applies to
	// Calling this method multiple times concatenate all given matchers with OR operator
	Condition(mwcm web.RequestMatcher) WebSecurity

	// AndCondition sets additional conditions of incoming request which this WebSecurity applies to
	// Calling this method multiple times concatenate all given matchers with AND operator
	AndCondition(mwcm web.RequestMatcher) WebSecurity

	// Add is DSL style setter to add:
	// - MiddlewareTemplate
	// - web.MiddlewareMapping
	// - web.MvcMapping
	// - web.StaticMapping
	// - web.SimpleMapping
	// when MiddlewareTemplate is given, WebSecurity's Route and Condition are applied to it
	// this method panic if other type is given
	Add(...interface{}) WebSecurity

	// Remove is DSL style setter to remove:
	// - MiddlewareTemplate
	// - web.MiddlewareMapping
	// - web.MvcMapping
	// - web.StaticMapping
	// - web.SimpleMapping
	Remove(...interface{}) WebSecurity

	// With is DSL style setter to enable features
	With(f Feature) WebSecurity

	// Shared get shared value
	Shared(key string) interface{}

	// AddShared add shared value. returns error when the key already exists
	AddShared(key string, value interface{}) error

	// Authenticator returns Authenticator
	Authenticator() Authenticator

	// Features get currently configured Feature list
	Features() []Feature
}

WebSecurity holds information on security configuration

type WebSecurityMappingBuilder

type WebSecurityMappingBuilder interface {
	Build() []web.Mapping
}

type WebSecurityReader

type WebSecurityReader interface {
	GetRoute() web.RouteMatcher
	GetCondition() web.RequestMatcher
	GetHandlers() []interface{}
}

Jump to

Keyboard shortcuts

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