core

package
v4.0.0-alpha.21 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: GPL-3.0 Imports: 127 Imported by: 0

Documentation

Overview

Package core provides core functionality.

Index

Constants

View Source
const (
	// DefaultNumberOfBackupCodes defines the default number of backup codes to generate.
	DefaultNumberOfBackupCodes = 10
	// DefaultBackupCodeLength defines the default length of a single backup code.
	DefaultBackupCodeLength = 8
	// BackupCodeAlphabet excludes characters that are easy to confuse when read from screen or paper.
	BackupCodeAlphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz"
)
View Source
const (
	// PassDBAdditionalAttributePluginFacts stores validated policy facts emitted
	// by a native plugin backend result.
	PassDBAdditionalAttributePluginFacts = "plugin_policy_facts"
)

Variables

View Source
var (
	// ErrAuthApplicationDependencyMissing means the service was built without required dependencies.
	ErrAuthApplicationDependencyMissing = stderrors.New("auth application service dependency missing")
	// ErrAuthOutcomeMissing means the auth FSM returned without a captured terminal outcome.
	ErrAuthOutcomeMissing = stderrors.New("auth application service outcome missing")
)
View Source
var BackendServers = NewBackendServer()

BackendServers is an exported package value.

View Source
var ErrMFAAttemptLimit = errors.New("MFA verification attempt limit exceeded")

ErrMFAAttemptLimit indicates that the account's shared code-verification budget is exhausted.

View Source
var ErrMFAProofRejected = errors.New("MFA proof rejected")

ErrMFAProofRejected reports a valid MFA operation whose submitted proof did not verify.

Functions

func ApplyStructuredAuthRequest

func ApplyStructuredAuthRequest(auth State, request *authdto.Request)

ApplyStructuredAuthRequest updates the provided authentication state with data from the structured request payload, if available.

func AttachPostActionExecutionGate

func AttachPostActionExecutionGate(parent context.Context, ctx *gin.Context)

AttachPostActionExecutionGate copies a standard-context gate into a Gin request.

func AuthnInternalProfileIDs

func AuthnInternalProfileIDs() ([]decisionservice.InternalProfileID, error)

AuthnInternalProfileIDs returns the complete detached set of production internal caller identities.

func AuthnStandardEffectBindings

func AuthnStandardEffectBindings() (
	map[string]policyruntime.SyncEffectProvider,
	map[string]policyruntime.PostActionProvider,
)

AuthnStandardEffectBindings creates detached generation bindings from the immutable registry mapping.

func BeginCanonicalWebAuthnLogin

func BeginCanonicalWebAuthnLogin(
	ctx context.Context,
	session *cookie.CanonicalSession,
	flow sessionstate.Handle,
	identity string,
	protocolName string,
	user *backend.User,
) (*protocol.CredentialAssertion, sessionstate.Handle, error)

BeginCanonicalWebAuthnLogin creates one typed, parent-bound login ceremony.

func BeginCanonicalWebAuthnRegistration

func BeginCanonicalWebAuthnRegistration(
	ctx context.Context,
	deps AuthDeps,
	session *cookie.CanonicalSession,
	flow sessionstate.Handle,
	identity string,
	protocolName string,
	user *backend.User,
) (*protocol.CredentialCreation, sessionstate.Handle, error)

BeginCanonicalWebAuthnRegistration creates one typed, enrollment-bound registration ceremony.

func CompleteCanonicalWebAuthnLogin

func CompleteCanonicalWebAuthnLogin(
	ctx *gin.Context,
	deps AuthDeps,
	session *cookie.CanonicalSession,
	ceremony sessionstate.Handle,
	flow sessionstate.Handle,
	identity string,
	protocolName string,
	protocolContext IDPMFAProtocolContext,
	user *backend.User,
	authState *AuthState,
) (*backend.User, bool)

CompleteCanonicalWebAuthnLogin consumes and verifies one typed login ceremony.

func CompleteCanonicalWebAuthnRegistration

func CompleteCanonicalWebAuthnRegistration(
	ctx *gin.Context,
	deps AuthDeps,
	session *cookie.CanonicalSession,
	ceremony sessionstate.Handle,
	flow sessionstate.Handle,
	identity string,
	protocolName string,
	user *backend.User,
	authState *AuthState,
) error

CompleteCanonicalWebAuthnRegistration consumes and persists one typed registration ceremony.

func CompletePostActionResponse

func CompletePostActionResponse(ctx *gin.Context)

CompletePostActionResponse releases the gate attached to ctx when one exists.

func ComputeBruteForceHints

func ComputeBruteForceHints(ctx context.Context, cfg config.File, redisClient rediscli.Client, clientIP, protocol, oidccid string) (clientNet string, repeating bool)

ComputeBruteForceHints derives client-network and repetition facts for configured actions. It evaluates the active brute-force rules without relying on a process-wide Lua worker. the previous inline implementation used by ExecuteLuaPostAction.

func ConsumeMFAAttempt

func ConsumeMFAAttempt(ctx context.Context, deps AuthDeps, identity string) error

ConsumeMFAAttempt reserves one account-wide TOTP/recovery verification before accessing a verifier. The trusted stable identity excludes IP, method and challenge so none can reset the budget. Successful attempts also consume capacity; resetting on success would race concurrent guesses.

func ContextWithGRPCMethod

func ContextWithGRPCMethod(ctx context.Context, method string) context.Context

ContextWithGRPCMethod stores a server-derived gRPC method for request policy facts.

func ContextWithOIDCClaims

func ContextWithOIDCClaims(ctx context.Context, claims any) context.Context

ContextWithOIDCClaims stores validated backchannel OIDC claims for auth application execution that has to preserve existing list-accounts scope checks.

func DetachedPostActionContext

func DetachedPostActionContext(requestContext context.Context) context.Context

DetachedPostActionContext keeps trace identity while using service-lifetime cancellation.

func FilterSensitiveOutputAttributes

func FilterSensitiveOutputAttributes(attributes bktype.AttributeMapping, configuredNames ...string) bktype.AttributeMapping

FilterSensitiveOutputAttributes copies attributes while dropping secret-bearing fields.

func GenerateBackupCodes

func GenerateBackupCodes() (*mfa.TOTPRecovery, error)

GenerateBackupCodes generates a new set of backup codes.

func HandleBackendErrors

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 HandleErrWithDeps

func HandleErrWithDeps(ctx *gin.Context, err error, _ AuthDeps)

HandleErrWithDeps is a DI-capable variant of HandleErr.

func HandleJSONError

func HandleJSONError(ctx *gin.Context, err error)

HandleJSONError handles JSON validation errors by aborting the request and returning a JSON response with error details.

func HandleJSONValidationError

func HandleJSONValidationError(ctx *gin.Context, field, message string)

HandleJSONValidationError handles manual validation errors by returning a JSON response in the same format as Gin's validation errors.

func InitPassDBResultPool

func InitPassDBResultPool()

InitPassDBResultPool initializes the PassDBResultPool in the objpool package This function should be called during application initialization

func IsSensitiveOutputAttribute

func IsSensitiveOutputAttribute(name string, configuredNames ...string) bool

IsSensitiveOutputAttribute reports whether an attribute name carries secret material. Configured names are matched exactly so deployment-specific MFA storage fields remain internal.

func ListBackendServers

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

func LoadStatsFromRedis(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client)

LoadStatsFromRedis loads the prometheus statistics at startup from a Redis server.

func LogIDPMFAuthResult

func LogIDPMFAuthResult(
	ctx *gin.Context,
	deps AuthDeps,
	protocolContext IDPMFAProtocolContext,
	username string,
	method string,
	statusMessage string,
	successful bool,
)

LogIDPMFAuthResult writes a Notice log for the result of a second-factor verification during the IDP login flow. It is intentionally not gated behind debug modules.

func NewAsyncJobStatusHandler

func NewAsyncJobStatusHandler(cfg config.File, logger *slog.Logger, redisClient rediscli.Client) gin.HandlerFunc

NewAsyncJobStatusHandler constructs a Gin handler for querying async job status using injected dependencies.

func NewBruteForceFlushAsyncHandler

func NewBruteForceFlushAsyncHandler(cfg config.File, logger *slog.Logger, redisClient rediscli.Client) gin.HandlerFunc

NewBruteForceFlushAsyncHandler constructs a Gin handler for the BruteForce flush async endpoint using injected dependencies.

func NewBruteForceFlushHandler

func NewBruteForceFlushHandler(cfg config.File, logger *slog.Logger, redisClient rediscli.Client) gin.HandlerFunc

NewBruteForceFlushHandler constructs a Gin handler for the BruteForce flush endpoint using injected dependencies.

func NewBruteForceListHandler

func NewBruteForceListHandler(cfg config.File, logger *slog.Logger, redisClient rediscli.Client) gin.HandlerFunc

NewBruteForceListHandler constructs a Gin handler for the BruteForce list endpoint using injected dependencies.

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 NewUserFlushAsyncHandler

func NewUserFlushAsyncHandler(cfg config.File, logger *slog.Logger, redisClient rediscli.Client, tokenFlusher ...TokenFlusher) gin.HandlerFunc

NewUserFlushAsyncHandler constructs a Gin handler for the async user cache flush endpoint using injected dependencies.

func NewUserFlushHandler

func NewUserFlushHandler(cfg config.File, logger *slog.Logger, redisClient rediscli.Client, tokenFlusher ...TokenFlusher) gin.HandlerFunc

NewUserFlushHandler constructs a Gin handler for the user cache flush endpoint using injected dependencies.

func NormalizeTOTPCode

func NormalizeTOTPCode(code string) string

NormalizeTOTPCode accepts common authenticator copy formats without changing the TOTP value.

func NormalizeTOTPSecret

func NormalizeTOTPSecret(secret string) string

NormalizeTOTPSecret accepts raw Base32 secrets and accidentally persisted otpauth URLs.

func PostActionExecutionDone

func PostActionExecutionDone(ctx *gin.Context) <-chan struct{}

PostActionExecutionDone returns the response-finalization channel attached to ctx.

func PostActionExecutionDoneFromContext

func PostActionExecutionDoneFromContext(ctx context.Context) <-chan struct{}

PostActionExecutionDoneFromContext returns a standard-context response gate.

func PostActionFinalizationGate

func PostActionFinalizationGate(ctx *gin.Context) effectsupervisor.FinalizationGate

PostActionFinalizationGate returns the typed response gate attached to ctx.

func PostActionFinalizationGateFromContext

func PostActionFinalizationGateFromContext(ctx context.Context) effectsupervisor.FinalizationGate

PostActionFinalizationGateFromContext returns a typed standard-context response gate.

func ProcessPassDBResult

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

func ProtectEndpointMiddleware(cfg config.File, logger *slog.Logger) 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 environment controls.

func PutPassDBResultToPool

func PutPassDBResultToPool(obj *PassDBResult)

PutPassDBResultToPool returns a PassDBResult object to the pool The object is reset before being returned to the pool

func RBLIsListed

func RBLIsListed(ctx *gin.Context, view *StateView, rbl *config.RBL) (bool, string, error)

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 RegisterBackendManagerFactory

func RegisterBackendManagerFactory(backendType definitions.Backend, factory BackendManagerFactory)

RegisterBackendManagerFactory registers a backend manager factory.

func SanitizeHTTPMetadata

func SanitizeHTTPMetadata(headers http.Header, credentialHeaderNames ...string) map[string][]string

SanitizeHTTPMetadata returns detached lowercase request headers without credential-bearing values.

func SaveStatsToRedis

func SaveStatsToRedis(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client)

SaveStatsToRedis saves the prometheus statistics to a Redis server.

func SetDefaultAccountCache

func SetDefaultAccountCache(ac *accountcache.Manager)

SetDefaultAccountCache sets the process-wide default account cache for core.

func SetDefaultChannel

func SetDefaultChannel(ch backend.Channel)

SetDefaultChannel sets the process-wide default channel for core.

func SetDefaultEnvironment

func SetDefaultEnvironment(env config.Environment)

SetDefaultEnvironment sets the process-wide default environment. Call this at boundaries (HTTP startup, workers, etc.) once the environment is known.

func SetDefaultLogger

func SetDefaultLogger(l *slog.Logger)

SetDefaultLogger sets the process-wide default logger for core.

func SetDefaultResponseWriter

func SetDefaultResponseWriter(w ResponseWriter)

SetDefaultResponseWriter configures the process-wide response writer. This is set at the HTTP boundary during startup so that request paths do not need to access global config/logger/environment.

func TotpValidation

func TotpValidation(_ *gin.Context, auth *AuthState, code string, deps AuthDeps) error

TotpValidation validates a TOTP code for a given account. It also checks for backup/recovery codes.

func UpdateRedisPoolStats

func UpdateRedisPoolStats(redisClient rediscli.Client)

UpdateRedisPoolStats updates and tracks Redis pool statistics such as hits, misses, timeouts, and connection counts.

func ValidateTOTPCode

func ValidateTOTPCode(code string, totpSecret string, deps AuthDeps) error

ValidateTOTPCode validates the time-based one-time password (TOTP) code against the provided secret.

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 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 AuthApplicationService

type AuthApplicationService interface {
	Authenticate(ctx context.Context, input AuthInput) (*AuthOutcome, error)
	LookupIdentity(ctx context.Context, input AuthInput) (*AuthOutcome, error)
	ListAccounts(ctx context.Context, input AuthInput) (*ListAccountsOutcome, error)
}

AuthApplicationService runs auth use cases behind transport adapters.

func NewAuthnCandidateApplicationService

func NewAuthnCandidateApplicationService(
	current AuthApplicationService,
	sessions authnCandidateDecisionSessionFactory,
	authentication decision.AuthenticationInput,
) (AuthApplicationService, error)

