Documentation
¶
Index ¶
- Variables
- func BeginRegistration(ctx *gin.Context)
- func ComputeBruteForceHints(ctx context.Context, clientIP, protocol, oidccid string) (clientNet string, repeating bool)
- func ConsentGETHandler(ctx *gin.Context)
- func ConsentPOSTHandler(ctx *gin.Context)
- func DeviceGETHandler(ctx *gin.Context)
- func DevicePOSTHandler(ctx *gin.Context)
- func ExtractJWTToken(ctx *gin.Context) (string, error)
- func FinishRegistration(ctx *gin.Context)
- func GenerateJWTToken(username string, roles []string) (string, int64, error)
- func GenerateRefreshToken(username string) (string, error)
- func GetRefreshTokenFromRedis(ctx context.Context, username string) (string, error)
- func GetTokenFromRedis(ctx context.Context, username string) (string, error)
- func HandleBackendErrors(passDBIndex int, passDBs []*PassDBMap, passDB *PassDBMap, err error, ...) error
- func HandleBruteForceRuleFlush(ctx *gin.Context)
- func HandleConfigLoad(ctx *gin.Context)
- func HandleErr(ctx *gin.Context, err error)
- func HandleJSONError(ctx *gin.Context, err error)
- func HandleJWTTokenGeneration(ctx *gin.Context)
- func HandleJWTTokenRefresh(ctx *gin.Context)
- func HandleUserFlush(ctx *gin.Context)
- func HanldeBruteForceList(ctx *gin.Context)
- func InitHTTPClient()
- func InitPassDBResultPool()
- func JWTAuthMiddleware() gin.HandlerFunc
- func ListBackendServers() []*config.BackendServer
- func LoadStatsFromRedis(ctx context.Context)
- func LoginGET2FAHandler(ctx *gin.Context)
- func LoginGETHandler(ctx *gin.Context)
- func LoginPOST2FAHandler(ctx *gin.Context)
- func LoginPOSTHandler(ctx *gin.Context)
- func LogoutGETHandler(ctx *gin.Context)
- func LogoutPOSTHandler(ctx *gin.Context)
- func NewTOTPSecret(value string) *mfamodel.TOTPSecret
- func NewWebAuthn(value string) *mfamodel.WebAuthn
- func NotifyGETHandler(ctx *gin.Context)
- func ProcessPassDBResult(ctx *gin.Context, passDBResult *PassDBResult, auth *AuthState, ...) error
- func ProtectEndpointMiddleware() gin.HandlerFunc
- func PutPassDBResultToPool(obj *PassDBResult)
- func RBLIsListed(ctx *gin.Context, view *StateView, rbl *config.RBL) (bool, string, error)
- func Register2FAHomeHandler(ctx *gin.Context)
- func RegisterActionDispatcher(a ActionDispatcher)
- func RegisterBruteForceService(b BruteForceService)
- func RegisterCacheService(c CacheService)
- func RegisterFeatureEngine(f FeatureEngine)
- func RegisterLuaFilter(l LuaFilter)
- func RegisterPasswordVerifier(v PasswordVerifier)
- func RegisterPostAction(p PostAction)
- func RegisterRBLService(r RBLService)
- func RegisterTotpGETHandler(ctx *gin.Context)
- func RegisterTotpPOSTHandler(ctx *gin.Context)
- func RunLuaPostAction(args PostActionArgs)
- func SaveStatsToRedis(ctx context.Context)
- func StoreRefreshTokenInRedis(ctx context.Context, username, refreshToken string) error
- func StoreTokenInRedis(ctx context.Context, username, token string, expiresAt int64) error
- func UpdateRedisPoolStats()
- func ValidateJWTToken(ctx context.Context, tokenString string) (*jwtclaims.Claims, error)
- func WithLanguageMiddleware() gin.HandlerFunc
- type AccountList
- type AccountListMap
- type AccountListOption
- type ActionDispatcher
- type AddTOTPSecretFunc
- type AuthContext
- type AuthContextOption
- func WithClientHostname(h string) AuthContextOption
- func WithClientID(id string) AuthContextOption
- func WithClientIP(ip string) AuthContextOption
- func WithClientPort(p string) AuthContextOption
- func WithLocalIP(ip string) AuthContextOption
- func WithLocalPort(p string) AuthContextOption
- func WithMethod(m string) AuthContextOption
- func WithOIDCCID(v string) AuthContextOption
- func WithProtocol(proto string) AuthContextOption
- func WithSSLFingerprint(v string) AuthContextOption
- func WithSSLSerial(v string) AuthContextOption
- func WithUserAgent(ua string) AuthContextOption
- func WithXSSL(v string) AuthContextOption
- func WithXSSLCipher(v string) AuthContextOption
- func WithXSSLClientCN(v string) AuthContextOption
- func WithXSSLClientDN(v string) AuthContextOption
- func WithXSSLClientIssuerDN(v string) AuthContextOption
- func WithXSSLClientNotAfter(v string) AuthContextOption
- func WithXSSLClientNotBefore(v string) AuthContextOption
- func WithXSSLClientSubjectDN(v string) AuthContextOption
- func WithXSSLClientVerify(v string) AuthContextOption
- func WithXSSLIssuer(v string) AuthContextOption
- func WithXSSLIssuerDN(v string) AuthContextOption
- func WithXSSLProtocol(v string) AuthContextOption
- func WithXSSLSessionID(v string) AuthContextOption
- func WithXSSLSubjectDN(v string) AuthContextOption
- type AuthState
- func (a *AuthState) ApplyContextData(x AuthContext)
- func (a *AuthState) ApplyCredentials(c Credentials)
- func (a *AuthState) AuthFail(ctx *gin.Context)
- func (a *AuthState) AuthOK(ctx *gin.Context)
- func (a *AuthState) AuthTempFail(ctx *gin.Context, reason string)
- func (a *AuthState) CheckBruteForce(ctx *gin.Context) (blockClientIP bool)
- func (a *AuthState) CreatePositivePasswordCache() *bktype.PositivePasswordCache
- func (a *AuthState) Ctx() context.Context
- func (a *AuthState) FeatureLua(ctx *gin.Context) (triggered bool, abortFeatures bool, err error)
- func (a *AuthState) FeatureRBLs(ctx *gin.Context) (triggered bool, err error)
- func (a *AuthState) FeatureRelayDomains() (triggered bool)
- func (a *AuthState) FeatureTLSEncryption() (triggered bool)
- func (a *AuthState) FilterLua(passDBResult *PassDBResult, ctx *gin.Context) definitions.AuthResult
- func (a *AuthState) GetAccount() string
- func (a *AuthState) GetAccountField() string
- func (a *AuthState) GetAccountOk() (string, bool)
- func (a *AuthState) GetAdditionalLogs() []any
- func (a *AuthState) GetAttributes() bktype.AttributeMapping
- func (a *AuthState) GetCacheNameFor(usedBackend definitions.CacheNameBackend) (cacheName string, err error)
- func (a *AuthState) GetClientIP() string
- func (a *AuthState) GetDisplayName() string
- func (a *AuthState) GetDisplayNameField() string
- func (a *AuthState) GetDisplayNameOk() (string, bool)
- func (a *AuthState) GetFromLocalCache(ctx *gin.Context) bool
- func (a *AuthState) GetGUID() string
- func (a *AuthState) GetPassword() string
- func (a *AuthState) GetProtocol() *config.Protocol
- func (a *AuthState) GetTOTPRecoveryField() string
- func (a *AuthState) GetTOTPSecret() string
- func (a *AuthState) GetTOTPSecretField() string
- func (a *AuthState) GetTOTPSecretOk() (string, bool)
- func (a *AuthState) GetUniqueUserID() string
- func (a *AuthState) GetUniqueUserIDField() string
- func (a *AuthState) GetUniqueUserIDOk() (string, bool)
- func (a *AuthState) GetUsedCacheBackend() (definitions.CacheNameBackend, error)
- func (a *AuthState) GetUsedPassDBBackend() definitions.Backend
- func (a *AuthState) GetUsername() string
- func (a *AuthState) HandleAuthentication(ctx *gin.Context)
- func (a *AuthState) HandleFeatures(ctx *gin.Context) definitions.AuthResult
- func (a *AuthState) HandlePassword(ctx *gin.Context) (authResult definitions.AuthResult)
- func (a *AuthState) HasJWTRole(ctx *gin.Context, role string) bool
- func (a *AuthState) HaveMonitoringFlag(flag definitions.Monitoring) bool
- func (a *AuthState) InitMethodAndUserAgent() State
- func (a *AuthState) IsInNetwork(networkList []string) (matchIP bool)
- func (a *AuthState) IsMasterUser() bool
- func (a *AuthState) ListUserAccounts() (accountList AccountList)
- func (a *AuthState) LogLineProcessingTemplate(endpoint string) []any
- func (a *AuthState) LogLineTemplate(status string, endpoint string) []any
- func (a *AuthState) PostLuaAction(passDBResult *PassDBResult)
- func (a *AuthState) PreproccessAuthRequest(ctx *gin.Context) (reject bool)
- func (a *AuthState) ProcessAuthentication(ctx *gin.Context)
- func (a *AuthState) ProcessFeatures(ctx *gin.Context) (abort bool)
- func (a *AuthState) SFKeyHash() string
- func (a *AuthState) SetClientHost(clientHost string)
- func (a *AuthState) SetClientID(clientID string)
- func (a *AuthState) SetClientIP(clientIP string)
- func (a *AuthState) SetClientPort(clientPort string)
- func (a *AuthState) SetLocalIP(localIP string)
- func (a *AuthState) SetLocalPort(port string)
- func (a *AuthState) SetLoginAttempts(loginAttempts uint)
- func (a *AuthState) SetMethod(method string)
- func (a *AuthState) SetNoAuth(noAuth bool)
- func (a *AuthState) SetOIDCCID(oidcCID string)
- func (a *AuthState) SetOperationMode(ctx *gin.Context)
- func (a *AuthState) SetPassword(password string)
- func (a *AuthState) SetProtocol(protocol *config.Protocol)
- func (a *AuthState) SetSSL(ssl string)
- func (a *AuthState) SetSSLCipher(sslCipher string)
- func (a *AuthState) SetSSLClientCN(sslClientCN string)
- func (a *AuthState) SetSSLClientDN(sslClientDN string)
- func (a *AuthState) SetSSLClientIssuerDN(sslClientIssuerDN string)
- func (a *AuthState) SetSSLClientNotAfter(sslClientNotAfter string)
- func (a *AuthState) SetSSLClientNotBefore(sslClientNotBefore string)
- func (a *AuthState) SetSSLClientSubjectDN(sslClientSubjectDN string)
- func (a *AuthState) SetSSLClientVerify(sslClientVerify string)
- func (a *AuthState) SetSSLFingerprint(sslFingerprint string)
- func (a *AuthState) SetSSLIssuer(xSSLIssuer string)
- func (a *AuthState) SetSSLIssuerDN(xSSLIssuerDN string)
- func (a *AuthState) SetSSLProtocol(sslProtocol string)
- func (a *AuthState) SetSSLSerial(sslSerial string)
- func (a *AuthState) SetSSLSessionID(sslSessionID string)
- func (a *AuthState) SetSSLSubjectDN(sslSubjectDN string)
- func (a *AuthState) SetStatusCodes(service string)
- func (a *AuthState) SetUserAgent(userAgent string)
- func (a *AuthState) SetUsername(username string)
- func (a *AuthState) String() string
- func (a *AuthState) UpdateBruteForceBucketsCounter(ctx *gin.Context)
- func (a *AuthState) View() *StateView
- func (a *AuthState) WithClientInfo(ctx *gin.Context) State
- func (a *AuthState) WithDefaults(ctx *gin.Context) State
- func (a *AuthState) WithLocalInfo(ctx *gin.Context) State
- func (a *AuthState) WithUserAgent(ctx *gin.Context) State
- func (a *AuthState) WithXSSL(ctx *gin.Context) State
- type Authenticator
- type BackendManager
- type BackendServer
- type Bootstrap
- type BruteForceService
- type CacheService
- type ClaimHandler
- type CredentialOption
- type Credentials
- type DefaultBootstrap
- type DefaultHTTPApp
- type DefaultHTTPServerFactory
- type DefaultResponseWriter
- type DefaultRouterComposer
- func (DefaultRouterComposer) ApplyCoreMiddlewares(r *gin.Engine)
- func (DefaultRouterComposer) ApplyEarlyMiddlewares(r *gin.Engine)
- func (DefaultRouterComposer) ComposeEngine() *gin.Engine
- func (DefaultRouterComposer) RegisterRoutes(r *gin.Engine, setupHealth func(*gin.Engine), setupMetrics func(*gin.Engine), ...)
- type DefaultServerSignals
- type DefaultTLSConfigurator
- type DefaultTransportRunner
- type Done
- type FeatureEngine
- type FieldMapping
- type HAProxyListenerProvider
- type HTTPApplication
- type HTTPServerFactory
- type JSONErrorMsg
- type LuaFilter
- type Metric
- type PassDBMap
- type PassDBOption
- type PassDBResult
- type PasswordVerifier
- type PostAction
- type PostActionArgs
- type PostActionInput
- type ProxyListenerProvider
- type RBLService
- type ResponseWriter
- type RouterComposer
- type SFOutcome
- type ServerSignals
- type State
- type StateView
- type TLSConfigurator
- type TransportRunner
- type WebAuthnCredentialDBFunc
Constants ¶
This section is empty.
Variables ¶
var BackendServers = NewBackendServer()
var LangBundle *i18n.Bundle
LangBundle holds the application's i18n bundle. It was previously located in http.go; moved here to decouple i18n from HTTP server wiring.
Functions ¶
func BeginRegistration ¶ added in v1.3.9
BeginRegistration is disabled when built without hydra.
func ComputeBruteForceHints ¶ added in v1.11.0
func ComputeBruteForceHints(ctx context.Context, clientIP, protocol, oidccid string) (clientNet string, repeating bool)
ComputeBruteForceHints derives clientNet and repeating fields for the post action based on config rules, protocol and optional OIDC client id. The logic matches the previous inline implementation used by ExecuteLuaPostAction.
func ConsentGETHandler ¶ added in v1.3.9
ConsentGETHandler handles GET requests to the '/consent' endpoint, returning a not found status when Hydra is disabled.
func ConsentPOSTHandler ¶ added in v1.3.9
ConsentPOSTHandler handles POST requests to the '/consent' endpoint, indicating that Hydra is disabled with a 404 response.
func DeviceGETHandler ¶ added in v1.3.9
DeviceGETHandler handles GET requests for the device login page, currently returning a 404 Not Found indicating "hydra disabled".
func DevicePOSTHandler ¶ added in v1.3.9
DevicePOSTHandler handles POST requests for the device authentication page, returning a 404 response if disabled.
func ExtractJWTToken ¶ added in v1.7.0
ExtractJWTToken extracts the JWT token from the Authorization header
func FinishRegistration ¶ added in v1.3.9
FinishRegistration is disabled when built without hydra.
func GenerateJWTToken ¶ added in v1.7.0
GenerateJWTToken generates a JWT token for the given username and roles
func GenerateRefreshToken ¶ added in v1.7.0
GenerateRefreshToken generates a refresh token for the given username
func GetRefreshTokenFromRedis ¶ added in v1.7.0
GetRefreshTokenFromRedis retrieves a JWT refresh token from Redis
func GetTokenFromRedis ¶ added in v1.7.0
GetTokenFromRedis retrieves a JWT token from Redis
func HandleBackendErrors ¶ added in v1.11.0
func HandleBackendErrors(passDBIndex int, passDBs []*PassDBMap, passDB *PassDBMap, err error, auth *AuthState, configErrors map[definitions.Backend]error) error
HandleBackendErrors handles the errors that occur during backend processing. It checks if the error is a configuration error for SQL, LDAP, or Lua backends and adds them to the configErrors map. If all password databases have been processed and there are configuration errors, it calls the checkAllBackends function. If the error is not a configuration error, it logs the error using the Logger. It returns the error unchanged.
func HandleBruteForceRuleFlush ¶ added in v1.3.9
HandleBruteForceRuleFlush handles the flushing of brute force rules for a given IP address and rule criteria. It processes the request, binds JSON input, validates data, performs the flush operation, and returns the result. The function logs the operation details, including rule applicability, flushed keys, and any encountered errors.
func HandleConfigLoad ¶ added in v1.7.11
HandleConfigLoad handles loading the server configuration and applies necessary JWT authentication checks. This function validates a provided JWT token for required roles when authentication is enabled. If JWT authentication fails, appropriate HTTP error responses are returned, such as Unauthorized or Forbidden. On success, it retrieves the server configuration as JSON and binds it to the request context.
func HandleErr ¶ added in v1.3.9
HandleErr renders a minimal error response when Hydra is disabled. It ensures core packages can signal errors uniformly across build variants.
func HandleJSONError ¶ added in v1.3.9
HandleJSONError handles JSON validation errors by aborting the request and returning a JSON response with error details.
func HandleJWTTokenGeneration ¶ added in v1.7.0
HandleJWTTokenGeneration handles the JWT token generation endpoint
func HandleJWTTokenRefresh ¶ added in v1.7.0
HandleJWTTokenRefresh handles the JWT token refresh endpoint
func HandleUserFlush ¶ added in v1.3.9
HandleUserFlush handles a user cache flush request by processing the input, flushing relevant cache keys, and sending a response.
func HanldeBruteForceList ¶ added in v1.3.9
HanldeBruteForceList lists all blocked IP addresses and accounts in response to a brute force attack event.
func InitHTTPClient ¶ added in v1.3.0
func InitHTTPClient()
InitHTTPClient is a no-op placeholder when building without the hydra tag. It maintains API parity with the hydra-enabled build where an HTTP client is initialized.
func InitPassDBResultPool ¶ added in v1.7.3
func InitPassDBResultPool()
InitPassDBResultPool initializes the PassDBResultPool in the objpool package This function should be called during application initialization
func JWTAuthMiddleware ¶ added in v1.7.0
func JWTAuthMiddleware() gin.HandlerFunc
JWTAuthMiddleware is a middleware that validates JWT tokens
func ListBackendServers ¶ added in v1.11.0
func ListBackendServers() []*config.BackendServer
ListBackendServers returns the current slice of configured backend servers. This accessor allows subpackages to read the list without exposing internal fields.
func LoadStatsFromRedis ¶
LoadStatsFromRedis loads the prometheus statistics at startup from a Redis server.
func LoginGET2FAHandler ¶ added in v1.3.9
LoginGET2FAHandler handles GET requests for the 2FA page, responding with a "hydra disabled" message when not enabled.
func LoginGETHandler ¶ added in v1.3.9
LoginGETHandler handles GET requests for the login endpoint, returning a 404 status if the service is disabled.
func LoginPOST2FAHandler ¶ added in v1.3.9
LoginPOST2FAHandler handles POST requests for 2FA registration, processing TOTP-based two-factor authentication logic.
func LoginPOSTHandler ¶ added in v1.3.9
LoginPOSTHandler handles POST requests to the login page, managing login flow, authentication validation, and optional 2FA logic.
func LogoutGETHandler ¶ added in v1.3.9
LogoutGETHandler manages GET requests to the '/logout' endpoint, returning a 404 status when the Hydra service is disabled.
func LogoutPOSTHandler ¶ added in v1.3.9
LogoutPOSTHandler handles POST requests to the '/logout/post' endpoint, returning a 404 status when Hydra is disabled.
func NewTOTPSecret ¶
func NewTOTPSecret(value string) *mfamodel.TOTPSecret
NewTOTPSecret creates a new TOTPSecret instance using the provided secret value. It returns a pointer to the created TOTPSecret object.
func NewWebAuthn ¶
NewWebAuthn creates and returns a new WebAuthn object initialized with the provided value.
func NotifyGETHandler ¶ added in v1.3.9
NotifyGETHandler handles GET requests for the notification page, returning a 404 status indicating Hydra is disabled.
func ProcessPassDBResult ¶ added in v1.11.0
func ProcessPassDBResult(ctx *gin.Context, passDBResult *PassDBResult, auth *AuthState, passDB *PassDBMap) error
ProcessPassDBResult updates the passDBResult based on the provided passDB and the AuthState object a. If passDBResult is nil, it returns an error of type errors.ErrNoPassDBResult. It then calls the util.DebugModule function to log debug information. Next, it calls the updateAuthentication function to update the fields of a based on the values in passDBResult. If the UserFound field of passDBResult is true, it sets the UserFound field of a to true. Finally, it returns the updated passDBResult and nil error.
func ProtectEndpointMiddleware ¶ added in v1.3.9
func ProtectEndpointMiddleware() gin.HandlerFunc
ProtectEndpointMiddleware is a Gin middleware that performs authentication and security checks for HTTP requests. It handles client IP extraction, brute force detection, protocol handling, and various authentication features.
func PutPassDBResultToPool ¶ added in v1.7.3
func PutPassDBResultToPool(obj *PassDBResult)
PutPassDBResultToPool returns a PassDBResult object to the pool The object is reset before being returned to the pool
func RBLIsListed ¶ added in v1.11.0
RBLIsListed is a small wrapper exposing the internal isListed logic to subpackages without duplicating implementation details. It accepts a StateView to avoid import cycles.
func Register2FAHomeHandler ¶ added in v1.3.9
Register2FAHomeHandler serves the '/2fa/v1/register/home' endpoint, providing a response when 2FA features are unavailable.
func RegisterActionDispatcher ¶ added in v1.11.0
func RegisterActionDispatcher(a ActionDispatcher)
RegisterActionDispatcher registers the active ActionDispatcher implementation.
func RegisterBruteForceService ¶ added in v1.11.0
func RegisterBruteForceService(b BruteForceService)
RegisterBruteForceService registers the active BruteForceService implementation.
func RegisterCacheService ¶ added in v1.11.0
func RegisterCacheService(c CacheService)
RegisterCacheService registers the active CacheService implementation.
func RegisterFeatureEngine ¶ added in v1.11.0
func RegisterFeatureEngine(f FeatureEngine)
RegisterFeatureEngine registers the active FeatureEngine implementation.
func RegisterLuaFilter ¶ added in v1.11.0
func RegisterLuaFilter(l LuaFilter)
RegisterLuaFilter registers the active LuaFilter implementation.
func RegisterPasswordVerifier ¶ added in v1.11.0
func RegisterPasswordVerifier(v PasswordVerifier)
RegisterPasswordVerifier registers the active PasswordVerifier implementation.
func RegisterPostAction ¶ added in v1.11.0
func RegisterPostAction(p PostAction)
RegisterPostAction registers the active PostAction implementation.
func RegisterRBLService ¶ added in v1.11.0
func RegisterRBLService(r RBLService)
RegisterRBLService registers the active RBLService implementation.
func RegisterTotpGETHandler ¶ added in v1.3.9
RegisterTotpGETHandler serves the TOTP registration page and responds with a "hydra disabled" message if not enabled.
func RegisterTotpPOSTHandler ¶ added in v1.3.9
RegisterTotpPOSTHandler handles POST requests for TOTP registration and returns a 404 status if the feature is disabled.
func RunLuaPostAction ¶ added in v1.11.0
func RunLuaPostAction(args PostActionArgs)
RunLuaPostAction enqueues a Lua post action on the worker channel using the pooled CommonRequest object. It mirrors prior behavior and preserves metrics.
func SaveStatsToRedis ¶
SaveStatsToRedis saves the prometheus statistics to a Redis server.
func StoreRefreshTokenInRedis ¶ added in v1.7.0
StoreRefreshTokenInRedis stores a JWT refresh token in Redis for multi-instance compatibility
func StoreTokenInRedis ¶ added in v1.7.0
StoreTokenInRedis stores a JWT token in Redis for multi-instance compatibility
func UpdateRedisPoolStats ¶ added in v1.3.3
func UpdateRedisPoolStats()
UpdateRedisPoolStats updates and tracks Redis pool statistics such as hits, misses, timeouts, and connection counts.
func ValidateJWTToken ¶ added in v1.7.0
ValidateJWTToken validates a JWT token and returns the claims
func WithLanguageMiddleware ¶ added in v1.3.9
func WithLanguageMiddleware() gin.HandlerFunc
WithLanguageMiddleware provides a no-op language middleware in non-hydra builds. It preserves the handler chain shape without introducing i18n or CSRF concerns here.
Types ¶
type AccountList ¶
type AccountList []string
AccountList is a slice of strings containing the list of all user accounts.
type AccountListMap ¶
type AccountListMap struct {
// contains filtered or unexported fields
}
AccountListMap is a struct type that represents a mapping between a backend and an account list option function for authentication.
type AccountListOption ¶
type AccountListOption func(a *AuthState) (AccountList, error)
AccountListOption is the function signature for an account Database.
type ActionDispatcher ¶ added in v1.11.0
type ActionDispatcher interface {
Dispatch(view *StateView, featureName string, luaAction definitions.LuaAction)
}
ActionDispatcher encapsulates triggering Lua actions (performAction).
func GetActionDispatcher ¶ added in v1.11.0
func GetActionDispatcher() ActionDispatcher
type AddTOTPSecretFunc ¶
type AddTOTPSecretFunc func(auth *AuthState, totp *mfa.TOTPSecret) (err error)
AddTOTPSecretFunc is a function signature that takes a *AuthState and *TOTPSecret as arguments and returns an error.
type AuthContext ¶ added in v1.11.0
type AuthContext struct {
Method string
UserAgent string
ClientIP string
ClientPort string
ClientHostname string
ClientID string
LocalIP string
LocalPort string
Protocol string
XSSL string
XSSLSessionID string
XSSLClientVerify string
XSSLClientDN string
XSSLClientCN string
XSSLIssuer string
XSSLClientNotBefore string
XSSLClientNotAfter string
XSSLSubjectDN string
XSSLIssuerDN string
XSSLClientSubjectDN string
XSSLClientIssuerDN string
XSSLProtocol string
XSSLCipher string
SSLSerial string
SSLFingerprint string
OIDCCID string
}
AuthContext contains request/connection metadata that influences authentication. It is applied to AuthState via ApplyContextData.
Only non-empty fields are applied to avoid altering existing precedence.
func NewAuthContext ¶ added in v1.11.0
func NewAuthContext(opts ...AuthContextOption) AuthContext
NewAuthContext constructs an AuthContext value using the provided options.
type AuthContextOption ¶ added in v1.11.0
type AuthContextOption func(*AuthContext)
AuthContextOption mutates an AuthContext during construction.
func WithClientHostname ¶ added in v1.11.0
func WithClientHostname(h string) AuthContextOption
func WithClientID ¶ added in v1.11.0
func WithClientID(id string) AuthContextOption
func WithClientIP ¶ added in v1.11.0
func WithClientIP(ip string) AuthContextOption
func WithClientPort ¶ added in v1.11.0
func WithClientPort(p string) AuthContextOption
func WithLocalIP ¶ added in v1.11.0
func WithLocalIP(ip string) AuthContextOption
func WithLocalPort ¶ added in v1.11.0
func WithLocalPort(p string) AuthContextOption
func WithMethod ¶ added in v1.11.0
func WithMethod(m string) AuthContextOption
func WithOIDCCID ¶ added in v1.11.0
func WithOIDCCID(v string) AuthContextOption
func WithProtocol ¶ added in v1.11.0
func WithProtocol(proto string) AuthContextOption
func WithSSLFingerprint ¶ added in v1.11.0
func WithSSLFingerprint(v string) AuthContextOption
func WithSSLSerial ¶ added in v1.11.0
func WithSSLSerial(v string) AuthContextOption
func WithUserAgent ¶ added in v1.11.0
func WithUserAgent(ua string) AuthContextOption
func WithXSSL ¶ added in v1.11.0
func WithXSSL(v string) AuthContextOption
func WithXSSLCipher ¶ added in v1.11.0
func WithXSSLCipher(v string) AuthContextOption
func WithXSSLClientCN ¶ added in v1.11.0
func WithXSSLClientCN(v string) AuthContextOption
func WithXSSLClientDN ¶ added in v1.11.0
func WithXSSLClientDN(v string) AuthContextOption
func WithXSSLClientIssuerDN ¶ added in v1.11.0
func WithXSSLClientIssuerDN(v string) AuthContextOption
func WithXSSLClientNotAfter ¶ added in v1.11.0
func WithXSSLClientNotAfter(v string) AuthContextOption
func WithXSSLClientNotBefore ¶ added in v1.11.0
func WithXSSLClientNotBefore(v string) AuthContextOption
func WithXSSLClientSubjectDN ¶ added in v1.11.0
func WithXSSLClientSubjectDN(v string) AuthContextOption
func WithXSSLClientVerify ¶ added in v1.11.0
func WithXSSLClientVerify(v string) AuthContextOption
func WithXSSLIssuer ¶ added in v1.11.0
func WithXSSLIssuer(v string) AuthContextOption
func WithXSSLIssuerDN ¶ added in v1.11.0
func WithXSSLIssuerDN(v string) AuthContextOption
func WithXSSLProtocol ¶ added in v1.11.0
func WithXSSLProtocol(v string) AuthContextOption
func WithXSSLSessionID ¶ added in v1.11.0
func WithXSSLSessionID(v string) AuthContextOption
func WithXSSLSubjectDN ¶ added in v1.11.0
func WithXSSLSubjectDN(v string) AuthContextOption
type AuthState ¶ added in v1.1.2
type AuthState struct {
// StartTime represents the starting time of a client request.
StartTime time.Time
// NoAuth is a flag that is set if the request mode does not require authentication.
NoAuth bool
// ListAccounts is a flag that is set if Nauthilus is requested to send a full list of available user accounts.
ListAccounts bool
// UserFound is a flag that is set if a password Database found the user.
UserFound bool
// Authenticated indicates whether the PassDB stage concluded with a decision (success or definitive fail).
// It is false only for tempfail conditions where no decision could be made.
Authenticated bool
// Authorized indicates whether filters allowed the request. It is set by FilterLua.
Authorized bool
// PasswordsAccountSeen is a counter increased whenever a new failed password was detected for the current account.
PasswordsAccountSeen uint
// PasswordsTotalSeen is a counter increased whenever a new failed password was detected.
PasswordsTotalSeen uint
// LoginAttempts is a counter incremented for each failed login request
LoginAttempts uint
// StatusCodeOk is the HTTP status code that is set by SetStatusCodes.
StatusCodeOK int
// StatusCodeInternalError is the HTTP status code that is set by SetStatusCodes.
StatusCodeInternalError int
// StatusCodeFail is the HTTP status code that is set by SetStatusCodes.
StatusCodeFail int
// GUID is a global unique identifier inherited in all functions and methods that deal with the
// authentication process. It is necessary to track log lines belonging to one request.
GUID string
// Method is set by the "Auth-Method" HTTP request header (Nginx protocol). It is typically something like "plain"
// or "login".
Method string
// AccountField is the name of either an SQL field name or an LDAP attribute that was used to retrieve a user account.
AccountField string
// Username is the value taken from the HTTP header "Auth-User" (Nginx protocol).
Username string
// Password is the value taken from the HTTP header "Auth-Pass" (Nginx protocol).
Password string
// ClientIP is the IP of a client that is to be authenticated. The value is set by the HTTP request header
// "Client-IP" (Nginx protocol).
ClientIP string
// XClientPort adds the remote client TCP port, which is set by the HTTP request header "X-Client-Port".
XClientPort string
// ClientHost is the DNS A name of the remote client. It is set with the HTTP request header "Client-Host" (Nginx
// protocol).
ClientHost string
// HAProxy specific headers
XSSL string // %[ssl_fc]
XSSLSessionID string // %[ssl_fc_session_id,hex]
XSSLClientVerify string // %[ssl_c_verify]
XSSLClientDN string // %{+Q}[ssl_c_s_dn]
XSSLClientCN string // %{+Q}[ssl_c_s_dn(cn)]
XSSLIssuer string // %{+Q}[ssl_c_i_dn]
XSSLClientNotBefore string // %{+Q}[ssl_c_notbefore]
XSSLClientNotAfter string // %{+Q}[ssl_c_notafter]
XSSLSubjectDN string // %{+Q}[ssl_c_s_dn]
XSSLIssuerDN string // %{+Q}[ssl_c_i_dn]
XSSLClientSubjectDN string // %{+Q}[ssl_c_s_dn]
XSSLClientIssuerDN string // %{+Q}[ssl_c_i_dn]
XSSLProtocol string // %[ssl_fc_protocol]
XSSLCipher string // %[ssl_fc_cipher]
// SSLSerial represents the serial number of an SSL certificate as a string.
SSLSerial string
// SSLFingerprint represents the fingerprint of an SSL certificate.
SSLFingerprint string
// XClientID is delivered by some mail user agents when using IMAP. This value is set by the HTTP request header
// "X-Client-Id".
XClientID string
// XLocalIP is the TCP/IP address of the server that asks for authentication. Its value is set by the HTTP request
// header "X-Local-IP".
XLocalIP string
// XPort is the TCP port of the server that asks for authentication. Its value is set by the HTTP request
// header "X-Local-Port".
XPort string
// UserAgent may have been seent by a mail user agent and is set by the HTTP request header "User-Agent".
UserAgent string
// StatusMessage is the HTTP response payload that is sent to the remote server that asked for authentication.
StatusMessage string
// Service is set by Nauthilus depending on the router endpoint. Look at requestHandler for the structure of available
// endpoints.
Service string
// BruteForceName is the canonical name of a brute force bucket that was triggered by a rule.
BruteForceName string
// FeatureName is the name of a feature that has triggered a reject.
FeatureName string
BackendName string
// OIDCCID is the OIDC Client ID used for authentication.
OIDCCID string
// TOTPSecret is used to store a TOTP secret in an SQL Database.
TOTPSecret string
// TOTPSecretField is the SQL field or LDAP attribute that resolves the TOTP secret for two-factor authentication.
TOTPSecretField string
// TOTPRecoveryField NYI
TOTPRecoveryField string
// UniqueUserIDField is a string representing a unique user identifier.
UniqueUserIDField string
// DisplayNameField is the display name of a user
DisplayNameField string
// AdditionalLogging is a slice of strings that can be filled from Lua features and a Lua backend. Its result will be
// added to the regular log lines.
AdditionalLogs []any
// BruteForceCounter is a map that increments failed login requests. The key is a rule name defined in the
// configuration file.
BruteForceCounter map[string]uint
// BFClientNet is a hint: the CIDR network chosen by the brute-force path for this request (if any).
BFClientNet string
// BFRepeating is a hint: whether the request belongs to a historically known brute-force CIDR.
BFRepeating bool
// SourcePassDBBackend is a marker for the Database that is responsible for a specific user. It is set by the
// password Database and stored in Redis to track the authentication flow across databases (including proxy).
SourcePassDBBackend definitions.Backend
// UsedPassDBBackend is set by the password Database that answered the current authentication request.
UsedPassDBBackend definitions.Backend
// UsedBackendIP is set by a filter Lua script for the Nginx endpoint to set the HTTP response header 'Auth-Server'.
UsedBackendIP string
// UsedBackendPort is set by a filter Lua script for the Nginx endpoint to set the HTTP response header 'Auth-Port'.
UsedBackendPort int
// Attributes is a result container for SQL and LDAP queries. Databases store their result by using a field or
// attribute name as a key and the corresponding result as a value.
Attributes bktype.AttributeMapping
// Protocol is set by the HTTP request header "Auth-Protocol" (Nginx protocol).
Protocol *config.Protocol
// HTTPClientContext tracks the context for an HTTP client connection.
HTTPClientContext *gin.Context
// HTTPClientRequest represents the underlying HTTP request to be sent by the client.
HTTPClientRequest *http.Request
// WorkCtx, if set, overrides the context returned by Ctx(). It is used to
// enforce per-operation timeouts (e.g., singleflight work budget) without
// relying on HTTP request context.
WorkCtx context.Context
// MonitoringFlags is a slice of definitions.Monitoring that is used to skip certain steps while processing an authentication request.
MonitoringFlags []definitions.Monitoring
// MasterUserMode is a flag for a backend to indicate a master user mode is ongoing.
MasterUserMode bool
*bruteforce.PasswordHistory
*lualib.Context
}
AuthState represents a struct that holds information related to an authentication process.
func (*AuthState) ApplyContextData ¶ added in v1.11.0
func (a *AuthState) ApplyContextData(x AuthContext)
ApplyContextData applies non-empty request/connection metadata to AuthState. Only fields provided (non-empty) are applied to preserve existing precedence.
func (*AuthState) ApplyCredentials ¶ added in v1.11.0
func (a *AuthState) ApplyCredentials(c Credentials)
ApplyCredentials applies non-empty credential fields to the AuthState. This function is part of Phase 8 (setter reduction) to consolidate multiple Set* calls into a single application step without changing behavior.
func (*AuthState) AuthFail ¶ added in v1.3.9
AuthFail handles the failure of authentication. It increases the login attempts, then delegates header/logging to the ResponseWriter.
func (*AuthState) AuthOK ¶ added in v1.3.9
AuthOK is the general method to indicate authentication success.
func (*AuthState) AuthTempFail ¶ added in v1.3.9
AuthTempFail sends a temporary failure response with the provided reason and logs the error.
func (*AuthState) CheckBruteForce ¶ added in v1.3.9
CheckBruteForce checks if a client is triggering brute force detection based on predefined rules and configurations. It evaluates conditions like authentication state, IP whitelisting, protocol enforcement, and bucket rate limits. Returns true if brute force detection is triggered, and false otherwise.
func (*AuthState) CreatePositivePasswordCache ¶ added in v1.11.0
func (a *AuthState) CreatePositivePasswordCache() *bktype.PositivePasswordCache
CreatePositivePasswordCache constructs a PositivePasswordCache containing user authentication details.
func (*AuthState) Ctx ¶ added in v1.10.0
Ctx returns a standard library context for this AuthState. Preference order: 1) HTTPClientRequest.Context() if present 2) HTTPClientContext.Request.Context() if present 3) svcctx.Get() as a safe, non-nil fallback
func (*AuthState) FeatureLua ¶ added in v1.3.9
FeatureLua runs Lua scripts and returns a trigger result.
func (*AuthState) FeatureRBLs ¶ added in v1.3.9
FeatureRBLs is a method that checks if the client IP address is whitelisted, and then performs an RBL check on the client's IP address. If the RBL score exceeds the configured threshold, the 'triggered' flag is set to true. It returns the 'triggered' flag and any error that occurred during the check.
func (*AuthState) FeatureRelayDomains ¶ added in v1.3.9
FeatureRelayDomains triggers if a user sent an email address as a login name and the domain component does not match the list of known domains.
func (*AuthState) FeatureTLSEncryption ¶ added in v1.3.9
FeatureTLSEncryption checks, if the remote client connection was secured.
func (*AuthState) FilterLua ¶ added in v1.3.9
func (a *AuthState) FilterLua(passDBResult *PassDBResult, ctx *gin.Context) definitions.AuthResult
FilterLua calls Lua filters which can change the backend result.
func (*AuthState) GetAccount ¶ added in v1.3.9
GetAccount returns the account value from the AuthState object. If the account field is not set or the account value is not found in the attributes, an empty string is returned
func (*AuthState) GetAccountField ¶ added in v1.3.9
GetAccountField returns the value of the AccountField field in the AuthState struct. If the AccountField field is nil, it returns an empty string.
func (*AuthState) GetAccountOk ¶ added in v1.3.9
GetAccountOk returns the account name of a user. If there is no account, it returns the empty string "". A boolean is set to return a "found" flag.
func (*AuthState) GetAdditionalLogs ¶ added in v1.4.3
GetAdditionalLogs returns a slice of additional logs associated with the AuthState instance.
func (*AuthState) GetAttributes ¶ added in v1.4.3
func (a *AuthState) GetAttributes() bktype.AttributeMapping
GetAttributes retrieves the stored database attributes from the AuthState and returns them as a AttributeMapping.
func (*AuthState) GetCacheNameFor ¶ added in v1.11.0
func (a *AuthState) GetCacheNameFor(usedBackend definitions.CacheNameBackend) (cacheName string, err error)
GetCacheNameFor retrieves the cache name associated with the given backend, based on the protocol configured for the AuthState.
func (*AuthState) GetClientIP ¶ added in v1.5.1
GetClientIP returns the client's IP address stored in the AuthState instance.
func (*AuthState) GetDisplayName ¶ added in v1.3.9
GetDisplayName returns the display name for a user. If there is no account, it returns the empty string "".
func (*AuthState) GetDisplayNameField ¶ added in v1.4.3
GetDisplayNameField retrieves the display name field from the AuthState. Returns an empty string if it's nil.
func (*AuthState) GetDisplayNameOk ¶ added in v1.1.2
GetDisplayNameOk returns the display name of a user. If there is no account, it returns the empty string "". A boolean is set to return a "found" flag.
func (*AuthState) GetFromLocalCache ¶ added in v1.3.9
GetFromLocalCache retrieves the AuthState object from the local cache using the generateLocalCacheKey() as the key. If the object is found in the cache, it updates the fields of the current AuthState object with the cached values. It also sets the a.GUID field with the original value to avoid losing the GUID from the previous object. If the a.HTTPClientContext field is not nil, it sets it to nil and restores it after updating the AuthState object. It sets the a.UsedPassDBBackend field to BackendLocalCache to indicate that the cache was used. Finally, it sets the "local_cache_auth" key to true in the gin.Context using ctx.Set() and returns true if the object is found in the cache; otherwise, it returns false.
func (*AuthState) GetGUID ¶ added in v1.4.3
GetGUID retrieves the GUID from the AuthState. Returns an empty string if the GUID is nil.
func (*AuthState) GetPassword ¶ added in v1.4.3
GetPassword retrieves the password stored in the AuthState instance. It returns the password as a string.
func (*AuthState) GetProtocol ¶ added in v1.4.3
GetProtocol retrieves the configured Protocol for the AuthState. If no Protocol is set, it returns a default Protocol instance.
func (*AuthState) GetTOTPRecoveryField ¶ added in v1.4.3
GetTOTPRecoveryField retrieves the TOTP recovery field value from AuthState. Returns an empty string if not set.
func (*AuthState) GetTOTPSecret ¶ added in v1.3.9
GetTOTPSecret returns the TOTP secret for a user. If there is no secret, it returns the empty string "".
func (*AuthState) GetTOTPSecretField ¶ added in v1.4.3
GetTOTPSecretField retrieves the TOTP secret field from the AuthState. Returns an empty string if the field is nil.
func (*AuthState) GetTOTPSecretOk ¶ added in v1.3.9
GetTOTPSecretOk returns the TOTP secret for a user. If there is no secret, it returns the empty string "". A boolean is set to return a "found" flag.
func (*AuthState) GetUniqueUserID ¶ added in v1.3.9
GetUniqueUserID returns the unique WebAuthn user identifier for a user. If there is no id, it returns the empty string "".
func (*AuthState) GetUniqueUserIDField ¶ added in v1.4.3
GetUniqueUserIDField retrieves the value of the UniqueUserIDField if set; returns an empty string otherwise.
func (*AuthState) GetUniqueUserIDOk ¶ added in v1.1.2
GetUniqueUserIDOk returns the unique identifier for a user. If there is no id, it returns the empty string "". A boolean is set to return a "found" flag.
func (*AuthState) GetUsedCacheBackend ¶ added in v1.11.0
func (a *AuthState) GetUsedCacheBackend() (definitions.CacheNameBackend, error)
GetUsedCacheBackend returns the cache name backend based on the used password database backend.
func (*AuthState) GetUsedPassDBBackend ¶ added in v1.4.3
func (a *AuthState) GetUsedPassDBBackend() definitions.Backend
GetUsedPassDBBackend returns the currently used backend for password database operations.
func (*AuthState) GetUsername ¶ added in v1.4.3
GetUsername retrieves the username from the AuthState structure.
func (*AuthState) HandleAuthentication ¶ added in v1.3.9
HandleAuthentication handles the authentication logic based on the selected service type.
func (*AuthState) HandleFeatures ¶ added in v1.3.9
func (a *AuthState) HandleFeatures(ctx *gin.Context) definitions.AuthResult
HandleFeatures processes multiple security features associated with authentication requests and returns the result. It checks for various features like TLS encryption, relay domains, RBL, and Lua scripting. The method returns an appropriate authentication result based on the features that are triggered or aborted.
func (*AuthState) HandlePassword ¶ added in v1.3.9
func (a *AuthState) HandlePassword(ctx *gin.Context) (authResult definitions.AuthResult)
HandlePassword handles the authentication process for the password flow. Delegate orchestration to the Authenticator to keep responsibilities separated.
func (*AuthState) HasJWTRole ¶ added in v1.7.0
HasJWTRole checks if the user has the specified role in their JWT token. It retrieves the JWT claims from the context and checks if the user has the required role. If JWT authentication is not enabled or no claims are found, it returns false.
func (*AuthState) HaveMonitoringFlag ¶ added in v1.3.9
func (a *AuthState) HaveMonitoringFlag(flag definitions.Monitoring) bool
HaveMonitoringFlag checks if the provided flag exists in the MonitoringFlags slice of the AuthState object. It iterates over the MonitoringFlags slice and returns true if the flag is found, otherwise it returns false.
func (*AuthState) InitMethodAndUserAgent ¶ added in v1.4.3
InitMethodAndUserAgent initializes the authentication method and user agent fields if they are not already set.
func (*AuthState) IsInNetwork ¶ added in v1.3.9
IsInNetwork checks an IP address against a network and returns true if it matches.
func (*AuthState) IsMasterUser ¶ added in v1.3.9
IsMasterUser checks whether the current user is a master user based on the MasterUser configuration in the GetFile(). It returns true if MasterUser is enabled and the number of occurrences of the delimiter in the Username is equal to 1, otherwise it returns false.
func (*AuthState) ListUserAccounts ¶ added in v1.3.9
func (a *AuthState) ListUserAccounts() (accountList AccountList)
ListUserAccounts returns the list of all known users from the account databases.
func (*AuthState) LogLineProcessingTemplate ¶ added in v1.10.0
LogLineProcessingTemplate generates and returns a list of key-value pairs for logging session-related details.
func (*AuthState) LogLineTemplate ¶ added in v1.3.9
LogLineTemplate constructs a key-value slice for logging authentication state and related metadata.
func (*AuthState) PostLuaAction ¶ added in v1.3.9
func (a *AuthState) PostLuaAction(passDBResult *PassDBResult)
PostLuaAction sends a Lua action to be executed asynchronously.
func (*AuthState) PreproccessAuthRequest ¶ added in v1.3.9
PreproccessAuthRequest preprocesses the authentication request by checking if the request is already in the local cache. If not found in the cache, it checks if the request is a brute force attack and updates the brute force counter. It then performs a post Lua action and triggers a failed authentication response. If a brute force attack is detected, it returns true, otherwise false.
func (*AuthState) ProcessAuthentication ¶ added in v1.9.10
ProcessAuthentication handles the authentication logic for all services.
func (*AuthState) ProcessFeatures ¶ added in v1.9.10
ProcessFeatures handles the processing of authentication-related features for a given context. It determines the action to take based on various authentication results and applies the necessary response.
func (*AuthState) SFKeyHash ¶ added in v1.11.0
SFKeyHash returns a short hash for the strict singleflight key to use in Redis keys.
func (*AuthState) SetClientHost ¶ added in v1.4.3
SetClientHost sets the client host value in the AuthState instance.
func (*AuthState) SetClientID ¶ added in v1.4.3
SetClientID sets the client ID for the authentication state using the provided clientID string.
func (*AuthState) SetClientIP ¶ added in v1.4.3
SetClientIP sets the client's IP address in the AuthState structure.
func (*AuthState) SetClientPort ¶ added in v1.4.3
SetClientPort sets the client's port information to the provided clientPort value.
func (*AuthState) SetLocalIP ¶ added in v1.4.3
SetLocalIP sets the local IP address for the AuthState instance.
func (*AuthState) SetLocalPort ¶ added in v1.4.3
SetLocalPort sets the local port for the AuthState instance to the given port string.
func (*AuthState) SetLoginAttempts ¶ added in v1.4.3
SetLoginAttempts sets the number of login attempts for the AuthState instance.
func (*AuthState) SetMethod ¶ added in v1.4.3
SetMethod sets the authentication method for the AuthState instance by assigning it to the Method field.
func (*AuthState) SetNoAuth ¶ added in v1.4.3
SetNoAuth configures the authentication state to enable or disable "NoAuth" mode based on the provided boolean value.
func (*AuthState) SetOIDCCID ¶ added in v1.7.5
SetOIDCCID sets the OIDC Client ID for the AuthState instance. It updates the OIDCCID field with the provided value.
func (*AuthState) SetOperationMode ¶ added in v1.4.3
SetOperationMode sets the operation mode of the AuthState object based on the "mode" query parameter from the provided gin context. It retrieves the GUID from the gin context and uses it for logging purposes. The operation mode can be "no-auth" or "list-accounts". If the mode is "no-auth", it sets the NoAuth field of the AuthState object to true. If the mode is "list-accounts", it sets the ListAccounts field of the AuthState object to true. The function "util.DebugModule" is used for logging debug messages with the appropriate module name and function name. Example usage of SetOperationMode:
a.setOperationMode(ctx)
func setupAuth(ctx *gin.Context, auth *AuthState) {
//...
auth.setOperationMode(ctx)
}
func (*AuthState) SetPassword ¶ added in v1.4.3
SetPassword sets the password for the AuthState instance.
func (*AuthState) SetProtocol ¶ added in v1.4.3
SetProtocol sets the protocol for the AuthState using the given Protocol configuration.
func (*AuthState) SetSSL ¶ added in v1.4.3
SetSSL sets the XSSL property of the AuthState to the provided SSL value.
func (*AuthState) SetSSLCipher ¶ added in v1.4.3
SetSSLCipher sets the SSL cipher suite for the current authentication state.
func (*AuthState) SetSSLClientCN ¶ added in v1.4.3
SetSSLClientCN sets the value of the SSL client common name (CN) for the AuthState instance.
func (*AuthState) SetSSLClientDN ¶ added in v1.4.3
SetSSLClientDN sets the distinguished name (DN) of the SSL client in the AuthState struct.
func (*AuthState) SetSSLClientIssuerDN ¶ added in v1.4.3
SetSSLClientIssuerDN sets the SSL client issuer distinguished name for the authentication state.
func (*AuthState) SetSSLClientNotAfter ¶ added in v1.4.3
SetSSLClientNotAfter sets the XSSLClientNotAfter field with the provided SSL client expiration date.
func (*AuthState) SetSSLClientNotBefore ¶ added in v1.4.3
SetSSLClientNotBefore sets the SSL client certificate's "Not Before" value in the AuthState.
func (*AuthState) SetSSLClientSubjectDN ¶ added in v1.4.3
SetSSLClientSubjectDN sets the subject distinguished name (DN) for the SSL client in the AuthState object.
func (*AuthState) SetSSLClientVerify ¶ added in v1.4.3
SetSSLClientVerify sets the SSL client verification value for the AuthState.
func (*AuthState) SetSSLFingerprint ¶ added in v1.4.3
SetSSLFingerprint sets the SSL fingerprint for the AuthState instance. It updates the SSLFingerprint field with the provided value.
func (*AuthState) SetSSLIssuer ¶ added in v1.4.3
SetSSLIssuer sets the issuer for the XSSL certificate in the AuthState.
func (*AuthState) SetSSLIssuerDN ¶ added in v1.4.3
SetSSLIssuerDN sets the X.509 SSL issuer distinguished name for the AuthState.
func (*AuthState) SetSSLProtocol ¶ added in v1.4.3
SetSSLProtocol sets the SSL protocol version to be used for the connection by updating the XSSLProtocol field.
func (*AuthState) SetSSLSerial ¶ added in v1.4.3
SetSSLSerial sets the SSL serial number for the AuthState instance.
func (*AuthState) SetSSLSessionID ¶ added in v1.4.3
SetSSLSessionID sets the SSL session ID for the AuthState instance.
func (*AuthState) SetSSLSubjectDN ¶ added in v1.4.3
SetSSLSubjectDN sets the SSL subject distinguished name to the provided string value.
func (*AuthState) SetStatusCodes ¶ added in v1.4.3
SetStatusCodes sets different status codes for various services.
func (*AuthState) SetUserAgent ¶ added in v1.4.3
SetUserAgent sets the UserAgent field for the AuthState with the provided userAgent value.
func (*AuthState) SetUsername ¶ added in v1.4.3
SetUsername sets the username for the AuthState instance to the given value.
func (*AuthState) String ¶ added in v1.1.2
String returns an AuthState object as string excluding the user password.
func (*AuthState) UpdateBruteForceBucketsCounter ¶ added in v1.3.9
UpdateBruteForceBucketsCounter updates brute force protection rules based on client and protocol details.
func (*AuthState) WithClientInfo ¶ added in v1.3.9
WithClientInfo adds the client IP, -port and -ID headers to the AuthState structure.
func (*AuthState) WithDefaults ¶ added in v1.3.9
WithDefaults sets default values for the AuthState structure including the GUID session value.
func (*AuthState) WithLocalInfo ¶ added in v1.3.9
WithLocalInfo adds the local IP and -port headers to the AuthState structure.
func (*AuthState) WithUserAgent ¶ added in v1.3.9
WithUserAgent adds the User-Agent header to the AuthState structure.
type Authenticator ¶ added in v1.11.0
type Authenticator struct {
Decoder any // placeholder for future RequestDecoder
Verifier PasswordVerifier
Cache CacheService
BF BruteForceService
Lua LuaFilter
Post PostAction
Resp ResponseWriter
}
Authenticator orchestrates the authentication flow. It wires the previously extracted services and keeps behavior identical to the legacy inline implementation in AuthState.HandlePassword.
In this initial step, Authenticate delegates to existing helper methods on AuthState to avoid any behavior changes.
Future iterations can migrate more logic from AuthState into this type.
func (Authenticator) Authenticate ¶ added in v1.11.0
func (aor Authenticator) Authenticate(ctx *gin.Context, auth *AuthState) (authResult definitions.AuthResult)
Authenticate runs the full password authentication flow. Behavior mirrors the legacy HandlePassword implementation exactly.
type BackendManager ¶ added in v1.5.0
type BackendManager interface {
// PassDB authenticates a user through a password database using the provided AuthState and returns the authentication result.
PassDB(auth *AuthState) (passDBResult *PassDBResult, err error)
// AccountDB retrieves a list of user accounts from the backend using the provided authentication state.
AccountDB(auth *AuthState) (accounts AccountList, err error)
// AddTOTPSecret adds the specified TOTP secret to the user's authentication state in the backend.
AddTOTPSecret(auth *AuthState, totp *mfa.TOTPSecret) (err error)
}
BackendManager defines an interface for managing authentication backends with methods for user authentication and account handling.
func NewLDAPManager ¶ added in v1.5.0
func NewLDAPManager(poolName string) BackendManager
NewLDAPManager creates and returns a BackendManager for managing LDAP authentication backends using the specified pool name.
func NewLuaManager ¶ added in v1.5.0
func NewLuaManager(backendName string) BackendManager
NewLuaManager initializes and returns a new LuaManager instance with the specified backend name.
type BackendServer ¶
type BackendServer struct {
// contains filtered or unexported fields
}
BackendServer represents a type for managing a slive of config.BackendServer
func NewBackendServer ¶
func NewBackendServer() *BackendServer
NewBackendServer creates a new instance of the BackendServer struct. It returns a pointer to the newly created BackendServer.
func (*BackendServer) GetTotalServers ¶
func (n *BackendServer) GetTotalServers() int
func (*BackendServer) Update ¶
func (n *BackendServer) Update(servers []*config.BackendServer)
Update updates the backendServer field of the BackendServer object with the provided servers slice.
type Bootstrap ¶ added in v1.9.10
type Bootstrap interface {
// InitWebAuthn initializes the global WebAuthn configuration from environment/config.
// Returns an error if the configuration is invalid.
InitWebAuthn() error
// InitSessionStore constructs and returns the Gin session store with secure defaults.
InitSessionStore() sessions.Store
// InitGinLogging wires Gin log writers and sets Gin mode based on configuration.
InitGinLogging()
}
Bootstrap initializes cross-cutting HTTP dependencies such as WebAuthn, the session store, and Gin logging, before the router is built.
type BruteForceService ¶ added in v1.11.0
type BruteForceService interface {
// WaitDelay returns the wait time in seconds based on configured max and login attempts.
WaitDelay(maxWaitDelay, loginAttempt uint) int
// LoadHistories loads brute-force related histories and updates counters on the AuthState.
LoadHistories(ctx *gin.Context, auth *AuthState, accountName string)
}
BruteForceService encapsulates backoff calculations and history/counter loading. Implementations live in a subpackage and register themselves via services_registry.
func GetBruteForceService ¶ added in v1.11.0
func GetBruteForceService() BruteForceService
type CacheService ¶ added in v1.11.0
type CacheService interface {
// OnSuccess updates the positive cache after a successful authentication attempt for the specified account name.
OnSuccess(auth *AuthState, accountName string) error
// OnFailure handles the actions required in case of an unsuccessful authentication attempt for the given account name.
OnFailure(auth *AuthState, accountName string)
}
CacheService abstracts positive/negative cache behavior.
func GetCacheService ¶ added in v1.11.0
func GetCacheService() CacheService
type ClaimHandler ¶
type ClaimHandler struct {
// Type is the reflected Kind of the claim value.
Type reflect.Kind
// ApplyFunc is a function that takes in three parameters: the claim value, the map of claims and the claim key.
// The function is intended to apply some process on the claim using the provided parameters,
// and return a boolean result.
ApplyFunc func(value any, claims map[string]any, claimKey string) bool
}
ClaimHandler represents a claim handler struct. A claim handler in this context is something to work with JSON Web Tokens (JWT), often used for APIs.
type CredentialOption ¶ added in v1.11.0
type CredentialOption func(*Credentials)
CredentialOption mutates a Credentials value during construction.
func WithPassword ¶ added in v1.11.0
func WithPassword(p string) CredentialOption
WithPassword sets the password field.
func WithTOTP ¶ added in v1.11.0
func WithTOTP(t string) CredentialOption
WithTOTP sets a TOTP one-time code (unused in current flows).
func WithTOTPRecovery ¶ added in v1.11.0
func WithTOTPRecovery(t string) CredentialOption
WithTOTPRecovery sets a TOTP recovery code (unused in current flows).
func WithUsername ¶ added in v1.11.0
func WithUsername(u string) CredentialOption
WithUsername sets the username field.
type Credentials ¶ added in v1.11.0
Credentials captures user-supplied credentials (username/password, optional MFA). It is intended to be immutable via options; apply them to AuthState via ApplyCredentials.
Note: We intentionally keep MFA fields optional and currently unused to avoid behavior changes in existing flows. They are placeholders for future phases.
func NewCredentials ¶ added in v1.11.0
func NewCredentials(opts ...CredentialOption) Credentials
NewCredentials constructs a Credentials value using the provided options.
type DefaultBootstrap ¶ added in v1.9.10
type DefaultBootstrap struct{}
DefaultBootstrap wires the existing bootstrapping functions.
func (DefaultBootstrap) InitGinLogging ¶ added in v1.9.10
func (DefaultBootstrap) InitGinLogging()
InitGinLogging configures Gin's writers to use the project's logger and sets Gin mode (release/debug) and color output based on configuration.
func (DefaultBootstrap) InitSessionStore ¶ added in v1.9.10
func (DefaultBootstrap) InitSessionStore() sessions.Store
InitSessionStore creates and returns the secure cookie-backed Gin session store with secure defaults (Secure, SameSite=Strict). The caller is responsible for registering the sessions middleware with Gin.
func (DefaultBootstrap) InitWebAuthn ¶ added in v1.9.10
func (DefaultBootstrap) InitWebAuthn() error
InitWebAuthn is a no-op in non-hydra builds.
type DefaultHTTPApp ¶ added in v1.9.10
type DefaultHTTPApp struct {
Bootstrap Bootstrap
RouterComposer RouterComposer
HTTPServerFactory HTTPServerFactory
ProxyProvider ProxyListenerProvider
TLSConfigurator TLSConfigurator
TransportRunner TransportRunner
}
DefaultHTTPApp orchestrates all components and preserves exact behavior.
func NewDefaultHTTPApp ¶ added in v1.9.10
func NewDefaultHTTPApp() *DefaultHTTPApp
NewDefaultHTTPApp constructs the default HTTP application facade that wires together the default implementations for bootstrapping, router composition, server factory, proxy listener provider, TLS configuration, and transport runner.
func (*DefaultHTTPApp) Start ¶ added in v1.9.10
func (a *DefaultHTTPApp) Start(ctx context.Context, setupHealth func(*gin.Engine), setupMetrics func(*gin.Engine), setupHydra func(*gin.Engine), setup2FA func(*gin.Engine), setupWebAuthn func(*gin.Engine), setupNotify func(*gin.Engine), setupBackchannel func(*gin.Engine), signals ServerSignals, )
Start bootstraps dependencies (WebAuthn, Gin logging, sessions), composes the Gin engine, registers routes via the provided callbacks, builds the HTTP server (incl. HTTP/2), configures TLS if enabled, prepares optional PROXY v2, and finally hands off to the TransportRunner to serve traffic.
The setup* callbacks are optional; if non-nil, they are invoked to register respective routes on the engine. Signals are used to decouple shutdown coordination from global channels.
type DefaultHTTPServerFactory ¶ added in v1.9.10
type DefaultHTTPServerFactory struct{}
DefaultHTTPServerFactory builds http.Server and configures HTTP/2 settings.
type DefaultResponseWriter ¶ added in v1.11.0
type DefaultResponseWriter struct{}
DefaultResponseWriter implements ResponseWriter with current behavior.
func (DefaultResponseWriter) Fail ¶ added in v1.11.0
func (DefaultResponseWriter) Fail(ctx *gin.Context, view *StateView)
Fail implements the failure response logic (unchanged behavior).
type DefaultRouterComposer ¶ added in v1.9.10
type DefaultRouterComposer struct{}
DefaultRouterComposer builds the gin.Engine and registers routes/middlewares in the exact order.
func (DefaultRouterComposer) ApplyCoreMiddlewares ¶ added in v1.9.10
func (DefaultRouterComposer) ApplyCoreMiddlewares(r *gin.Engine)
ApplyCoreMiddlewares configures the router builder to add recovery, trusted proxies, request decompression, response compression, and metrics middleware in the same order as before.
func (DefaultRouterComposer) ApplyEarlyMiddlewares ¶ added in v1.9.10
func (DefaultRouterComposer) ApplyEarlyMiddlewares(r *gin.Engine)
ApplyEarlyMiddlewares registers pprof (if enabled), the concurrency limiter, and the structured logging middleware. The order is preserved as in the legacy code.
func (DefaultRouterComposer) ComposeEngine ¶ added in v1.9.10
func (DefaultRouterComposer) ComposeEngine() *gin.Engine
ComposeEngine creates a fresh gin.Engine without any default middleware. This mirrors the legacy code which constructed the engine explicitly.
func (DefaultRouterComposer) RegisterRoutes ¶ added in v1.9.10
func (DefaultRouterComposer) RegisterRoutes(r *gin.Engine, setupHealth func(*gin.Engine), setupMetrics func(*gin.Engine), setupHydra func(*gin.Engine), setup2FA func(*gin.Engine), setupWebAuthn func(*gin.Engine), setupNotify func(*gin.Engine), setupBackchannel func(*gin.Engine), )
RegisterRoutes wires health and metrics routes, then (if enabled) the frontend routes (Hydra, 2FA, WebAuthn, Notify) and finally the backchannel routes. The order is kept to preserve exact behavior of the legacy implementation.
type DefaultServerSignals ¶ added in v1.9.10
type DefaultServerSignals struct {
// contains filtered or unexported fields
}
DefaultServerSignals provides default channels for HTTP and HTTP/3 lifecycle notifications.
func NewDefaultServerSignals ¶ added in v1.9.10
func NewDefaultServerSignals(enableHTTP3 bool) *DefaultServerSignals
NewDefaultServerSignals creates a ServerSignals implementation. If enableHTTP3 is true, the HTTP/3 done channel will be created as well.
func (*DefaultServerSignals) HTTP3Done ¶ added in v1.9.10
func (s *DefaultServerSignals) HTTP3Done() chan Done
HTTP3Done returns the channel that signals completion of the HTTP/3 server lifecycle (graceful shutdown finished). It may be nil if HTTP/3 is disabled.
func (*DefaultServerSignals) HTTPDone ¶ added in v1.9.10
func (s *DefaultServerSignals) HTTPDone() chan Done
HTTPDone returns the channel that signals completion of the HTTP/1.1+2 server lifecycle (graceful shutdown finished).
type DefaultTLSConfigurator ¶ added in v1.9.10
type DefaultTLSConfigurator struct{}
DefaultTLSConfigurator constructs tls.Config according to settings.
func (DefaultTLSConfigurator) Build ¶ added in v1.9.10
func (DefaultTLSConfigurator) Build() *tls.Config
Build assembles a *tls.Config* honoring configured CA, cipher suites, minimum TLS version, NextProtos, and InsecureSkipVerify. If a CA is set, it is used for both RootCAs and optional client verification (VerifyClientCertIfGiven).
type DefaultTransportRunner ¶ added in v1.9.10
type DefaultTransportRunner struct{}
DefaultTransportRunner starts HTTP/1.1+2 and optional HTTP/3, with graceful shutdown.
func (DefaultTransportRunner) Serve ¶ added in v1.9.10
func (DefaultTransportRunner) Serve(ctx context.Context, srv *http.Server, certFile, keyFile string, proxy *proxyproto.Listener, signals ServerSignals)
Serve launches the HTTP/1.1+2 server (and optionally HTTP/3) and manages graceful shutdown on context cancellation. Termination signals are forwarded via the provided ServerSignals implementation to decouple consumers from globals.
type FeatureEngine ¶ added in v1.11.0
type FeatureEngine interface {
Evaluate(ctx *gin.Context, view *StateView) (triggered bool, abort bool, logs []any, newStatus *string, err error)
}
FeatureEngine encapsulates the evaluation of Lua-based features. It returns whether a feature was triggered, whether further features should be aborted, and optional logs plus a new StatusMessage.
func GetFeatureEngine ¶ added in v1.11.0
func GetFeatureEngine() FeatureEngine
type FieldMapping ¶ added in v1.11.0
FieldMapping groups configurable field names to reduce scattered getters. Currently unused to avoid behavior changes; reserved for next steps.
type HAProxyListenerProvider ¶ added in v1.9.10
type HAProxyListenerProvider struct{}
HAProxyListenerProvider provides PROXY v2 listener when enabled.
func (HAProxyListenerProvider) Get ¶ added in v1.9.10
func (HAProxyListenerProvider) Get() *proxyproto.Listener
Get returns a PROXY v2 aware listener if the feature is enabled in the configuration, otherwise it returns nil.
type HTTPApplication ¶ added in v1.9.10
type HTTPApplication interface {
Start(ctx context.Context,
setupHealth func(*gin.Engine),
setupMetrics func(*gin.Engine),
setupHydra func(*gin.Engine),
setup2FA func(*gin.Engine),
setupWebAuthn func(*gin.Engine),
setupNotify func(*gin.Engine),
setupBackchannel func(*gin.Engine),
signals ServerSignals,
)
}
HTTPApplication is a high-level façade to start the HTTP stack with injected route setup callbacks. It encapsulates bootstrapping, engine composition, server creation and transport serving.
type HTTPServerFactory ¶ added in v1.9.10
HTTPServerFactory creates a configured http.Server (incl. HTTP/2 settings).
type JSONErrorMsg ¶ added in v1.3.8
type JSONErrorMsg struct {
// Field represents the name of the field that caused the validation error.
Field string `json:"field"`
// Message represents the error message associated with the validation error.
Message string `json:"message"`
}
JSONErrorMsg represents an error message in JSON format with the field name and error message string.
type LuaFilter ¶ added in v1.11.0
type LuaFilter interface {
Filter(ctx *gin.Context, view *StateView, result *PassDBResult) definitions.AuthResult
}
LuaFilter encapsulates the Lua filter pipeline and returns an AuthResult.
type PassDBMap ¶
type PassDBMap struct {
// contains filtered or unexported fields
}
PassDBMap is a struct type that represents a mapping between a backend type and a PassDBOption function. It is used in the verifyPassword method of the AuthState struct to perform password verification against multiple databases. The backend field represents the type of database backend (definitions.Backend), and the fn field represents the PassDBOption function. The PassDBOption function takes an AuthState pointer as input and returns a PassDBResult pointer and an error. The PassDBResult pointer contains the result of the password verification process. This struct is used to store the database mappings in an array and loop through them in the verifyPassword method.
type PassDBOption ¶
type PassDBOption func(auth *AuthState) (*PassDBResult, error)
PassDBOption This type specifies the signature of a password database.
type PassDBResult ¶
type PassDBResult struct {
// Authenticated is a flag that is set if a user was not only found, but also succeeded authentication.
Authenticated bool
// UserFound is a flag that is set if the user was found in a password Database.
UserFound bool
// BackendName specifies the name of the backend that authenticated or found the user in the password database.
BackendName string
// AccountField is the SQL field or LDAP attribute that was used for the user account.
AccountField string
// TOTPSecretField is set by the Database which has found the user.
TOTPSecretField string
// TOTPRecoveryField NYI
TOTPRecoveryField string
// UniqueUserIDField is a string representing a unique user identifier.
UniqueUserIDField string
// DisplayNameField is the display name of a user
DisplayNameField string
// Backend is set by the Database backend, which has found the user.
Backend definitions.Backend
// Attributes is the result catalog returned by the underlying password Database.
Attributes bktype.AttributeMapping
// AdditionalFeatures contains additional features for machine learning
AdditionalFeatures map[string]any
}
PassDBResult is used in all password databases to store final results of an authentication process.
func CachePassDB ¶ added in v1.3.9
func CachePassDB(auth *AuthState) (passDBResult *PassDBResult, err error)
CachePassDB implements the redis password database backend.
func GetPassDBResultFromPool ¶ added in v1.7.3
func GetPassDBResultFromPool() *PassDBResult
GetPassDBResultFromPool retrieves a PassDBResult object from the pool If the pool is empty, a new PassDBResult object is created
func VerifyPasswordPipeline ¶ added in v1.11.0
func VerifyPasswordPipeline(ctx *gin.Context, auth *AuthState, passDBs []*PassDBMap) (*PassDBResult, error)
VerifyPasswordPipeline is the exported, package-internal implementation of the legacy password verification loop. It is used by the default implementation provided from subpackage core/auth to avoid accessing unexported fields.
func (*PassDBResult) IsPassDBResult ¶ added in v1.7.3
func (p *PassDBResult) IsPassDBResult() bool
IsPassDBResult returns true to identify this as a PassDBResult This implements the PoolablePassDBResult interface from the localcache package
func (*PassDBResult) Reset ¶ added in v1.7.3
func (p *PassDBResult) Reset()
Reset resets all fields of the PassDBResult to their zero values This is used when returning a PassDBResult to the pool It implements the Resettable interface
func (*PassDBResult) String ¶
func (p *PassDBResult) String() string
String returns the string for a PassDBResult object.
type PasswordVerifier ¶ added in v1.11.0
type PasswordVerifier interface {
Verify(ctx *gin.Context, a *AuthState, passDBs []*PassDBMap) (*PassDBResult, error)
}
PasswordVerifier abstracts the PassDB verification pipeline.
func GetPasswordVerifier ¶ added in v1.11.0
func GetPasswordVerifier() PasswordVerifier
type PostAction ¶ added in v1.11.0
type PostAction interface {
Run(input PostActionInput)
}
PostAction encapsulates the asynchronous post-action dispatch to the Lua worker.
type PostActionArgs ¶ added in v1.11.0
type PostActionArgs struct {
Context *lualib.Context
HTTPRequest *http.Request
StatusMessage string
Request lualib.CommonRequest
}
PostActionArgs bundles all necessary inputs for the Lua post-action dispatch. Request is passed by value and copied into a pooled lualib.CommonRequest. StatusMessage is copied and its address is set on the pooled request.
Callers should prefer providing BF hints (ClientNet/Repeating) when available; if absent, RunLuaPostAction will derive them via ComputeBruteForceHints.
This API replaces the legacy ExecuteLuaPostAction monster signature. The legacy function is kept as a thin wrapper for backward compatibility.
type PostActionInput ¶ added in v1.11.0
type PostActionInput struct {
View *StateView
Result *PassDBResult
}
PostActionInput aggregates the minimal inputs required for the Lua post action. It deliberately reduces dozens of parameters to a compact value object.
type ProxyListenerProvider ¶ added in v1.9.10
type ProxyListenerProvider interface {
Get() *proxyproto.Listener // nil if disabled
}
ProxyListenerProvider optionally supplies an HAProxy PROXY v2 listener.
type RBLService ¶ added in v1.11.0
type RBLService interface {
// Score computes the aggregated RBL score for the request.
Score(ctx *gin.Context, view *StateView) (int, error)
// Threshold returns the configured threshold at which a feature is triggered.
Threshold() int
}
RBLService encapsulates RBL checking and aggregation.
func GetRBLService ¶ added in v1.11.0
func GetRBLService() RBLService
type ResponseWriter ¶ added in v1.11.0
type ResponseWriter interface {
// OK sends a success response to the client by setting appropriate headers and processing authentication logic.
OK(ctx *gin.Context, view *StateView)
// Fail sends a failure response to the client by setting appropriate headers and processing login attempt logic.
Fail(ctx *gin.Context, view *StateView)
// TempFail sends a temporary failure response with the specified reason and logs the error for debugging purposes.
TempFail(ctx *gin.Context, view *StateView, reason string)
}
ResponseWriter defines how to write authentication responses. It abstracts OK/Fail/TempFail without changing external API.
type RouterComposer ¶ added in v1.9.10
type RouterComposer interface {
ComposeEngine() *gin.Engine
ApplyEarlyMiddlewares(*gin.Engine) // pprof, limit, logger
ApplyCoreMiddlewares(*gin.Engine) // recovery, proxies, compression, metrics
RegisterRoutes(r *gin.Engine,
setupHealth func(*gin.Engine),
setupMetrics func(*gin.Engine),
setupHydra func(*gin.Engine),
setup2FA func(*gin.Engine),
setupWebAuthn func(*gin.Engine),
setupNotify func(*gin.Engine),
setupBackchannel func(*gin.Engine),
)
}
RouterComposer builds/configures the Gin engine and registers routes in the exact order as before.
type SFOutcome ¶ added in v1.10.5
type SFOutcome struct {
Result definitions.AuthResult
AccountField string
Attributes bktype.AttributeMapping
TOTPSecretField string
UniqueUserIDField string
DisplayNameField string
SourcePassDBBackend definitions.Backend
UsedPassDBBackend definitions.Backend
BackendName string
UsedBackendIP string
UsedBackendPort int
Authenticated bool
Authorized bool
StatusMessage string
}
SFOutcome is the snapshot a singleflight leader publishes to waiting followers. It contains the final auth view AFTER filters have run and PostActions have been dispatched. Followers must not execute filters/post-actions again; they only apply this snapshot to their own AuthState and return the final result.
type ServerSignals ¶ added in v1.9.10
type ServerSignals interface {
// HTTPDone returns a channel that is signaled when the HTTP/1.1+2 server
// has terminated gracefully.
HTTPDone() chan Done
// HTTP3Done returns a channel that is signaled when the HTTP/3 server
// has terminated gracefully. It may be nil if HTTP/3 is disabled.
HTTP3Done() chan Done
}
ServerSignals encapsulates server lifecycle signaling channels used to coordinate graceful shutdown. Implementations may return nil for HTTP/3 when HTTP/3 is disabled.
type State ¶ added in v1.4.3
type State interface {
// SetUsername sets the username for the current authentication state.
SetUsername(username string)
// SetPassword sets the password for the current authentication state.
SetPassword(password string)
// SetClientIP sets the client's IP address used during the authentication process.
SetClientIP(clientIP string)
// SetClientPort sets the client's port as a string.
SetClientPort(clientPort string)
// SetClientHost sets the client host information for the current state using the provided hostname string.
SetClientHost(clientHost string)
// SetClientID sets the client ID to the provided string value.
SetClientID(clientID string)
// SetStatusCodes sets the current status code associated with the authentication process.
SetStatusCodes(statusCode string)
// SetOperationMode sets the operation mode for the authentication process based on the provided gin context.
SetOperationMode(ctx *gin.Context)
// SetNoAuth sets the authentication state to no authentication required when true, or requires authentication when false.
SetNoAuth(bool)
// SetProtocol sets the authentication protocol to be used during the authentication process.
SetProtocol(protocol *config.Protocol)
// GetGUID retrieves the globally unique identifier (GUID) associated with the current authentication state.
GetGUID() string
// GetUsername retrieves the username currently stored in the state and returns it as a string.
GetUsername() string
// GetPassword retrieves the current password stored in the authentication state as a string.
GetPassword() string
// GetProtocol retrieves the protocol configuration associated with the current state.
GetProtocol() *config.Protocol
// SetLoginAttempts sets the number of login attempts for the current authentication process.
SetLoginAttempts(uint)
// SetMethod sets the authentication method used during the authentication process.
SetMethod(method string)
// SetUserAgent sets the user agent information for the current authentication state.
SetUserAgent(userAgent string)
// SetLocalIP sets the local IP address for the current state.
SetLocalIP(localIP string)
// SetLocalPort sets the local port for the authentication state.
SetLocalPort(localPort string)
// SetSSL sets the SSL parameter to the specified value for the authentication process.
SetSSL(ssl string)
// SetSSLSessionID sets the SSL session ID associated with the current state for tracking and verification purposes.
SetSSLSessionID(sslSessionID string)
// SetSSLClientVerify sets the verification result of the SSL client as a string. Typically used for SSL client validation.
SetSSLClientVerify(sslClientVerify string)
// SetSSLClientDN sets the SSL client distinguished name (DN) for the current authentication state.
SetSSLClientDN(sslClientDN string)
// SetSSLClientCN sets the Common Name (CN) from the SSL client certificate for the current authentication state.
SetSSLClientCN(sslClientCN string)
// SetSSLIssuer sets the SSL issuer string for the current authentication state.
SetSSLIssuer(sslIssuer string)
// SetSSLClientNotBefore sets the "not before" validity period for the SSL client certificate.
SetSSLClientNotBefore(sslClientNotBefore string)
// SetSSLClientNotAfter sets the expiration date and time of the SSL client certificate.
SetSSLClientNotAfter(sslClientNotAfter string)
// SetSSLSubjectDN sets the SSL subject distinguished name (DN) associated with the current authentication state.
SetSSLSubjectDN(sslSubjectDN string)
// SetSSLIssuerDN sets the distinguished name (DN) of the SSL issuer for the current state.
SetSSLIssuerDN(sslIssuerDN string)
// SetSSLClientSubjectDN sets the distinguished name (DN) of the SSL client certificate's subject.
SetSSLClientSubjectDN(sslClientSubjectDN string)
// SetSSLClientIssuerDN sets the distinguished name (DN) of the SSL client issuer to the provided string value.
SetSSLClientIssuerDN(sslClientIssuerDN string)
// SetSSLProtocol sets the SSL security protocol for the current authentication session.
SetSSLProtocol(sslProtocol string)
// SetSSLCipher sets the SSL cipher used for the client connection.
SetSSLCipher(sslCipher string)
// SetSSLSerial sets the SSL serial number for the authentication state.
SetSSLSerial(sslSerial string)
// SetSSLFingerprint sets the SSL fingerprint value for the current state.
SetSSLFingerprint(sslFingerprint string)
// SetOIDCCID sets the OIDC Client ID for the authentication state.
SetOIDCCID(oidcCID string)
// GetAccountOk returns the account field value and a boolean indicating if the account field is present and valid.
GetAccountOk() (string, bool)
// GetTOTPSecretOk retrieves the TOTP secret if available and returns it along with a bool indicating its presence.
GetTOTPSecretOk() (string, bool)
// GetAccountField retrieves the current account field associated with the authentication process.
GetAccountField() string
// GetTOTPSecretField retrieves the TOTP secret field associated with the current authentication state.
GetTOTPSecretField() string
// GetTOTPRecoveryField retrieves the TOTP recovery field used during the authentication process.
GetTOTPRecoveryField() string
// GetUniqueUserIDField returns the name of the field or attribute that represents a unique user identifier in the database.
GetUniqueUserIDField() string
// GetDisplayNameField retrieves the display name field of a user from the current state.
GetDisplayNameField() string
// GetUsedPassDBBackend returns the backend used for the password database during the authentication process.
GetUsedPassDBBackend() definitions.Backend
// GetAttributes retrieves a map of database attributes where keys are field names and values are the corresponding data.
GetAttributes() bktype.AttributeMapping
// GetAdditionalLogs retrieves a slice of additional log entries, useful for appending context-specific logging details.
GetAdditionalLogs() []any
// GetClientIP retrieves the client's IP address associated with the current authentication or request context.
GetClientIP() string
// PreproccessAuthRequest preprocesses the authentication request and determines if it should be rejected.
PreproccessAuthRequest(ctx *gin.Context) bool
// UpdateBruteForceBucketsCounter increments counters to track brute-force attack attempts for the associated client IP.
UpdateBruteForceBucketsCounter(ctx *gin.Context)
// HandleAuthentication processes the primary authentication logic based on the request context and service parameters.
HandleAuthentication(ctx *gin.Context)
// HandlePassword processes the password-based authentication for a user and returns the authentication result.
HandlePassword(ctx *gin.Context) definitions.AuthResult
// ProcessFeatures evaluates and processes feature-related data from the request context.
// It returns a boolean indicating whether the process should abort further execution.
ProcessFeatures(ctx *gin.Context) (abort bool)
// ProcessAuthentication processes authentication requests using.
ProcessAuthentication(ctx *gin.Context)
// FilterLua applies Lua-based filtering logic to the provided PassDBResult and execution context.
// It returns an AuthResult indicating the outcome of the filtering process.
FilterLua(passDBResult *PassDBResult, ctx *gin.Context) definitions.AuthResult
// PostLuaAction performs actions or post-processing after executing Lua scripts during authentication workflow.
PostLuaAction(passDBResult *PassDBResult)
// WithDefaults configures the State with default values derived from the provided gin.Context.
WithDefaults(ctx *gin.Context) State
// WithClientInfo adds client-related information from the provided context to the current authentication state and returns it.
WithClientInfo(ctx *gin.Context) State
// WithLocalInfo enriches the authentication state with the client's local information based on the provided context.
WithLocalInfo(ctx *gin.Context) State
// WithUserAgent updates the State object with information extracted from the request's User-Agent header.
WithUserAgent(ctx *gin.Context) State
// WithXSSL sets XSSL-related context for the authentication process and returns the updated State object.
WithXSSL(ctx *gin.Context) State
// InitMethodAndUserAgent initializes the authentication method and user agent fields if they are not already set.
InitMethodAndUserAgent() State
// IsMasterUser determines if the authenticated user has master-level privileges, returning true if they do.
IsMasterUser() bool
// contains filtered or unexported methods
}
State is implemented by AuthState and defines the methods to interact with the authentication process.
func NewAuthStateFromContext ¶ added in v1.4.3
NewAuthStateFromContext initializes and returns an AuthState using the provided gin.Context. It gets an AuthState from the pool, sets the context to a copied HTTPClientContext and assigns the current time to the StartTime field.
func NewAuthStateWithSetup ¶ added in v1.4.3
NewAuthStateWithSetup creates a new instance of the AuthState struct. It takes a gin.Context object as a parameter and sets it as the HTTPClientContext field of the AuthState struct. If an error occurs while setting the StatusCode field using the SetStatusCodes function, it logs the error and returns nil. Otherwise, it calls the setupAuth function to setup the AuthState struct based on the service parameter from the gin.Context object. Finally, it returns the created AuthState struct.
type StateView ¶ added in v1.11.0
type StateView struct {
// contains filtered or unexported fields
}
StateView is a read-only snapshot wrapper around AuthState used by response and header layers. It keeps a private pointer to AuthState to avoid behavior changes. Future phases may replace direct AuthState access with copied fields.
type TLSConfigurator ¶ added in v1.9.10
TLSConfigurator encapsulates TLS parameters (CA, suites, min version, NextProtos...).
type TransportRunner ¶ added in v1.9.10
type TransportRunner interface {
Serve(ctx context.Context, srv *http.Server, certFile, keyFile string, proxy *proxyproto.Listener, signals ServerSignals)
}
TransportRunner starts the network listeners for HTTP/1.1+2 and optionally HTTP/3, and manages graceful shutdown and error handling. Parameters:
- ctx: lifecycle context; cancellation triggers graceful shutdown
- srv: configured net/http server (HTTP/1.1+2)
- certFile, keyFile: TLS certificate and key file paths (only used if TLS enabled)
- proxy: optional HAProxy PROXY v2 listener (nil if disabled)
- signals: channels to signal server termination events
type WebAuthnCredentialDBFunc ¶
type WebAuthnCredentialDBFunc func(uniqueUserID string) ([]webauthn.Credential, error)
WebAuthnCredentialDBFunc defines a signature for WebAuthn credential object lookups
Source Files
¶
- auth.go
- auth_nohydra.go
- backend_servers.go
- bindjson.go
- brute_force_service.go
- bruteforce.go
- cache.go
- cache_service.go
- context.go
- features.go
- headers.go
- http.go
- http_interfaces.go
- http_webauthn_nohydra.go
- hydra_nohydra.go
- i18n.go
- jwt.go
- ldap.go
- logging.go
- lua.go
- lua_post_action.go
- lua_service.go
- mfa.go
- password_verifier.go
- pool.go
- protect_impl.go
- rbl.go
- response.go
- rest.go
- services_registry.go
- statistics.go
- types.go
- webauthn_nohydra.go
- workflow.go