NewAuthnCandidateApplicationService constructs an explicit-evidence Decision Service adapter for tests.

func NewAuthnCandidateApplicationServiceWithInternalProfiles

func NewAuthnCandidateApplicationServiceWithInternalProfiles(
	current AuthApplicationService,
	sessions authnCandidateDecisionSessionFactory,
	profiles AuthnInternalCallerProfiles,
) (AuthApplicationService, error)

NewAuthnCandidateApplicationServiceWithInternalProfiles constructs an explicit-evidence test adapter.

func NewProductionAuthApplicationService

func NewProductionAuthApplicationService(
	deps AuthDeps,
	decisions *decisionservice.DecisionService,
) (AuthApplicationService, error)

NewProductionAuthApplicationService constructs the sole generation-captured auth application authority.

type AuthAttributes

type AuthAttributes struct {
	// Attributes is a map of user attributes retrieved from the backend.
	Attributes bktype.AttributeMapping
	// contains filtered or unexported fields
}

AuthAttributes handles user attributes and their synchronization.

type AuthCacheInvalidator

type AuthCacheInvalidator interface {
	InvalidateIdentities(identities ...string) int
}

AuthCacheInvalidator removes local authentication state by public identity.

type AuthContext

type AuthContext struct {
	RequestMetadata map[string][]string
	Transport       AuthTransportContext

	Method    string
	UserAgent string

	ClientIP          string
	ClientPort        string
	ClientHostname    string
	ClientID          string
	ExternalSessionID 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
	SAMLEntityID 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

func NewAuthContext(opts ...AuthContextOption) AuthContext

NewAuthContext constructs an AuthContext value using the provided options.

type AuthContextOption

type AuthContextOption func(*AuthContext)

AuthContextOption mutates an AuthContext during construction.

func WithAuthTransportContext

func WithAuthTransportContext(transport AuthTransportContext) AuthContextOption

WithAuthTransportContext stores detached server-observed transport metadata.

func WithClientHostname

func WithClientHostname(h string) AuthContextOption

WithClientHostname provides the exported WithClientHostname function.

func WithClientID

func WithClientID(id string) AuthContextOption

WithClientID provides the exported WithClientID function.

func WithClientIP

func WithClientIP(ip string) AuthContextOption

WithClientIP provides the exported WithClientIP function.

func WithClientPort

func WithClientPort(p string) AuthContextOption

WithClientPort provides the exported WithClientPort function.

func WithExternalSessionID

func WithExternalSessionID(id string) AuthContextOption

WithExternalSessionID sets the optional upstream session identifier.

func WithLocalIP

func WithLocalIP(ip string) AuthContextOption

WithLocalIP provides the exported WithLocalIP function.

func WithLocalPort

func WithLocalPort(p string) AuthContextOption

WithLocalPort provides the exported WithLocalPort function.

func WithMethod

func WithMethod(m string) AuthContextOption

WithMethod provides the exported WithMethod function.

func WithOIDCCID

func WithOIDCCID(v string) AuthContextOption

WithOIDCCID provides the exported WithOIDCCID function.

func WithProtocol

func WithProtocol(proto string) AuthContextOption

WithProtocol provides the exported WithProtocol function.

func WithRequestMetadata

func WithRequestMetadata(values map[string][]string) AuthContextOption

WithRequestMetadata stores allowlisted transport metadata candidates for policy facts.

func WithSAMLEntityID

func WithSAMLEntityID(v string) AuthContextOption

WithSAMLEntityID stores the request-bound SAML service-provider identity.

func WithSSLFingerprint

func WithSSLFingerprint(v string) AuthContextOption

WithSSLFingerprint provides the exported WithSSLFingerprint function.

func WithSSLSerial

func WithSSLSerial(v string) AuthContextOption

WithSSLSerial provides the exported WithSSLSerial function.

func WithUserAgent

func WithUserAgent(ua string) AuthContextOption

WithUserAgent provides the exported WithUserAgent function.

func WithXSSL

func WithXSSL(v string) AuthContextOption

WithXSSL provides the exported WithXSSL function.

func WithXSSLCipher

func WithXSSLCipher(v string) AuthContextOption

WithXSSLCipher provides the exported WithXSSLCipher function.

func WithXSSLClientCN

func WithXSSLClientCN(v string) AuthContextOption

WithXSSLClientCN provides the exported WithXSSLClientCN function.

func WithXSSLClientDN

func WithXSSLClientDN(v string) AuthContextOption

WithXSSLClientDN provides the exported WithXSSLClientDN function.

func WithXSSLClientIssuerDN

func WithXSSLClientIssuerDN(v string) AuthContextOption

WithXSSLClientIssuerDN provides the exported WithXSSLClientIssuerDN function.

func WithXSSLClientNotAfter

func WithXSSLClientNotAfter(v string) AuthContextOption

WithXSSLClientNotAfter provides the exported WithXSSLClientNotAfter function.

func WithXSSLClientNotBefore

func WithXSSLClientNotBefore(v string) AuthContextOption

WithXSSLClientNotBefore provides the exported WithXSSLClientNotBefore function.

func WithXSSLClientSubjectDN

func WithXSSLClientSubjectDN(v string) AuthContextOption

WithXSSLClientSubjectDN provides the exported WithXSSLClientSubjectDN function.

func WithXSSLClientVerify

func WithXSSLClientVerify(v string) AuthContextOption

WithXSSLClientVerify provides the exported WithXSSLClientVerify function.

func WithXSSLIssuer

func WithXSSLIssuer(v string) AuthContextOption

WithXSSLIssuer provides the exported WithXSSLIssuer function.

func WithXSSLIssuerDN

func WithXSSLIssuerDN(v string) AuthContextOption

WithXSSLIssuerDN provides the exported WithXSSLIssuerDN function.

func WithXSSLProtocol

func WithXSSLProtocol(v string) AuthContextOption

WithXSSLProtocol provides the exported WithXSSLProtocol function.

func WithXSSLSessionID

func WithXSSLSessionID(v string) AuthContextOption

WithXSSLSessionID provides the exported WithXSSLSessionID function.

func WithXSSLSubjectDN

func WithXSSLSubjectDN(v string) AuthContextOption

WithXSSLSubjectDN provides the exported WithXSSLSubjectDN function.

type AuthDecision

type AuthDecision string

AuthDecision is the terminal application-level authentication decision.

const (
	// AuthDecisionUnset indicates that no terminal decision was produced.
	AuthDecisionUnset AuthDecision = "unset"
	// AuthDecisionOK indicates successful authentication.
	AuthDecisionOK AuthDecision = "ok"
	// AuthDecisionFail indicates a domain authentication failure.
	AuthDecisionFail AuthDecision = "fail"
	// AuthDecisionTempFail indicates a temporary authentication failure.
	AuthDecisionTempFail AuthDecision = "tempfail"
)

type AuthDeps

type AuthDeps struct {
	Cfg                        config.File
	Logger                     *slog.Logger
	Env                        config.Environment
	Redis                      rediscli.Client
	Tolerate                   tolerate.Tolerate
	Resp                       ResponseWriter
	AccountCache               *accountcache.Manager
	Channel                    backend.Channel
	Backend                    BackendManager
	PluginBackendFactory       BackendManagerFactory
	NativeRuntime              AuthnNativeRuntime
	HostServices               AuthnHostServices
	LDAPQueue                  LDAPRequestQueue
	LDAPAuthQueue              LDAPAuthRequestQueue
	BackendAuthenticationCache *PositiveBackendAuthenticationCache
}

AuthDeps bundles dependencies required by authentication request paths.

type AuthGroups

type AuthGroups struct {
	// Groups stores resolved group names.
	Groups []string

	// GroupDistinguishedNames stores resolved group distinguished names.
	GroupDistinguishedNames []string
	// contains filtered or unexported fields
}

AuthGroups handles resolved group memberships and their synchronization.

type AuthIDPContext

type AuthIDPContext struct {
	IdentityAttributeRequest *IdentityAttributeRequest
	Request                  AuthIDPRequestContext
	ExistingBackendRef       RemoteBackendRef
}

AuthIDPContext carries only bounded IdP values needed by authentication and identity lookup.

func NewAuthIDPContext

func NewAuthIDPContext(
	request IDPRequestContext,
	identityAttributeRequest *IdentityAttributeRequest,
	existingBackendRef RemoteBackendRef,
) AuthIDPContext

NewAuthIDPContext constructs a detached IdP application context.

func (AuthIDPContext) Clone

func (c AuthIDPContext) Clone() AuthIDPContext

Clone returns a detached copy of the IdP application context.

type AuthIDPRequestContext

type AuthIDPRequestContext struct {
	RequestedScopes []string
	GrantType       string
	RedirectURI     string
}

AuthIDPRequestContext carries protocol facts while excluding browser-owned MFA state.

type AuthInput

type AuthInput struct {
	Credentials        Credentials
	Context            AuthContext
	IDP                AuthIDPContext
	CorrelationID      string
	Mode               AuthMode
	EntryPoint         AuthnEntryPoint
	Service            string
	AuthLoginAttempt   uint
	DisableMemoryCache bool
	DisableCache       bool
}

AuthInput contains transport-neutral authentication input.

func NewAuthInputFromStructuredRequest

func NewAuthInputFromStructuredRequest(service string, mode AuthMode, request authdto.Request) AuthInput

NewAuthInputFromStructuredRequest maps the shared structured auth DTO into transport-neutral application input.

type AuthInputError

type AuthInputError struct {
	Field  string
	Reason string
}

AuthInputError reports an invalid transport-neutral request field.

func (*AuthInputError) Error

func (e *AuthInputError) Error() string

type AuthMode

type AuthMode string

AuthMode describes the application-level auth operation.

const (
	// AuthModeAuthenticate runs the normal password authentication pipeline.
	AuthModeAuthenticate AuthMode = "auth"
	// AuthModeLookupIdentity runs the trusted identity lookup path without a password.
	AuthModeLookupIdentity AuthMode = "lookup-identity"
	// AuthModeListAccounts runs the account-provider listing path.
	AuthModeListAccounts AuthMode = "list-accounts"
)

type AuthOutcome

type AuthOutcome = authOutcomeProjection[AuthDecision]

AuthOutcome contains the captured terminal authentication result.

type AuthPermissionDeniedError

type AuthPermissionDeniedError struct {
	Reason string
}

AuthPermissionDeniedError reports a domain authorization rejection before the auth use case can proceed.

func (*AuthPermissionDeniedError) Error

func (e *AuthPermissionDeniedError) Error() string

type AuthPreprocessRejectedError

type AuthPreprocessRejectedError struct {
	Outcome *AuthOutcome
}

AuthPreprocessRejectedError reports a list-accounts preprocessing rejection.

func (*AuthPreprocessRejectedError) Error

type AuthRequest

type AuthRequest struct {
	// Protocol is the protocol used for the request.
	Protocol *config.Protocol

	// HTTPClientContext is the Gin context associated with the request.
	HTTPClientContext *gin.Context

	// HTTPClientRequest is the HTTP request being processed.
	HTTPClientRequest *http.Request

	// RequestMetadata contains incoming transport metadata such as gRPC metadata.
	RequestMetadata map[string][]string

	// Transport contains server-observed transport evidence supplied by the boundary adapter.
	Transport AuthTransportContext

	// Method is the authentication method.
	Method string

	// Username is the name of the user attempting to authenticate.
	Username string

	// Password is the user's password.
	Password secret.Value

	// ClientIP is the IP address of the client making the request.
	ClientIP string

	// XClientPort is the port number of the client.
	XClientPort string

	// ClientHost is the hostname of the client.
	ClientHost string

	// UserAgent is the user agent string of the client.
	UserAgent string

	// Service is the name of the service being accessed.
	Service string

	// OIDCCID is the OIDC client ID.
	OIDCCID string

	// SAMLEntityID is the SAML Entity ID.
	SAMLEntityID string

	// XSSL indicates whether the connection is SSL/TLS.
	XSSL string // %[ssl_fc]

	// XSSLSessionID is the SSL session ID.
	XSSLSessionID string // %[ssl_fc_session_id,hex]

	// XSSLClientVerify indicates the status of client certificate verification.
	XSSLClientVerify string // %[ssl_c_verify]

	// XSSLClientDN is the distinguished name of the client certificate.
	XSSLClientDN string // %{+Q}[ssl_c_s_dn]

	// XSSLClientCN is the common name of the client certificate.
	XSSLClientCN string // %{+Q}[ssl_c_s_dn(cn)]

	// XSSLIssuer is the issuer of the client certificate.
	XSSLIssuer string // %{+Q}[ssl_c_i_dn]

	// XSSLClientNotBefore is the "Not Before" date of the client certificate.
	XSSLClientNotBefore string // %{+Q}[ssl_c_notbefore]

	// XSSLClientNotAfter is the "Not After" date of the client certificate.
	XSSLClientNotAfter string // %{+Q}[ssl_c_notafter]

	// XSSLSubjectDN is the subject DN of the server certificate.
	XSSLSubjectDN string // %{+Q}[ssl_c_s_dn]

	// XSSLIssuerDN is the issuer DN of the server certificate.
	XSSLIssuerDN string // %{+Q}[ssl_c_i_dn]

	// XSSLClientSubjectDN is the subject DN of the client certificate.
	XSSLClientSubjectDN string // %{+Q}[ssl_c_s_dn]

	// XSSLClientIssuerDN is the issuer DN of the client certificate.
	XSSLClientIssuerDN string // %{+Q}[ssl_c_i_dn]

	// XSSLProtocol is the SSL/TLS protocol version.
	XSSLProtocol string // %[ssl_fc_protocol]

	// XSSLCipher is the SSL/TLS cipher suite used.
	XSSLCipher string // %[ssl_fc_cipher]

	// SSLSerial is the serial number of the SSL certificate.
	SSLSerial string

	// SSLFingerprint is the fingerprint of the SSL certificate.
	SSLFingerprint string

	// AuthLoginAttempt is the incoming authentication attempt ordinal.
	AuthLoginAttempt uint

	// XClientID is a custom client identifier.
	XClientID string

	// ExternalSessionID is an upstream session identifier supplied by the caller.
	ExternalSessionID string

	// XLocalIP is the local IP address on which the request was received.
	XLocalIP string

	// XPort is the local port number on which the request was received.
	XPort string

	// NoAuth indicates whether authentication should be skipped.
	NoAuth bool

	// ListAccounts indicates whether to list available accounts.
	ListAccounts bool
}

AuthRequest holds data directly extracted from the HTTP request or connection metadata.

type AuthResponseSettings

type AuthResponseSettings struct {
	SMTPBackendAddress  string
	IMAPBackendAddress  string
	POP3BackendAddress  string
	DefaultLanguage     string
	InstanceName        string
	SMTPBackendPort     int
	IMAPBackendPort     int
	POP3BackendPort     int
	NginxWaitDelay      uint
	BackendHealthChecks bool
	Captured            bool
}

AuthResponseSettings snapshots config-derived response inputs from one runtime generation.

type AuthRuntime

type AuthRuntime struct {
	// IDPContext carries typed request-local protocol facts for canonical browser flows.
	IDPContext *IDPRequestContext

	// StartTime is the time when the authentication request started.
	StartTime time.Time

	// AdditionalLogs contains additional log entries for the request.
	AdditionalLogs []any

	// MonitoringFlags holds flags related to request monitoring.
	MonitoringFlags []definitions.Monitoring

	// BruteForceBuckets contains read-only bucket facts collected for policy evaluation.
	BruteForceBuckets []bruteforce.BucketPolicyFact

	// AccountProviderPluginFacts contains native plugin account-list facts for policy evaluation.
	AccountProviderPluginFacts []pluginapi.PolicyFact

	// BruteForceToleration contains the request-local toleration fact collected for policy evaluation.
	BruteForceToleration tolerate.PolicyFact

	// RelayDomainPolicy contains the request-local relay-domain facts collected for policy evaluation.
	RelayDomainPolicy RelayDomainPolicyFact

	// RBLPolicy contains the request-local RBL facts collected for policy evaluation.
	RBLPolicy RBLPolicyFact

	// GUID is a unique identifier for the authentication request.
	GUID string

	// StatusMessage is a message describing the status of the request.
	StatusMessage string

	// StatusMessageI18NKey is the policy-selected localization key for StatusMessage.
	StatusMessageI18NKey string

	// ResponseLanguage is the policy-selected response-rendering language.
	ResponseLanguage string

	// AuthFSMTerminalState contains the current auth FSM terminal state when known.
	AuthFSMTerminalState string

	// AccountField is the name of the field containing the account information.
	AccountField string

	// AccountName is the name of the account being authenticated.
	AccountName string

	// EnvironmentName is the name of the environment control or source being accessed.
	EnvironmentName string

	// RemoteBackendRef binds follow-up identity operations to an authority-side backend.
	RemoteBackendRef RemoteBackendRef

	// IdentityAttributeRequest carries edge-side requested backend attributes for claim materialization.
	IdentityAttributeRequest *IdentityAttributeRequest

	// BackendName is the name of the backend used for authentication.
	BackendName string

	// UsedBackendIP is the IP address of the backend server used.
	UsedBackendIP string

	// TOTPSecret is the secret used for TOTP authentication.
	TOTPSecret string

	// TOTPSecretField is the field name containing the TOTP secret.
	TOTPSecretField string

	// TOTPRecoveryField is the field name containing the TOTP recovery codes.
	TOTPRecoveryField string

	// UniqueUserIDField is the field name containing the unique user ID.
	UniqueUserIDField string

	// DisplayNameField is the field name containing the user's display name.
	DisplayNameField string

	// BFClientNet is the network address used for brute-force detection.
	BFClientNet string

	// AdditionalAttributes contains additional attribute-specific data.
	AdditionalAttributes map[string]any

	// AuthFSMEventPath contains current auth FSM events seen by this request.
	AuthFSMEventPath []string

	// Context is the Lua context associated with the request.
	Context *lualib.Context

	// UsedBackendPort is the port number of the backend server used.
	UsedBackendPort int

	// StatusCodeOK is the HTTP status code for a successful request.
	StatusCodeOK int

	// StatusCodeInternalError is the HTTP status code for an internal server error.
	StatusCodeInternalError int

	// StatusCodeFail is the HTTP status code for a failed authentication.
	StatusCodeFail int

	// SourcePassDBBackend is the source password database backend.
	SourcePassDBBackend definitions.Backend

	// UsedPassDBBackend is the password database backend actually used.
	UsedPassDBBackend definitions.Backend

	// UserFound indicates whether the user was found in the backend.
	UserFound bool

	// Authenticated indicates whether the user was successfully authenticated.
	Authenticated bool

	// Authorized indicates whether the user is authorized for the request.
	Authorized bool

	// BFRepeating indicates whether brute-force detection is repeating.
	BFRepeating bool

	// BFRWP stores the request-level Repeating Wrong Password (RWP) allowance decision.
	// A pre-auth candidate is cleared after successful authentication, so final logs retain true only for failures
	// whose brute-force bucket counters were not increased.
	BFRWP bool
	// BruteForceError marks unavailable protection, distinct from an attack.
	BruteForceError bool

	// MasterUserMode indicates whether the request is in master user mode.
	MasterUserMode bool
}

AuthRuntime holds process-related data generated or tracked during the authentication request.

type AuthSecurity

type AuthSecurity struct {
	// Tolerate is the brute-force tolerance configuration.
	Tolerate tolerate.Tolerate

	// BruteForceName is the name of the brute-force protection profile.
	BruteForceName string

	// BruteForceCounter keeps track of brute-force attempts.
	BruteForceCounter map[string]uint

	// Logs contains custom log entries.
	Logs *lualib.CustomLogKeyValue

	// PasswordsAccountSeen is the number of passwords seen for the account.
	PasswordsAccountSeen uint

	// PasswordsTotalSeen is the total number of passwords seen.
	PasswordsTotalSeen uint

	// LoginAttempts is the number of login attempts made.
	LoginAttempts uint
	// contains filtered or unexported fields
}

AuthSecurity manages counters, managers and history related to brute-force and security.

type AuthState

type AuthState struct {

	// Request holds data directly extracted from the HTTP request or connection metadata.
	Request AuthRequest

	// Runtime holds process-related data generated or tracked during the authentication request.
	Runtime AuthRuntime

	// Security manages counters, managers and history related to brute-force and security.
	Security AuthSecurity

	// Attributes handles user attributes and their synchronization.
	Attributes AuthAttributes

	// Groups handles resolved groups and their synchronization.
	Groups AuthGroups
	// contains filtered or unexported fields
}

AuthState represents a struct that holds information related to an authentication process.

func NewIDPSpecializedAuthState

func NewIDPSpecializedAuthState(
	ctx *gin.Context,
	deps AuthDeps,
	input AuthInput,
	outcome *AuthOutcome,
) (*AuthState, error)

NewIDPSpecializedAuthState materializes successful admitted identity data for specialized MFA operations. It does not execute authentication, policy evaluation, or browser-flow state transitions.

func (*AuthState) AccountCache

func (a *AuthState) AccountCache() *accountcache.Manager

AccountCache provides the exported AccountCache method.

func (*AuthState) ApplyContextData

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

func (a *AuthState) ApplyCredentials(c Credentials)

ApplyCredentials applies non-empty credential fields to the AuthState.

func (*AuthState) ApplyPluginResponseMutation

func (a *AuthState) ApplyPluginResponseMutation(ctx *gin.Context, mutation pluginapi.ResponseMutation)

ApplyPluginResponseMutation applies safe plugin response mutations while the HTTP response is still mutable.

func (*AuthState) AuthFail

func (a *AuthState) AuthFail(ctx *gin.Context)

AuthFail handles the failure of authentication. It increases the login attempts, then delegates header/logging to the ResponseWriter.

func (*AuthState) AuthOK

func (a *AuthState) AuthOK(ctx *gin.Context)

AuthOK is the general method to indicate authentication success.

func (*AuthState) AuthTempFail

func (a *AuthState) AuthTempFail(ctx *gin.Context, reason string)

AuthTempFail sends a temporary failure response with the provided reason and logs the error.

func (*AuthState) AuthnRequestStageFlags

func (a *AuthState) AuthnRequestStageFlags() AuthnRequestStageFlags

AuthnRequestStageFlags derives stage visibility only from the captured request state.

func (*AuthState) Cfg

func (a *AuthState) Cfg() config.File

Cfg provides the exported Cfg method.

func (*AuthState) Channel

func (a *AuthState) Channel() backend.Channel

Channel provides the exported Channel method.

func (*AuthState) CheckBruteForce

func (a *AuthState) CheckBruteForce(ctx *gin.Context) (blockClientIP bool)

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) CheckBucketOverLimit

func (a *AuthState) CheckBucketOverLimit(rules []config.BruteForceRule, message *string) (withError bool, ruleTriggered bool, ruleNumber int)

CheckBucketOverLimit checks if any brute force bucket limit has been exceeded.

func (*AuthState) CheckRepeatingBruteForcer

func (a *AuthState) CheckRepeatingBruteForcer(rules []config.BruteForceRule, network **net.IPNet, message *string) (withError bool, alreadyTriggered bool, ruleNumber int)

CheckRepeatingBruteForcer checks for repeating brute force attacks based on the given rules.

func (*AuthState) CollectBucketPolicyFacts

func (a *AuthState) CollectBucketPolicyFacts(rules []config.BruteForceRule) ([]bruteforce.BucketPolicyFact, error)

CollectBucketPolicyFacts reads current brute-force bucket policy facts.

func (*AuthState) CommitRWPSlidingWindow

func (a *AuthState) CommitRWPSlidingWindow() (bool, error)

CommitRWPSlidingWindow delegates to the underlying BucketManager to write the RWP hash.

func (*AuthState) ControlRBL

func (a *AuthState) ControlRBL(ctx *gin.Context) (triggered bool, err error)

ControlRBL checks the client IP address against configured RBL providers.

func (*AuthState) ControlRelayDomains

func (a *AuthState) ControlRelayDomains() (triggered bool)

ControlRelayDomains 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) ControlTLSEncryption

func (a *AuthState) ControlTLSEncryption(ctx *gin.Context) (triggered bool)

ControlTLSEncryption checks, if the remote client connection was secured.

func (*AuthState) CreatePositivePasswordCache

func (a *AuthState) CreatePositivePasswordCache() *bktype.PositivePasswordCache

CreatePositivePasswordCache constructs a PositivePasswordCache containing user authentication details.

func (*AuthState) Ctx

func (a *AuthState) Ctx() context.Context

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) DeleteAttribute

func (a *AuthState) DeleteAttribute(name string)

DeleteAttribute removes the attribute with the given name from the AuthState in a concurrency-safe manner. It is safe to call from multiple goroutines.

func (*AuthState) DeleteIPBruteForceRedis

func (a *AuthState) DeleteIPBruteForceRedis(rule *config.BruteForceRule, ruleName string) (removedKey string, err error)

DeleteIPBruteForceRedis removes brute force tracking for an IP from Redis.

func (*AuthState) DeleteWebAuthnCredential

func (a *AuthState) DeleteWebAuthnCredential(credential *mfa.PersistentCredential) (err error)

DeleteWebAuthnCredential removes a WebAuthn credential for the user in the backend.

func (*AuthState) DeleteWebAuthnCredentialFromSelectedBackend

func (a *AuthState) DeleteWebAuthnCredentialFromSelectedBackend(credential *mfa.PersistentCredential) error

DeleteWebAuthnCredentialFromSelectedBackend deletes a credential only from the backend selected by authentication.

func (*AuthState) Env

func (a *AuthState) Env() config.Environment

Env provides the exported Env method.

func (*AuthState) EnvironmentLuaSource

func (a *AuthState) EnvironmentLuaSource(
	ctx *gin.Context,
	name string,
	prototype *lua.FunctionProto,
	pools *vmpool.Manager,
	poolKey vmpool.PoolKey,
	modules *luaseal.Modules,
) (triggered bool, skipRemainingEnvironment bool, err error)

EnvironmentLuaSource runs one generation-owned precompiled environment source.

func (*AuthState) FillAccessTokenClaims

func (a *AuthState) FillAccessTokenClaims(
	cfgClaims *config.AccessTokenClaims,
	claims map[string]any,
	requestedScopes []string,
	customScopes []config.Oauth2CustomScope,
)

FillAccessTokenClaims populates a map of claims from AccessTokenClaims configuration.

func (*AuthState) FillCommonRequest

func (a *AuthState) FillCommonRequest(cr *lualib.CommonRequest)

FillCommonRequest populates a CommonRequest object from the current AuthState.

func (*AuthState) FillIDTokenClaims

func (a *AuthState) FillIDTokenClaims(
	cfgClaims *config.IDTokenClaims,
	claims map[string]any,
	requestedScopes []string,
	customScopes []config.Oauth2CustomScope,
)

FillIDTokenClaims populates a map of claims from IDTokenClaims configuration.

func (*AuthState) FinishLogging

func (a *AuthState) FinishLogging(ctx *gin.Context, result definitions.AuthResult)

FinishLogging logs the authentication result and updates metrics.

func (*AuthState) FinishSetup

func (a *AuthState) FinishSetup(ctx *gin.Context)

FinishSetup completes the initialization of the state and logs the incoming request.

func (*AuthState) GetAccount

func (a *AuthState) GetAccount() string

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

func (a *AuthState) GetAccountField() string

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

func (a *AuthState) GetAccountOk() (string, bool)

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

func (a *AuthState) GetAdditionalLogs() []any

GetAdditionalLogs returns a slice of additional logs associated with the AuthState instance.

func (*AuthState) GetAttribute

func (a *AuthState) GetAttribute(name string) ([]any, bool)

GetAttribute returns the attribute slice and a boolean indicating presence, under a read lock.

func (*AuthState) GetAttributes

func (a *AuthState) GetAttributes() bktype.AttributeMapping

GetAttributes retrieves the stored database attributes from the AuthState and returns them as a AttributeMapping.

func (*AuthState) GetAttributesCopy

func (a *AuthState) GetAttributesCopy() bktype.AttributeMapping

GetAttributesCopy returns a deep copy of the Attributes map to avoid aliasing across components. The copy is made under a read lock; callers may safely mutate the returned map.

func (*AuthState) GetBackendManager

func (a *AuthState) GetBackendManager(backendType definitions.Backend, backendName string) BackendManager

GetBackendManager returns a BackendManager based on the provided backend type and name.

func (*AuthState) GetBruteForceBanRedisKey

func (a *AuthState) GetBruteForceBanRedisKey(rule *config.BruteForceRule) (key string, network string, err error)

GetBruteForceBanRedisKey returns the Redis ban key and normalized network for the specified brute force rule.

func (*AuthState) GetBruteForceBucketRedisKey

func (a *AuthState) GetBruteForceBucketRedisKey(rule *config.BruteForceRule) (key string)

GetBruteForceBucketRedisKey returns the Redis key for the specified brute force rule.

func (*AuthState) GetBruteForceCounter

func (a *AuthState) GetBruteForceCounter() map[string]uint

GetBruteForceCounter returns the brute force counter from the AuthState.

func (*AuthState) GetBruteForceError

func (a *AuthState) GetBruteForceError() error

GetBruteForceError reports request-level protection unavailability.

func (*AuthState) GetBruteForceName

func (a *AuthState) GetBruteForceName() string

GetBruteForceName returns the brute force name from the AuthState.

func (*AuthState) GetBucketKeys

func (a *AuthState) GetBucketKeys(rule *config.BruteForceRule) []string

GetBucketKeys returns all Redis keys associated with a brute force rule.

func (*AuthState) GetBucketPolicyFacts

func (a *AuthState) GetBucketPolicyFacts() []bruteforce.BucketPolicyFact

GetBucketPolicyFacts returns the last collected brute-force bucket policy facts.

func (*AuthState) GetCacheNameFor

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

func (a *AuthState) GetClientIP() string

GetClientIP returns the client's IP address stored in the AuthState instance.

func (*AuthState) GetDisplayName

func (a *AuthState) GetDisplayName() string

GetDisplayName returns the display name for a user. If there is no account, it returns the empty string "".

func (*AuthState) GetDisplayNameField

func (a *AuthState) GetDisplayNameField() string

GetDisplayNameField retrieves the display name field from the AuthState. Returns an empty string if it's nil.

func (*AuthState) GetDisplayNameOk

func (a *AuthState) GetDisplayNameOk() (string, bool)

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) GetEnvironmentName

func (a *AuthState) GetEnvironmentName() string

GetEnvironmentName returns the environment name from the AuthState.

func (*AuthState) GetFailCount

func (a *AuthState) GetFailCount() uint

GetFailCount returns the current number of failed login attempts using the centralized manager if available. If the manager is not initialized, it falls back to the legacy field. This method is used for logging current_password_retries to ensure the value represents the number of failures (0-based), not the 1-based attempt ordinal.

func (*AuthState) GetFromLocalCache

func (a *AuthState) GetFromLocalCache(ctx *gin.Context) bool

GetFromLocalCache applies one complete positive backend snapshot to the current request.

func (*AuthState) GetGUID

func (a *AuthState) GetGUID() string

GetGUID retrieves the GUID from the AuthState. Returns an empty string if the GUID is nil.

func (*AuthState) GetGroupDistinguishedNames

func (a *AuthState) GetGroupDistinguishedNames() []string

GetGroupDistinguishedNames returns a copy of resolved group distinguished names.

func (*AuthState) GetGroups

func (a *AuthState) GetGroups() []string

GetGroups returns a copy of resolved group names.

func (*AuthState) GetLogger

func (a *AuthState) GetLogger() *slog.Logger

GetLogger provides the exported GetLogger method.

func (*AuthState) GetLoginAttempts

func (a *AuthState) GetLoginAttempts() uint

GetLoginAttempts returns the number of login attempts from the AuthState.

func (*AuthState) GetPassword

func (a *AuthState) GetPassword() secret.Value

GetPassword retrieves the password stored in the AuthState instance.

func (*AuthState) GetPasswordsAccountSeen

func (a *AuthState) GetPasswordsAccountSeen() uint

GetPasswordsAccountSeen returns the count of passwords seen for the account.

func (*AuthState) GetPasswordsTotalSeen

func (a *AuthState) GetPasswordsTotalSeen() uint

GetPasswordsTotalSeen returns the total count of passwords seen across all accounts.

func (*AuthState) GetProtocol

func (a *AuthState) GetProtocol() *config.Protocol

GetProtocol retrieves the configured Protocol for the AuthState. If no Protocol is set, it returns a default Protocol instance.

func (*AuthState) GetSlidingWindowKeys

func (a *AuthState) GetSlidingWindowKeys(rule *config.BruteForceRule, network *net.IPNet) (currentKey, prevKey string, weight float64)

GetSlidingWindowKeys returns the current and previous window keys for a rule.

func (*AuthState) GetSourcePassDBBackend

func (a *AuthState) GetSourcePassDBBackend() definitions.Backend

GetSourcePassDBBackend returns the source backend used for the password database during the authentication process.

func (*AuthState) GetTOTPRecoveryCodes

func (a *AuthState) GetTOTPRecoveryCodes() []string

GetTOTPRecoveryCodes returns the TOTP recovery codes for a user.

func (*AuthState) GetTOTPRecoveryField

func (a *AuthState) GetTOTPRecoveryField() string

GetTOTPRecoveryField retrieves the TOTP recovery field value from AuthState. Returns an empty string if not set.

func (*AuthState) GetTOTPSecret

func (a *AuthState) GetTOTPSecret() string

GetTOTPSecret returns the TOTP secret for a user. If there is no secret, it returns the empty string "".

func (*AuthState) GetTOTPSecretField

func (a *AuthState) GetTOTPSecretField() string

GetTOTPSecretField retrieves the TOTP secret field from the AuthState. Returns an empty string if the field is nil.

func (*AuthState) GetTOTPSecretOk

func (a *AuthState) GetTOTPSecretOk() (string, bool)

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) GetTolerationPolicyFact

func (a *AuthState) GetTolerationPolicyFact() tolerate.PolicyFact

GetTolerationPolicyFact returns the last collected toleration policy fact.

func (*AuthState) GetUniqueUserID

func (a *AuthState) GetUniqueUserID() string

GetUniqueUserID returns the unique WebAuthn user identifier for a user. If there is no id, it returns the empty string "".

func (*AuthState) GetUniqueUserIDField

func (a *AuthState) GetUniqueUserIDField() string

GetUniqueUserIDField retrieves the value of the UniqueUserIDField if set; returns an empty string otherwise.

func (*AuthState) GetUniqueUserIDOk

func (a *AuthState) GetUniqueUserIDOk() (string, bool)

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

func (a *AuthState) GetUsedCacheBackend() (definitions.CacheNameBackend, error)

GetUsedCacheBackend returns the cache name backend based on the used password database backend.

func (*AuthState) GetUsedPassDBBackend

func (a *AuthState) GetUsedPassDBBackend() definitions.Backend

GetUsedPassDBBackend returns the currently used backend for password database operations.

func (*AuthState) GetUsedPassDBBackendName

func (a *AuthState) GetUsedPassDBBackendName() string

GetUsedPassDBBackendName returns the name of the currently used backend for password database operations.

func (*AuthState) GetUsername

func (a *AuthState) GetUsername() string

GetUsername retrieves the username from the AuthState structure.

func (*AuthState) GetWebAuthnCredentials

func (a *AuthState) GetWebAuthnCredentials() (credentials []mfa.PersistentCredential, err error)

GetWebAuthnCredentials retrieves WebAuthn credentials for the user in the backend.

func (*AuthState) GetWebAuthnCredentialsFromSelectedBackend

func (a *AuthState) GetWebAuthnCredentialsFromSelectedBackend() ([]mfa.PersistentCredential, error)

GetWebAuthnCredentialsFromSelectedBackend retrieves credentials only from the backend selected by authentication.

func (*AuthState) HandleEnvironment

func (a *AuthState) HandleEnvironment(ctx *gin.Context) definitions.AuthResult

HandleEnvironment processes the complete established environment provider sequence.

func (*AuthState) HasOIDCScope

func (a *AuthState) HasOIDCScope(ctx *gin.Context, scope string) bool

HasOIDCScope checks if the current request's OIDC Bearer token contains the specified scope. Returns false if no OIDC claims are present in the context.

func (*AuthState) HaveMonitoringFlag

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

func (a *AuthState) InitMethodAndUserAgent() State

InitMethodAndUserAgent initializes the authentication method and user agent fields if they are not already set.

func (*AuthState) IsBackendHealthCheckRequest

func (a *AuthState) IsBackendHealthCheckRequest() bool

IsBackendHealthCheckRequest reports whether the current authentication request matches a configured health-check identity.

func (*AuthState) IsIPAddressBlocked

func (a *AuthState) IsIPAddressBlocked() (buckets []string, found bool)

IsIPAddressBlocked checks if the current client IP address is blocked by any brute force rules.

func (*AuthState) IsInNetwork

func (a *AuthState) IsInNetwork(networkList []string) (matchIP bool)

IsInNetwork checks an IP address against a network and returns true if it matches.

func (*AuthState) IsMasterUser

func (a *AuthState) IsMasterUser() bool

IsMasterUser checks whether the current user matches the configured master-user login format. It returns true only when master-user mode is enabled and the configured format can be parsed unambiguously.

func (*AuthState) ListUserAccounts

func (a *AuthState) ListUserAccounts() (accountList AccountList)

ListUserAccounts returns the list of all known users from the account databases.

func (*AuthState) LoadAllPasswordHistories

func (a *AuthState) LoadAllPasswordHistories()

LoadAllPasswordHistories loads all password histories for the current AuthState.

func (*AuthState) LogLineProcessingTemplate

func (a *AuthState) LogLineProcessingTemplate(endpoint string) []any

LogLineProcessingTemplate generates and returns a list of key-value pairs for logging session-related details.

func (*AuthState) LogLineTemplate

func (a *AuthState) LogLineTemplate(status string, endpoint string) []any

LogLineTemplate constructs a key-value slice for logging authentication state and related metadata.

func (*AuthState) Logger

func (a *AuthState) Logger() *slog.Logger

Logger provides the exported Logger method.

func (*AuthState) PasswordBytes

func (a *AuthState) PasswordBytes() []byte

PasswordBytes materializes the password as a short-lived byte slice.

func (*AuthState) PasswordString

func (a *AuthState) PasswordString() string

PasswordString materializes the password as a short-lived string.

func (*AuthState) PolicyDecisionContext

func (a *AuthState) PolicyDecisionContext(ctx *gin.Context) *policycollection.DecisionContext

PolicyDecisionContext returns the request-local policy collection context.

func (*AuthState) PolicyScriptRecorder

func (a *AuthState) PolicyScriptRecorder(ctx *gin.Context) policycollection.ScriptRecorder

PolicyScriptRecorder returns the request-local Lua script result sink.

func (*AuthState) PrepareNetcalc

func (a *AuthState) PrepareNetcalc(rules []config.BruteForceRule)

PrepareNetcalc pre-calculates network CIDRs for brute force rules.

func (*AuthState) PreproccessAuthRequest

func (a *AuthState) PreproccessAuthRequest(ctx *gin.Context) (reject bool)

PreproccessAuthRequest runs request-local brute-force controls before environment and backend authentication. If a brute-force attack is rejected, it returns true. Configured policy controls may let processing continue.

func (*AuthState) ProcessBruteForce

func (a *AuthState) ProcessBruteForce(ruleTriggered, alreadyTriggered bool, rule *config.BruteForceRule, network *net.IPNet, message string, setter func()) bool

ProcessBruteForce evaluates and handles a brute force trigger based on the given rule and network.

func (*AuthState) ProcessPWHist

func (a *AuthState) ProcessPWHist() (accountName string)

ProcessPWHist processes the password history and updates the account name if necessary.

func (*AuthState) PurgeCache

func (a *AuthState) PurgeCache()

PurgeCache invalidates the user authentication cache.

func (*AuthState) PurgeCacheFor

func (a *AuthState) PurgeCacheFor(username string)

PurgeCacheFor invalidates the user authentication cache for a specific username.

func (*AuthState) RangeAttributes

func (a *AuthState) RangeAttributes(fn func(string, []any) bool)

RangeAttributes iterates over all attributes under a read lock and calls fn for each key/value. If fn returns false, iteration stops early.

func (*AuthState) Redis

func (a *AuthState) Redis() rediscli.Client

Redis provides the exported Redis method.

func (*AuthState) ReplaceAllAttributes

func (a *AuthState) ReplaceAllAttributes(m bktype.AttributeMapping)

ReplaceAllAttributes replaces the entire Attributes map with a deep copy of the provided map, under write lock. Passing nil will set Attributes to nil.

func (*AuthState) ResetLoginAttemptsOnSuccess

func (a *AuthState) ResetLoginAttemptsOnSuccess()

ResetLoginAttemptsOnSuccess resets the internal fail counter after a successful authentication. This affects only the in-process view; any persistent brute-force storage remains managed by the brute-force subsystem.

func (*AuthState) SFKeyHash

func (a *AuthState) SFKeyHash() string

SFKeyHash returns the digest for the legacy strict singleflight key.

func (*AuthState) SaveBruteForceBucketCounterToRedis

func (a *AuthState) SaveBruteForceBucketCounterToRedis(rule *config.BruteForceRule)

SaveBruteForceBucketCounterToRedis persists the brute force bucket counter to Redis.

func (*AuthState) SaveFailedPasswordCounterInRedis

func (a *AuthState) SaveFailedPasswordCounterInRedis()

SaveFailedPasswordCounterInRedis updates the failed password counter in Redis.

func (*AuthState) SaveWebAuthnCredential

func (a *AuthState) SaveWebAuthnCredential(credential *mfa.PersistentCredential) (err error)

SaveWebAuthnCredential saves a WebAuthn credential for the user in the backend.

func (*AuthState) SaveWebAuthnCredentialToSelectedBackend

func (a *AuthState) SaveWebAuthnCredentialToSelectedBackend(credential *mfa.PersistentCredential) error

SaveWebAuthnCredentialToSelectedBackend saves a credential only to the backend selected by authentication.

func (*AuthState) SetAccount

func (a *AuthState) SetAccount(account string)

SetAccount sets the account for the AuthState instance.

func (*AuthState) SetAttributeIfAbsent

func (a *AuthState) SetAttributeIfAbsent(name string, value any)

SetAttributeIfAbsent sets the attribute to a single-value slice if it does not exist yet. This mirrors typical usage where scripts want to add an attribute only when missing. It allocates the Attributes map lazily and is concurrency-safe.

func (*AuthState) SetAttributeValues

func (a *AuthState) SetAttributeValues(name string, values []any)

SetAttributeValues replaces one attribute with a defensive copy of values.

func (*AuthState) SetClientHost

func (a *AuthState) SetClientHost(clientHost string)

SetClientHost sets the client host value in the AuthState instance.

func (*AuthState) SetClientID

func (a *AuthState) SetClientID(clientID string)

SetClientID sets the client ID for the authentication state using the provided clientID string.

func (*AuthState) SetClientIP

func (a *AuthState) SetClientIP(clientIP string)

SetClientIP sets the client's IP address in the AuthState structure.

func (*AuthState) SetClientPort

func (a *AuthState) SetClientPort(clientPort string)

SetClientPort sets the client's port information to the provided clientPort value.

func (*AuthState) SetLocalIP

func (a *AuthState) SetLocalIP(localIP string)

SetLocalIP sets the local IP address for the AuthState instance.

func (*AuthState) SetLocalPort

func (a *AuthState) SetLocalPort(port string)

SetLocalPort sets the local port for the AuthState instance to the given port string.

func (*AuthState) SetLoginAttempts

func (a *AuthState) SetLoginAttempts(loginAttempts uint)

SetLoginAttempts sets the number of login attempts for the AuthState instance.

func (*AuthState) SetMethod

func (a *AuthState) SetMethod(method string)

SetMethod sets the authentication method for the AuthState instance by assigning it to the Method field.

func (*AuthState) SetNoAuth

func (a *AuthState) SetNoAuth(noAuth bool)

SetNoAuth configures the authentication state to enable or disable "NoAuth" mode based on the provided boolean value.

func (*AuthState) SetOIDCCID

func (a *AuthState) SetOIDCCID(oidcCID string)

SetOIDCCID sets the OIDC Client ID for the AuthState instance. It updates the OIDCCID field with the provided value.

func (*AuthState) SetOperationMode

func (a *AuthState) SetOperationMode(ctx *gin.Context)

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

func (a *AuthState) SetPassword(password secret.Value)

SetPassword sets the password for the AuthState instance.

func (*AuthState) SetProtocol

func (a *AuthState) SetProtocol(protocol *config.Protocol)

SetProtocol sets the protocol for the AuthState using the given Protocol configuration.

func (*AuthState) SetResolvedGroups

func (a *AuthState) SetResolvedGroups(groups []string, groupDistinguishedNames []string)

SetResolvedGroups replaces the resolved group names and group DNs.

func (*AuthState) SetSAMLEntityID

func (a *AuthState) SetSAMLEntityID(samlEntityID string)

SetSAMLEntityID sets the SAML Entity ID for the AuthState instance. It updates the SAMLEntityID field with the provided value.

func (*AuthState) SetSSL

func (a *AuthState) SetSSL(ssl string)

SetSSL sets the XSSL property of the AuthState to the provided SSL value.

func (*AuthState) SetSSLCipher

func (a *AuthState) SetSSLCipher(sslCipher string)

SetSSLCipher sets the SSL cipher suite for the current authentication state.

func (*AuthState) SetSSLClientCN

func (a *AuthState) SetSSLClientCN(sslClientCN string)

SetSSLClientCN sets the value of the SSL client common name (CN) for the AuthState instance.

func (*AuthState) SetSSLClientDN

func (a *AuthState) SetSSLClientDN(sslClientDN string)

SetSSLClientDN sets the distinguished name (DN) of the SSL client in the AuthState struct.

func (*AuthState) SetSSLClientIssuerDN

func (a *AuthState) SetSSLClientIssuerDN(sslClientIssuerDN string)

SetSSLClientIssuerDN sets the SSL client issuer distinguished name for the authentication state.

func (*AuthState) SetSSLClientNotAfter

func (a *AuthState) SetSSLClientNotAfter(sslClientNotAfter string)

SetSSLClientNotAfter sets the XSSLClientNotAfter field with the provided SSL client expiration date.

func (*AuthState) SetSSLClientNotBefore

func (a *AuthState) SetSSLClientNotBefore(sslClientNotBefore string)

SetSSLClientNotBefore sets the SSL client certificate's "Not Before" value in the AuthState.

func (*AuthState) SetSSLClientSubjectDN

func (a *AuthState) SetSSLClientSubjectDN(sslClientSubjectDN string)

SetSSLClientSubjectDN sets the subject distinguished name (DN) for the SSL client in the AuthState object.

func (*AuthState) SetSSLClientVerify

func (a *AuthState) SetSSLClientVerify(sslClientVerify string)

SetSSLClientVerify sets the SSL client verification value for the AuthState.

func (*AuthState) SetSSLFingerprint

func (a *AuthState) SetSSLFingerprint(sslFingerprint string)

SetSSLFingerprint sets the SSL fingerprint for the AuthState instance. It updates the SSLFingerprint field with the provided value.

func (*AuthState) SetSSLIssuer

func (a *AuthState) SetSSLIssuer(xSSLIssuer string)

SetSSLIssuer sets the issuer for the XSSL certificate in the AuthState.

func (*AuthState) SetSSLIssuerDN

func (a *AuthState) SetSSLIssuerDN(xSSLIssuerDN string)

SetSSLIssuerDN sets the X.509 SSL issuer distinguished name for the AuthState.

func (*AuthState) SetSSLProtocol

func (a *AuthState) SetSSLProtocol(sslProtocol string)

SetSSLProtocol sets the SSL protocol version to be used for the connection by updating the XSSLProtocol field.

func (*AuthState) SetSSLSerial

func (a *AuthState) SetSSLSerial(sslSerial string)

SetSSLSerial sets the SSL serial number for the AuthState instance.

func (*AuthState) SetSSLSessionID

func (a *AuthState) SetSSLSessionID(sslSessionID string)

SetSSLSessionID sets the SSL session ID for the AuthState instance.

func (*AuthState) SetSSLSubjectDN

func (a *AuthState) SetSSLSubjectDN(sslSubjectDN string)

SetSSLSubjectDN sets the SSL subject distinguished name to the provided string value.

func (*AuthState) SetStatusCodes

func (a *AuthState) SetStatusCodes(service string)

SetStatusCodes sets different status codes for various services.

func (*AuthState) SetTOTPRecoveryField

func (a *AuthState) SetTOTPRecoveryField(totpRecoveryField string)

SetTOTPRecoveryField sets the TOTP recovery field for the AuthState object.

func (*AuthState) SetTOTPSecret

func (a *AuthState) SetTOTPSecret(totpSecret string)

SetTOTPSecret sets the TOTP secret for the AuthState instance.

func (*AuthState) SetTOTPSecretField

func (a *AuthState) SetTOTPSecretField(totpSecretField string)

SetTOTPSecretField sets the TOTP secret field for the AuthState object.

func (*AuthState) SetUserAgent

func (a *AuthState) SetUserAgent(userAgent string)

SetUserAgent sets the UserAgent field for the AuthState with the provided userAgent value.

func (*AuthState) SetUsername

func (a *AuthState) SetUsername(username string)

SetUsername sets the username for the AuthState instance to the given value.

func (*AuthState) ShouldEnforceBucketUpdate

func (a *AuthState) ShouldEnforceBucketUpdate() (bool, error)

ShouldEnforceBucketUpdate determines whether brute force bucket counters should be increased.

func (*AuthState) String

func (a *AuthState) String() string

String returns a human-readable representation of the AuthState. The GUID is omitted and the password is hidden unless dev mode is active.

func (*AuthState) SyncLoginAttemptsFromAttemptOrdinal

func (a *AuthState) SyncLoginAttemptsFromAttemptOrdinal(ordinal uint)

SyncLoginAttemptsFromAttemptOrdinal updates the internal login attempt manager from a 1-based attempt ordinal and mirrors the normalized fail count.

func (*AuthState) SyncLoginAttemptsFromBucket

func (a *AuthState) SyncLoginAttemptsFromBucket(counter uint)

SyncLoginAttemptsFromBucket updates the internal login attempt manager from a brute-force bucket value and mirrors the FailCount to the legacy field. The bucket is considered authoritative over header hints.

func (*AuthState) SyncLoginAttemptsFromHeader

func (a *AuthState) SyncLoginAttemptsFromHeader(headerValue string)

SyncLoginAttemptsFromHeader updates the internal login attempt manager from a header value containing a 1-based attempt ordinal.

func (*AuthState) Tolerate

func (a *AuthState) Tolerate() tolerate.Tolerate

Tolerate returns the request-owned brute-force tolerance authority.

func (*AuthState) UpdateBruteForceBucketsCounter

func (a *AuthState) UpdateBruteForceBucketsCounter(ctx *gin.Context)

UpdateBruteForceBucketsCounter updates brute force protection rules based on client and protocol details.

func (*AuthState) UpdateWebAuthnCredential

func (a *AuthState) UpdateWebAuthnCredential(oldCredential *mfa.PersistentCredential, newCredential *mfa.PersistentCredential) (err error)

UpdateWebAuthnCredential updates an existing WebAuthn credential in the backend.

func (*AuthState) UpdateWebAuthnCredentialInSelectedBackend

func (a *AuthState) UpdateWebAuthnCredentialInSelectedBackend(
	oldCredential *mfa.PersistentCredential,
	newCredential *mfa.PersistentCredential,
) error

UpdateWebAuthnCredentialInSelectedBackend updates a credential only in the backend selected by authentication.

func (*AuthState) View

func (a *AuthState) View() *StateView

View creates a read-only view for the current auth state.

func (*AuthState) WithAccountName

func (a *AuthState) WithAccountName(accountName string) bruteforce.BucketManager

WithAccountName sets the account name in the AuthState.

func (*AuthState) WithClientInfo

func (a *AuthState) WithClientInfo(ctx *gin.Context) State

WithClientInfo adds the client IP, -port and -ID headers to the AuthState structure.

func (*AuthState) WithDefaults

func (a *AuthState) WithDefaults(ctx *gin.Context) State

WithDefaults sets default values for the AuthState structure including the GUID session value.

func (*AuthState) WithLocalInfo

func (a *AuthState) WithLocalInfo(ctx *gin.Context) State

WithLocalInfo adds the local IP and -port headers to the AuthState structure.

func (*AuthState) WithOIDCCID

func (a *AuthState) WithOIDCCID(oidcCID string) bruteforce.BucketManager

WithOIDCCID sets the OIDC Client ID in the AuthState.

func (*AuthState) WithPassword

func (a *AuthState) WithPassword(password secret.Value) bruteforce.BucketManager

WithPassword sets the password in the AuthState.

func (*AuthState) WithProtocol

func (a *AuthState) WithProtocol(protocol string) bruteforce.BucketManager

WithProtocol sets the protocol in the AuthState.

func (*AuthState) WithRWPDecision

func (a *AuthState) WithRWPDecision(enforce bool) bruteforce.BucketManager

WithRWPDecision sets the cached RWP enforcement decision (true=enforce, false=RWP active).

func (*AuthState) WithUserAgent

func (a *AuthState) WithUserAgent(ctx *gin.Context) State

WithUserAgent adds the User-Agent header to the AuthState structure.

func (*AuthState) WithUsername

func (a *AuthState) WithUsername(username string) bruteforce.BucketManager

WithUsername sets the username in the AuthState.

func (*AuthState) WithXSSL

func (a *AuthState) WithXSSL(ctx *gin.Context) State

WithXSSL adds HAProxy header processing to the AuthState structure.

type AuthTransportContext

type AuthTransportContext struct {
	Kind         string
	Listener     string
	HTTPMethod   string
	HTTPRoute    string
	GRPCMethod   string
	Peer         string
	MTLSIdentity string
	Protected    bool
}

AuthTransportContext carries server-observed transport metadata without a Gin dependency.

type AuthnEntryCallerProfiles

type AuthnEntryCallerProfiles struct {
	// Authenticate is the opaque internal caller evidence for password authentication.
	Authenticate decision.AuthenticationInput
	// LookupIdentity is the opaque internal caller evidence for identity lookup.
	LookupIdentity decision.AuthenticationInput
	// EntryPoint is selected exclusively by the trusted host adapter.
	EntryPoint AuthnEntryPoint
}

AuthnEntryCallerProfiles binds host-created authenticate and lookup evidence to one entry path.

type AuthnEntryPoint

type AuthnEntryPoint uint8

AuthnEntryPoint identifies one host-owned authentication entry path.

Transport adapters must select this value from trusted routing and flow state. Request routes, scopes, client identifiers, and other user input never select it.

const (
	// AuthnEntryDefault preserves the operation-specific profile used by existing callers.
	AuthnEntryDefault AuthnEntryPoint = iota
	// AuthnEntryBackchannel explicitly selects the existing backchannel operation profile.
	AuthnEntryBackchannel
	// AuthnEntryIDPInternal selects protocol-unbound internal and self-service IdP paths.
	AuthnEntryIDPInternal
	// AuthnEntryIDPOIDCAuthorizationCode selects OIDC authorization-code IdP paths.
	AuthnEntryIDPOIDCAuthorizationCode
	// AuthnEntryIDPOIDCDeviceCode selects OIDC device-code IdP paths.
	AuthnEntryIDPOIDCDeviceCode
	// AuthnEntryIDPSAML selects SAML IdP paths.
	AuthnEntryIDPSAML
	// AuthnEntryIDPDelayedIdentity selects delayed-response identity hydration.
	AuthnEntryIDPDelayedIdentity
	// AuthnEntryIDPMasterFactor selects master-user factor identity hydration.
	AuthnEntryIDPMasterFactor
	// AuthnEntryIDPMFABackend selects specialized MFA backend identity lookup.
	AuthnEntryIDPMFABackend
)

func (AuthnEntryPoint) String

func (e AuthnEntryPoint) String() string

String returns the stable host-side name of the entry point.

type AuthnHostServices

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

AuthnHostServices owns every host implementation used by candidate authn execution.

func NewAuthnHostServices

func NewAuthnHostServices(input AuthnHostServicesInput) (AuthnHostServices, error)

NewAuthnHostServices validates and freezes one detached host implementation bundle.

func (AuthnHostServices) Valid

func (s AuthnHostServices) Valid() bool

Valid reports whether the bundle is complete and safe for request execution.

func (AuthnHostServices) WaitDelay

func (s AuthnHostServices) WaitDelay(maxWaitDelay, loginAttempt uint) int

WaitDelay calculates the response delay through the captured brute-force service.

type AuthnHostServicesInput

type AuthnHostServicesInput struct {
	PasswordVerifier PasswordVerifier
	Cache            CacheService
	BruteForce       BruteForceService
	Subject          CapturedLuaSubject
	RBL              RBLService
}

AuthnHostServicesInput supplies the immutable host implementation bundle captured by one application owner.

type AuthnInternalCallerProfiles

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

AuthnInternalCallerProfiles owns exact host-created admission presentations by authn operation.

The bundle is candidate-only and contains no production configuration authority. Its opaque credentials are detached during construction and never derived from end-user authentication material.

func NewAuthnInternalCallerProfiles

func NewAuthnInternalCallerProfiles(
	authenticate decision.AuthenticationInput,
	lookupIdentity decision.AuthenticationInput,
	listAccounts decision.AuthenticationInput,
) (AuthnInternalCallerProfiles, error)

NewAuthnInternalCallerProfiles constructs the complete candidate operation-profile bundle.

func NewAuthnInternalCallerProfilesWithEntries

func NewAuthnInternalCallerProfilesWithEntries(
	defaults AuthnInternalCallerProfiles,
	entries ...AuthnEntryCallerProfiles,
) (AuthnInternalCallerProfiles, error)

NewAuthnInternalCallerProfilesWithEntries adds exact host-owned entry presentations to generic defaults.

type AuthnNativeCapture

type AuthnNativeCapture struct {
	Runtime      pluginapi.RuntimeContext
	Credentials  pluginapi.CredentialProvider
	Snapshot     pluginapi.RequestSnapshot
	PasswordHash string
}

AuthnNativeCapture owns the public request values prepared for one exact generation binding.

type AuthnNativeCaptureInput

type AuthnNativeCaptureInput struct {
	Auth         *AuthState
	Capabilities []pluginapi.Capability
	Detached     bool
}

AuthnNativeCaptureInput selects request-owned projection without selecting a plugin component.

type AuthnNativeRuntime

type AuthnNativeRuntime interface {
	Capture(context.Context, AuthnNativeCaptureInput) (AuthnNativeCapture, error)
	ApplyRuntimeDelta(*AuthState, pluginapi.RuntimeDelta) error
}

AuthnNativeRuntime projects and applies request-owned public plugin values without component lookup.

type AuthnRequestStageFlags

type AuthnRequestStageFlags struct {
	EnvironmentRejected      bool
	EnvironmentStageExpected bool
	SubjectStageExpected     bool
}

AuthnRequestStageFlags describes request-observed authn stage availability.

type BackendAuthenticationCacheKey

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

BackendAuthenticationCacheKey is an opaque credential-bound cache key.

type BackendManager

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)

	// DeleteTOTPSecret removes the TOTP secret for the user in the backend.
	DeleteTOTPSecret(auth *AuthState) (err error)

	// AddTOTPRecoveryCodes adds the specified TOTP recovery codes to the user's authentication state in the backend.
	AddTOTPRecoveryCodes(auth *AuthState, recovery *mfa.TOTPRecovery) (err error)

	// DeleteTOTPRecoveryCodes removes all TOTP recovery codes for the user in the backend.
	DeleteTOTPRecoveryCodes(auth *AuthState) (err error)

	// GetWebAuthnCredentials retrieves WebAuthn credentials for the user in the backend.
	GetWebAuthnCredentials(auth *AuthState) (credentials []mfa.PersistentCredential, err error)

	// SaveWebAuthnCredential saves a WebAuthn credential for the user in the backend.
	SaveWebAuthnCredential(auth *AuthState, credential *mfa.PersistentCredential) (err error)

	// DeleteWebAuthnCredential removes a WebAuthn credential for the user in the backend.
	DeleteWebAuthnCredential(auth *AuthState, credential *mfa.PersistentCredential) (err error)

	// UpdateWebAuthnCredential updates an existing WebAuthn credential in the backend.
	UpdateWebAuthnCredential(auth *AuthState, oldCredential *mfa.PersistentCredential, newCredential *mfa.PersistentCredential) (err error)
}

BackendManager defines an interface for managing authentication backends with methods for user authentication and account handling.

func NewLDAPManager

func NewLDAPManager(poolName string, deps AuthDeps) BackendManager

NewLDAPManager creates and returns a BackendManager for managing LDAP authentication backends using the specified pool name.

func NewLuaManager

func NewLuaManager(backendName string, deps AuthDeps) BackendManager

NewLuaManager initializes and returns a new LuaManager instance with the specified backend name.

func NewTestBackendManager

func NewTestBackendManager(backendName string, deps AuthDeps) BackendManager

NewTestBackendManager constructs a BackendManager backed by an in-memory store.

type BackendManagerFactory

type BackendManagerFactory func(backendName string, deps AuthDeps) BackendManager

BackendManagerFactory constructs a backend manager for a backend plugged in from another package.

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

GetTotalServers provides the exported GetTotalServers method.

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

type Bootstrap interface {
	// InitWebAuthn initializes the global WebAuthn configuration from environment/config.
	// Returns an error if the configuration is invalid.
	InitWebAuthn() error
	// InitGinLogging wires Gin log writers and sets Gin mode based on configuration.
	InitGinLogging()
}

Bootstrap initializes cross-cutting HTTP dependencies such as WebAuthn and Gin logging, before the router is built.

type BruteForceService

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. Production injects one implementation through the immutable AuthnHostServices bundle.

type CacheService

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)

	// Purge removes all cached entries for the specified username.
	Purge(auth *AuthState, username string)
}

CacheService abstracts positive/negative cache behavior.

type CachedBackendAuthentication

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

CachedBackendAuthentication is an owned positive backend and identity snapshot.

type CaptureResponseWriter

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

CaptureResponseWriter captures auth terminal outcomes without rendering HTTP.

func NewCaptureResponseWriter

func NewCaptureResponseWriter(logger *slog.Logger) *CaptureResponseWriter

NewCaptureResponseWriter creates a request-scoped outcome collector.

func NewDefaultCaptureResponseWriter

func NewDefaultCaptureResponseWriter(deps ResponseDeps) *CaptureResponseWriter

NewDefaultCaptureResponseWriter creates a capture writer based on DI response dependencies.

func (*CaptureResponseWriter) Fail

func (w *CaptureResponseWriter) Fail(ctx *gin.Context, view *StateView)

Fail applies failure side effects and captures the failure outcome.

func (*CaptureResponseWriter) OK

func (w *CaptureResponseWriter) OK(ctx *gin.Context, view *StateView)

OK applies success side effects and captures the success outcome.

func (*CaptureResponseWriter) Outcome

Outcome returns a copy of the last captured outcome.

func (*CaptureResponseWriter) TempFail

func (w *CaptureResponseWriter) TempFail(ctx *gin.Context, view *StateView, reason string)

TempFail applies temporary-failure side effects and captures the temporary failure outcome.

type CapturedAuthDecision

type CapturedAuthDecision string

CapturedAuthDecision is the terminal auth decision captured from the response layer.

const (
	// CapturedAuthDecisionUnset indicates that no terminal decision was captured yet.
	CapturedAuthDecisionUnset CapturedAuthDecision = "unset"
	// CapturedAuthDecisionOK indicates successful authentication.
	CapturedAuthDecisionOK CapturedAuthDecision = "ok"
	// CapturedAuthDecisionFail indicates a terminal authentication failure.
	CapturedAuthDecisionFail CapturedAuthDecision = "fail"
	// CapturedAuthDecisionTempFail indicates a temporary terminal failure.
	CapturedAuthDecisionTempFail CapturedAuthDecision = "tempfail"
)

type CapturedAuthOutcome

type CapturedAuthOutcome = authOutcomeProjection[CapturedAuthDecision]

CapturedAuthOutcome stores the transport-neutral terminal auth outcome.

type CapturedLuaSubject

type CapturedLuaSubject interface {
	AnalyzeSource(
		ctx *gin.Context,
		view *StateView,
		result *PassDBResult,
		name string,
		prototype *lua.FunctionProto,
		pools *vmpool.Manager,
		poolKey vmpool.PoolKey,
		modules *luaseal.Modules,
	) definitions.AuthResult
}

CapturedLuaSubject executes one generation-owned precompiled subject source.

type ClaimManager

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

ClaimManager maps backend attributes to OIDC claims with scope/type handling.

func NewClaimManager

func NewClaimManager(auth *AuthState, requestedScopes []string, customScopes []config.Oauth2CustomScope) *ClaimManager

NewClaimManager constructs a ClaimManager for the given AuthState and scopes.

func (*ClaimManager) ApplyAccessTokenMappings

func (m *ClaimManager) ApplyAccessTokenMappings(mappings []config.OIDCClaimMapping, claims map[string]any)

ApplyAccessTokenMappings applies access-token mappings without reserved token claims.

func (*ClaimManager) ApplyIDTokenMappings

func (m *ClaimManager) ApplyIDTokenMappings(mappings []config.OIDCClaimMapping, claims map[string]any)

ApplyIDTokenMappings applies ID-token mappings without issuer-owned token claims.

func (*ClaimManager) ApplyMappings

func (m *ClaimManager) ApplyMappings(mappings []config.OIDCClaimMapping, claims map[string]any)

ApplyMappings applies configured claim mappings to the provided claims map.

type CompositeAuthCacheInvalidator

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

CompositeAuthCacheInvalidator explicitly coordinates the two separated auth caches.

func NewCompositeAuthCacheInvalidator

func NewCompositeAuthCacheInvalidator(backendAuthentications *PositiveBackendAuthenticationCache, userAuth *localcache.UserAuthCache) *CompositeAuthCacheInvalidator

NewCompositeAuthCacheInvalidator creates a local cache invalidator.

func (*CompositeAuthCacheInvalidator) InvalidateIdentities

func (c *CompositeAuthCacheInvalidator) InvalidateIdentities(identities ...string) int

InvalidateIdentities removes all backend-authentication variants and priority hints.

type CredentialOption

type CredentialOption func(*Credentials)

CredentialOption mutates a Credentials value during construction.

func WithPassword

func WithPassword(p secret.Value) CredentialOption

WithPassword sets the password field.

func WithUsername

func WithUsername(u string) CredentialOption

WithUsername sets the username field.

type Credentials

type Credentials struct {
	Username     string
	Password     secret.Value
	TOTP         string
	TOTPRecovery string
}

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

func NewCredentials(opts ...CredentialOption) Credentials

NewCredentials constructs a Credentials value using the provided options.

type DefaultBootstrap

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

DefaultBootstrap wires the existing bootstrapping functions.

func NewDefaultBootstrap

func NewDefaultBootstrap(deps HTTPDeps) DefaultBootstrap

NewDefaultBootstrap provides the exported NewDefaultBootstrap function.

func (DefaultBootstrap) InitGinLogging

func (b 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) InitWebAuthn

func (b DefaultBootstrap) InitWebAuthn() error

InitWebAuthn initializes the global WebAuthn configuration using values from the environment/config. The legacy behavior (logging on error) is preserved.

type DefaultHTTPApp

type DefaultHTTPApp struct {
	Bootstrap         Bootstrap
	RouterComposer    RouterComposer
	HTTPServerFactory HTTPServerFactory
	ProxyProvider     ProxyListenerProvider
	TLSConfigurator   TLSConfigurator
	TransportRunner   TransportRunner
	// contains filtered or unexported fields
}

DefaultHTTPApp orchestrates all components and preserves exact behavior.

func NewDefaultHTTPApp

func NewDefaultHTTPApp(deps HTTPDeps) *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

func (a *DefaultHTTPApp) Start(ctx context.Context,
	setupHealth func(*gin.Engine),
	setupMetrics func(*gin.Engine),
	setupIDP 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

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

DefaultHTTPServerFactory builds http.Server and configures HTTP/2 settings.

func NewDefaultHTTPServerFactory

func NewDefaultHTTPServerFactory(deps HTTPDeps) DefaultHTTPServerFactory

NewDefaultHTTPServerFactory provides the exported NewDefaultHTTPServerFactory function.

func (DefaultHTTPServerFactory) New

func (f DefaultHTTPServerFactory) New(router *gin.Engine) *http.Server

New constructs a configured *http.Server* with HTTP/2 enabled and sensible timeouts. Idle timeout honors the configured keep-alive settings.

type DefaultRouterComposer

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

DefaultRouterComposer builds the gin.Engine and registers routes/middlewares in the exact order.

func NewDefaultRouterComposer

func NewDefaultRouterComposer(deps HTTPDeps) DefaultRouterComposer

NewDefaultRouterComposer provides the exported NewDefaultRouterComposer function.

func (DefaultRouterComposer) ApplyCoreMiddlewares

func (c 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

func (c 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

func (c DefaultRouterComposer) ComposeEngine() *gin.Engine

ComposeEngine creates a fresh gin.Engine without any default middleware. This mirrors the legacy code which constructed the engine explicitly and enables ContextWithFallback so gin.Context behaves consistently as a context.Context with respect to Deadline/Done/Err/Value fallbacks.

func (DefaultRouterComposer) RegisterRoutes

func (c DefaultRouterComposer) RegisterRoutes(r *gin.Engine,
	setupHealth func(*gin.Engine),
	setupMetrics func(*gin.Engine),
	setupIDP func(*gin.Engine),
	setupBackchannel func(*gin.Engine),
)

RegisterRoutes wires health and metrics routes, then (if enabled) the frontend routes (IDP) and finally the backchannel routes. The order is kept to preserve exact behavior of the legacy implementation.

type DefaultServerSignals

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

DefaultServerSignals provides default channels for HTTP and HTTP/3 lifecycle notifications.

func NewDefaultServerSignals

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

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

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

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

DefaultTLSConfigurator constructs tls.Config according to settings.

func NewDefaultTLSConfigurator

func NewDefaultTLSConfigurator(deps HTTPDeps) DefaultTLSConfigurator

NewDefaultTLSConfigurator provides the exported NewDefaultTLSConfigurator function.

func (DefaultTLSConfigurator) Build

func (c 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

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

DefaultTransportRunner starts HTTP/1.1+2 and optional HTTP/3, with graceful shutdown.

func NewDefaultTransportRunner

func NewDefaultTransportRunner(deps HTTPDeps) DefaultTransportRunner

NewDefaultTransportRunner provides the exported NewDefaultTransportRunner function.

func (DefaultTransportRunner) Serve

func (r DefaultTransportRunner) Serve(ctx context.Context, srv *http.Server, 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 Done

type Done struct{}

Done is the value for channels to finish workers

type FieldMapping

type FieldMapping struct {
	Account     string
	TOTPSecret  string
	UniqueID    string
	DisplayName string
}

FieldMapping groups configurable field names to reduce scattered getters. Currently unused to avoid behavior changes; reserved for next steps.

type FrontendAsset

type FrontendAsset struct {
	RelativePath string
	Content      []byte
}

FrontendAsset is one detached immutable public file under the frontend asset root.

type HAProxyListenerProvider

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

HAProxyListenerProvider provides PROXY v2 listener when enabled.

func NewHAProxyListenerProvider

func NewHAProxyListenerProvider(deps HTTPDeps) HAProxyListenerProvider

NewHAProxyListenerProvider provides the exported NewHAProxyListenerProvider function.

func (HAProxyListenerProvider) Get

Get returns a PROXY v2 aware listener if the support is enabled in the configuration, otherwise it returns nil.

type HTTPApplication

type HTTPApplication interface {
	Start(ctx context.Context,
		setupHealth func(*gin.Engine),
		setupMetrics func(*gin.Engine),
		setupIDP 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 HTTPAuthResponseRenderer

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

HTTPAuthResponseRenderer projects transport-neutral application outcomes onto established HTTP surfaces.

func NewHTTPAuthResponseRenderer

func NewHTTPAuthResponseRenderer(deps ResponseDeps) *HTTPAuthResponseRenderer

NewHTTPAuthResponseRenderer constructs the shared HTTP response adapter.

func (*HTTPAuthResponseRenderer) RenderAuth

func (r *HTTPAuthResponseRenderer) RenderAuth(ctx *gin.Context, input AuthInput, outcome *AuthOutcome)

RenderAuth writes one terminal authentication outcome without replaying domain side effects.

func (*HTTPAuthResponseRenderer) RenderListAccounts

func (r *HTTPAuthResponseRenderer) RenderListAccounts(
	ctx *gin.Context,
	input AuthInput,
	outcome *ListAccountsOutcome,
)

RenderListAccounts writes the established negotiated account-provider surface.

type HTTPDeps

type HTTPDeps struct {
	Cfg            config.File
	Logger         *slog.Logger
	Env            config.Environment
	Redis          rediscli.Client
	AccountCache   *accountcache.Manager
	RouteArtifacts *RouteArtifacts
}

HTTPDeps describes the exported HTTPDeps type.

type HTTPServerFactory

type HTTPServerFactory interface {
	New(*gin.Engine) *http.Server
}

HTTPServerFactory creates a configured http.Server (incl. HTTP/2 settings).

type IDPMFAProtocolContext

type IDPMFAProtocolContext struct {
	Protocol     string
	OIDCClientID string
	SAMLEntityID string
	Request      IDPRequestContext
}

IDPMFAProtocolContext binds MFA audit telemetry to typed protocol state.

type IDPRequestContext

type IDPRequestContext struct {
	GrantType       string
	RedirectURI     string
	RequestedScopes []string
	MFACompleted    bool
	MFAMethod       string
}

IDPRequestContext is the bounded protocol projection used by policy/Lua requests without browser-state reads.

type IdentityAttributeRequest

type IdentityAttributeRequest struct {
	Names                          []string
	IncludeStandardIdentity        bool
	IncludeGroups                  bool
	IncludeGroupDistinguishedNames bool
	ReportMissing                  bool
}

IdentityAttributeRequest describes backend identity data needed by edge-side claim materialization.

func NewOIDCIdentityAttributeRequest

func NewOIDCIdentityAttributeRequest(
	client *config.OIDCClient,
	requestedScopes []string,
	customScopes []config.Oauth2CustomScope,
) *IdentityAttributeRequest

NewOIDCIdentityAttributeRequest derives backend attributes from OIDC claim mappings and granted scopes.

func NewSAMLIdentityAttributeRequest

func NewSAMLIdentityAttributeRequest(sp *config.SAML2ServiceProvider) *IdentityAttributeRequest

NewSAMLIdentityAttributeRequest derives backend attributes from SAML SP attribute configuration.

func (*IdentityAttributeRequest) Clone

Clone returns a detached copy of the request.

type JSONErrorMsg

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 LDAPAuthRequestQueue

type LDAPAuthRequestQueue interface {
	Push(request *bktype.LDAPAuthRequest, priority int)
}

LDAPAuthRequestQueue describes the exported LDAPAuthRequestQueue type.

type LDAPRequestQueue

type LDAPRequestQueue interface {
	Push(request *bktype.LDAPRequest, priority int)
}

LDAPRequestQueue describes the exported LDAPRequestQueue type.

type ListAccountsOutcome

type ListAccountsOutcome struct {
	ResponseHeaders         http.Header
	MessageResolver         localization.MessageResolver
	ResponseHeaderDeletes   []string
	FSMEventPath            []string
	Accounts                AccountList
	ResponseSettings        AuthResponseSettings
	Decision                AuthDecision
	TerminalState           string
	Session                 string
	StatusMessage           string
	StatusMessageI18NKey    string
	ResponseLanguage        string
	Error                   string
	Protocol                string
	HTTPStatus              int
	LoginAttempts           uint
	MemoryCacheHit          bool
	DelayedResponseEligible bool
}

ListAccountsOutcome contains the account-provider response.

type LoginAttemptManager

type LoginAttemptManager interface {
	InitFromHeader(headerVal string)
	InitFromAttemptOrdinal(ordinal uint)
	InitFromBucket(counter uint)
	OnAuthFailure()
	OnAuthSuccess()
	FailCount() uint
	AttemptOrdinal() uint
	Remaining() uint
	ShouldBlock() bool
}

LoginAttemptManager defines a small object that centralizes initialization and mutation of login attempt counters from different sources (headers, brute-force buckets).

Invariant: failCount counts failed authentications (0 before first failure, 1 after first failure, ...). Header values are interpreted as attempt ordinals (1-based) and normalized to failCount = max(0, ordinal-1).

type Metric

type Metric struct {
	Value float64 `redis:"value"`
	Label string  `redis:"label"`
}

Metric is a prometheus metric with a value and a label.

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 describes the exported PassDBOption type. PassDBOption This type specifies the signature of a password database.

type PassDBResult

type PassDBResult struct {
	// 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

	// Account is the actual account name of the user.
	Account 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

	// BackendRef binds this result to an authority-side backend without exposing credentials.
	BackendRef RemoteBackendRef

	// Attributes is the result catalog returned by the underlying password Database.
	Attributes bktype.AttributeMapping

	// Groups contains resolved group names.
	Groups []string

	// GroupDistinguishedNames contains resolved group distinguished names.
	GroupDistinguishedNames []string

	// AdditionalAttributes contains additional backend attributes
	AdditionalAttributes map[string]any

	// 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

	// Backend is set by the Database backend, which has found the user.
	Backend definitions.Backend
}

PassDBResult is used in all password databases to store final results of an authentication process.

func CachePassDB

func CachePassDB(auth *AuthState) (passDBResult *PassDBResult, err error)

CachePassDB implements the redis password database backend.

func GetPassDBResultFromPool

func GetPassDBResultFromPool() *PassDBResult

GetPassDBResultFromPool retrieves a PassDBResult object from the pool If the pool is empty, a new PassDBResult object is created

func VerifyPasswordPipeline

func VerifyPasswordPipeline(ctx *gin.Context, auth *AuthState, passDBs []*PassDBMap) (*PassDBResult, error)

VerifyPasswordPipeline coordinates authentication processes across multiple password databases and backends. It iterates through the provided PassDBMap, invoking their associated functions to authenticate a user or locate credentials. Handles backend-specific configuration errors and logs failures while trying successive backends, as necessary. Returns a successful PassDBResult upon user authentication or relevant errors if all attempts fail.

func (*PassDBResult) Clone

func (p *PassDBResult) Clone() *PassDBResult

Clone creates a deep copy of the PassDBResult. It retrieves a new object from the pool and populates it.

func (*PassDBResult) IsPassDBResult

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

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 a human-readable representation of the PassDBResult.

type PasswordVerifier

type PasswordVerifier interface {
	Verify(ctx *gin.Context, a *AuthState, passDBs []*PassDBMap) (*PassDBResult, error)
}

PasswordVerifier abstracts the PassDB verification pipeline.

type PositiveBackendAuthenticationCache

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

PositiveBackendAuthenticationCache owns positive backend snapshots, expiry, and identity indexes.

func NewPositiveBackendAuthenticationCache

func NewPositiveBackendAuthenticationCache(clock func() time.Time) *PositiveBackendAuthenticationCache

NewPositiveBackendAuthenticationCache creates an isolated positive backend cache.

func (*PositiveBackendAuthenticationCache) ApplyForRequest

func (c *PositiveBackendAuthenticationCache) ApplyForRequest(ctx *gin.Context, auth *AuthState) bool

ApplyForRequest loads and installs one request-eligible backend snapshot.

func (*PositiveBackendAuthenticationCache) Clear

Clear removes all cached backend snapshots and index ownership.

func (*PositiveBackendAuthenticationCache) Close

Close clears the cache, stops its optional runner, and waits for completion.

func (*PositiveBackendAuthenticationCache) InvalidateIdentities

func (c *PositiveBackendAuthenticationCache) InvalidateIdentities(identities ...string) int

InvalidateIdentities removes all variants owned by the supplied identities.

func (*PositiveBackendAuthenticationCache) StoreForRequest

func (c *PositiveBackendAuthenticationCache) StoreForRequest(
	ctx *gin.Context,
	auth *AuthState,
	result *PassDBResult,
	ttl time.Duration,
	identities ...string,
) bool

StoreForRequest records one request-eligible positive backend result.

func (*PositiveBackendAuthenticationCache) SweepExpired

func (c *PositiveBackendAuthenticationCache) SweepExpired() int

SweepExpired atomically removes idle expired values and all index ownership.

type PostActionExecutionGate

type PostActionExecutionGate = effectsupervisor.Gate

PostActionExecutionGate is the typed internal application-response finalization gate.

func ContextWithHTTPPostActionExecutionGate

func ContextWithHTTPPostActionExecutionGate(ctx context.Context) (context.Context, *PostActionExecutionGate)

ContextWithHTTPPostActionExecutionGate installs a transport-owned HTTP commit gate.

func ContextWithPostActionExecutionGate

func ContextWithPostActionExecutionGate(ctx context.Context) (context.Context, *PostActionExecutionGate)

ContextWithPostActionExecutionGate installs a gate on a standard request context.

func InstallPostActionExecutionGate

func InstallPostActionExecutionGate(ctx *gin.Context) *PostActionExecutionGate

InstallPostActionExecutionGate attaches a fresh execution gate to a Gin request.

func NewPostActionExecutionGate

func NewPostActionExecutionGate() *PostActionExecutionGate

NewPostActionExecutionGate creates an HTTP commit execution gate.

type ProxyListenerProvider

type ProxyListenerProvider interface {
	Get() *proxyproto.Listener // nil if disabled
}

ProxyListenerProvider optionally supplies an HAProxy PROXY v2 listener.

type PublicMFAState

type PublicMFAState struct {
	WebAuthnCredentials []mfa.PersistentCredential
	RecoveryCodeCount   int
	HasTOTP             bool
	HasWebAuthn         bool
}

PublicMFAState contains public MFA metadata that is safe to expose to an IDP edge.

type PublicMFAStateProvider

type PublicMFAStateProvider interface {
	GetPublicMFAState(auth *AuthState, includeWebAuthn bool) (PublicMFAState, error)
}

PublicMFAStateProvider is implemented by backends that can read public MFA state directly.

type RBLFactService

type RBLFactService interface {
	// ScoreWithFacts computes the aggregated RBL score and returns the request-local policy facts.
	ScoreWithFacts(ctx *gin.Context, view *StateView) (RBLPolicyFact, error)
}

RBLFactService computes the aggregated RBL score together with policy-visible facts.

type RBLListPolicyFact

type RBLListPolicyFact struct {
	Name         string
	Host         string
	Query        string
	ReturnCode   string
	ReasonCode   string
	IPFamily     string
	Weight       int
	Listed       bool
	Error        bool
	AllowFailure bool
}

RBLListPolicyFact is the request-local policy view of one configured RBL list.

func RBLPolicyLookup

func RBLPolicyLookup(ctx *gin.Context, view *StateView, rbl *config.RBL) (RBLListPolicyFact, error)

RBLPolicyLookup exposes the internal RBL lookup together with policy-visible list facts.

type RBLPolicyFact

type RBLPolicyFact struct {
	Lists                  []RBLListPolicyFact
	MatchedLists           []string
	Score                  int
	Threshold              int
	MatchedCount           int
	ListCount              int
	AllowFailureErrorCount int
	EffectiveError         bool
	SoftAllowlisted        bool
	IPAllowlisted          bool
}

RBLPolicyFact is the request-local policy view of aggregate RBL evaluation.

type RBLService

type RBLService interface {
	// Score computes the aggregated RBL score for the request.
	Score(ctx *gin.Context, view *StateView) (int, error)
}

RBLService encapsulates RBL checking and aggregation.

type RelayDomainPolicyFact

type RelayDomainPolicyFact struct {
	Value           string
	MatchedDomain   string
	ConfiguredCount int
	Present         bool
	Known           bool
	Rejected        bool
	StaticMatch     bool
	SoftAllowlisted bool
}

RelayDomainPolicyFact is the request-local policy view of relay-domain evaluation.

type RemoteBackendRef

type RemoteBackendRef struct {
	Type        string
	Name        string
	Protocol    string
	Authority   string
	OpaqueToken string
}

RemoteBackendRef binds an edge session to an authority-side backend reference.

func (RemoteBackendRef) IsZero

func (r RemoteBackendRef) IsZero() bool

IsZero reports whether the reference is empty.

type RemoteMFAOperations

type RemoteMFAOperations interface {
	BeginTOTPRegistration(auth *AuthState, idempotencyKey string) (TOTPRegistration, error)
	FinishTOTPRegistration(auth *AuthState, pendingRegistrationID string, code string, idempotencyKey string) error
	VerifyTOTP(auth *AuthState, code string) (bool, error)
	DeleteTOTP(auth *AuthState, idempotencyKey string) error
	GenerateRecoveryCodes(auth *AuthState, count uint32, idempotencyKey string) ([]string, error)
	UseRecoveryCode(auth *AuthState, code string, idempotencyKey string) (bool, error)
	DeleteRecoveryCodes(auth *AuthState, idempotencyKey string) error
}

RemoteMFAOperations is implemented by backends that delegate MFA operations to an authority.

type ResponseDeps

type ResponseDeps struct {
	Cfg       config.File
	Env       config.Environment
	Logger    *slog.Logger
	Resolver  localization.MessageResolver
	WaitDelay func(maxWaitDelay, loginAttempt uint) int
}

ResponseDeps provides the dependencies required to write responses without using globals. Migrates request paths to use these injected dependencies.

type ResponseWriter

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.

func NewDefaultResponseWriter

func NewDefaultResponseWriter(deps ResponseDeps) ResponseWriter

NewDefaultResponseWriter constructs the default response writer with injected dependencies.

type RouteArtifacts

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

RouteArtifacts owns every parsed or copied file dependency used by inbound routes.

func PrepareRouteArtifacts

func PrepareRouteArtifacts(configured config.File, snapshot *config.ArtifactSnapshot) (*RouteArtifacts, error)

PrepareRouteArtifacts parses all listener identities, trust roots, templates, and public files from one sealed source.

func (*RouteArtifacts) FrontendAssets

func (a *RouteArtifacts) FrontendAssets() []FrontendAsset

FrontendAssets returns defensive copies of every captured public asset.

func (*RouteArtifacts) FrontendTemplates

func (a *RouteArtifacts) FrontendTemplates() (*template.Template, error)

FrontendTemplates returns a detached parsed template set for one router.

func (*RouteArtifacts) GRPCServerTLSConfig

func (a *RouteArtifacts) GRPCServerTLSConfig(section *config.RuntimeGRPCTLSSection) (*tls.Config, error)

GRPCServerTLSConfig builds one detached gRPC listener configuration from sealed material.

func (*RouteArtifacts) HTTPClientCAs

func (a *RouteArtifacts) HTTPClientCAs() *x509.CertPool

HTTPClientCAs returns a detached inbound HTTP trust pool.

func (*RouteArtifacts) HTTPServerCertificate

func (a *RouteArtifacts) HTTPServerCertificate() (tls.Certificate, error)

HTTPServerCertificate returns a detached listener identity.

func (*RouteArtifacts) ReadFile

func (a *RouteArtifacts) ReadFile(path string) ([]byte, error)

ReadFile returns a defensive copy of one sealed route-served file.

type RouterComposer

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),
		setupIDP func(*gin.Engine),
		setupBackchannel func(*gin.Engine),
	)
}

RouterComposer builds/configures the Gin engine and registers routes in the exact order as before.

type ScopeManager

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

ScopeManager evaluates whether claims are permitted by the requested scopes.

func NewScopeManager

func NewScopeManager(requestedScopes []string, customScopes []config.Oauth2CustomScope) *ScopeManager

NewScopeManager constructs a ScopeManager from config and the requested scopes. It merges standard claim definitions with custom scope/claim definitions.

func (*ScopeManager) AllowsClaim

func (s *ScopeManager) AllowsClaim(claimName string) bool

AllowsClaim reports whether a claim is allowed by any of the requested scopes.

func (*ScopeManager) DefaultType

func (s *ScopeManager) DefaultType(claimName string) string

DefaultType returns the default type for a claim name, if defined.

type ServerSignals

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

type State interface {
	// DeleteWebAuthnCredential removes a WebAuthn credential for the user in the backend.
	DeleteWebAuthnCredential(credential *mfa.PersistentCredential) (err error)

	// SaveWebAuthnCredential saves a WebAuthn credential for the user in the backend.
	SaveWebAuthnCredential(credential *mfa.PersistentCredential) (err error)

	// UpdateWebAuthnCredential updates an existing WebAuthn credential in the backend.
	UpdateWebAuthnCredential(oldCredential *mfa.PersistentCredential, newCredential *mfa.PersistentCredential) (err error)

	// GetWebAuthnCredentials retrieves WebAuthn credentials for the user in the backend.
	GetWebAuthnCredentials() (credentials []mfa.PersistentCredential, err error)

	// FinishSetup completes the initialization of the state and logs the incoming request.
	FinishSetup(ctx *gin.Context)

	// SetUsername sets the username for the current authentication state.
	SetUsername(username string)

	// SetPassword sets the password for the current authentication state.
	SetPassword(password secret.Value)

	// 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.
	GetPassword() secret.Value

	// GetProtocol retrieves the protocol configuration associated with the current state.
	GetProtocol() *config.Protocol

	// FinishLogging logs the authentication result and updates metrics.
	FinishLogging(ctx *gin.Context, result definitions.AuthResult)

	// 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)

	// SetSAMLEntityID sets the SAML Entity ID for the authentication state.
	SetSAMLEntityID(samlEntityID string)

	// GetAccountOk returns the account field value and a boolean indicating if the account field is present and valid.
	GetAccountOk() (string, bool)

	// GetUniqueUserIDOk returns the unique user identifier and a boolean indicating its presence.
	GetUniqueUserIDOk() (string, bool)

	// GetDisplayNameOk returns the user display name and a boolean indicating its presence.
	GetDisplayNameOk() (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

	// GetUsedPassDBBackendName returns the name of the backend used for the password database during the authentication process.
	GetUsedPassDBBackendName() string

	// GetSourcePassDBBackend returns the source backend used for the password database during the authentication process.
	GetSourcePassDBBackend() definitions.Backend

	// GetAttributes retrieves a map of database attributes where keys are field names and values are the corresponding data.
	GetAttributes() bktype.AttributeMapping

	// GetAttributesCopy returns a deep copy of the attributes map.
	GetAttributesCopy() 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

	// GetLogger returns the injected logger for this state.
	GetLogger() *slog.Logger

	// 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)

	// 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

	// AccountCache returns the AccountCache manager.
	AccountCache() *accountcache.Manager

	// Channel returns the backend channel.
	Channel() backend.Channel

	// PurgeCache invalidates the user authentication cache.
	PurgeCache()

	// PurgeCacheFor invalidates the user authentication cache for a specific username.
	PurgeCacheFor(username string)
	// contains filtered or unexported methods
}

State is implemented by AuthState and defines the methods to interact with the authentication process.

func NewAuthStateFromContextWithDeps

func NewAuthStateFromContextWithDeps(ctx *gin.Context, deps AuthDeps) State

NewAuthStateFromContextWithDeps initializes and returns an AuthState using the provided gin.Context and explicit deps.

func NewAuthStateWithSetupWithDeps

func NewAuthStateWithSetupWithDeps(ctx *gin.Context, deps AuthDeps) State

NewAuthStateWithSetupWithDeps is the dependency-injected variant of NewAuthStateWithSetup. Call this from request boundaries that already have explicit deps available.

type StateView

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.

func (*StateView) Auth

func (v *StateView) Auth() *AuthState

Auth exposes the underlying AuthState for implementations in subpackages. It keeps write access internal to core by returning the pointer; callers must treat it as read-only.

type TLSConfigurator

type TLSConfigurator interface {
	Build() *tls.Config // nil if TLS disabled
}

TLSConfigurator encapsulates TLS parameters (CA, suites, min version, NextProtos...).

type TOTPRecoveryCodeConsumer

type TOTPRecoveryCodeConsumer interface {
	ConsumeTOTPRecoveryCode(auth *AuthState, code string) (valid bool, remaining int, err error)
}

TOTPRecoveryCodeConsumer consumes a matching recovery code in one backend-owned operation.

type TOTPRegistration

type TOTPRegistration struct {
	ExpiresAt             time.Time
	PendingRegistrationID string
	Secret                string
	OTPAuthURL            string
}

TOTPRegistration contains one-time setup material for a pending TOTP registration.

type TOTPSettings

type TOTPSettings struct {
	Issuer    string
	Period    uint
	Skew      uint
	Digits    otp.Digits
	Algorithm otp.Algorithm
}

TOTPSettings contains the interoperable TOTP profile used for setup and validation.

func NewTOTPSettings

func NewTOTPSettings(cfg config.File) TOTPSettings

NewTOTPSettings builds the TOTP profile from configuration and applies stable interoperability defaults.

func (TOTPSettings) Generate

func (settings TOTPSettings) Generate(accountName string) (TOTPRegistration, error)

Generate creates one-time TOTP setup material for an account.

func (TOTPSettings) Validate

func (settings TOTPSettings) Validate(code string, secret string) error

Validate verifies a user supplied TOTP code against a stored secret.

type TokenFlusher

type TokenFlusher interface {
	FlushUserTokens(ctx context.Context, userID string) error
}

TokenFlusher abstracts the ability to flush all OIDC/SAML2 tokens for a user. It is implemented by idp.RedisTokenStorage and injected into restAdminDeps to avoid a cyclic import between core and idp.

type TransportRunner

type TransportRunner interface {
	Serve(ctx context.Context, srv *http.Server, 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)
  • proxy: optional HAProxy PROXY v2 listener (nil if disabled)
  • signals: channels to signal server termination events

type WebAuthnCredentialDBFunc

type WebAuthnCredentialDBFunc func(uniqueUserID string) ([]mfa.PersistentCredential, error)

WebAuthnCredentialDBFunc defines a signature for WebAuthn credential object lookups

Directories

Path Synopsis
Package cookie provides secure encrypted cookie management for storing sensitive session data in a single encrypted browser cookie.
Package cookie provides secure encrypted cookie management for storing sensitive session data in a single encrypted browser cookie.
Package language provides language functionality.
Package language provides language functionality.
Package localization contains transport-neutral policy message localization.
Package localization contains transport-neutral policy message localization.

Jump to

Keyboard shortcuts

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