backend

package
v4.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: GPL-3.0 Imports: 42 Imported by: 0

Documentation

Overview

Package backend provides backend functionality.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteWebAuthnFromRedis

func DeleteWebAuthnFromRedis(ctx context.Context, logger *slog.Logger, cfg config.File, redisClient rediscli.Client, uniqueUserID string) error

DeleteWebAuthnFromRedis removes a cached WebAuthn user entry by unique user ID.

func GetCacheNames

func GetCacheNames(cfg config.File, channel Channel, requestedProtocol string, backends definitions.CacheNameBackend) (cacheNames config.StringSet)

GetCacheNames retrieves LDAP/Lua protocol cache names and native plugin instance namespaces. If no cache names are found, a default cache name "__default__" is returned.

func GetUserAccountFromCache

func GetUserAccountFromCache(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, accountCache *accountcache.Manager, username, protocol, oidcClientID, guid string) (accountName string)

GetUserAccountFromCache fetches the user account name from Redis cache using the provided username. Logs errors and increments Redis read counter. Returns an empty string if the account name is not found or an error occurs.

func IdentityCacheKey

func IdentityCacheKey(prefix, cacheName, username string) string

IdentityCacheKey identifies one username in a configured backend cache namespace. Different lookup contexts replace this entry and must pass the separate scope check.

func IsPluginPasswordCacheName

func IsPluginPasswordCacheName(name string) bool

IsPluginPasswordCacheName identifies only the reserved internal namespace, never a printable cache_name.

func LDAPAuthWorker

func LDAPAuthWorker(ctx context.Context, cfg config.File, logger *slog.Logger, channel Channel, poolName string, deps LDAPWorkerDeps)

LDAPAuthWorker is responsible for handling LDAP authentication requests using a connection pool and concurrency control. It initializes the authentication connection pool, starts a resource management process, and handles requests or exits gracefully. It now uses a priority queue instead of channels for better request handling.

func LDAPEndpointWithCtx

func LDAPEndpointWithCtx(cfg config.File) lua.LGFunction

LDAPEndpointWithCtx is a WithCtx-factory alias returning the same function as LuaLDAPEndpoint(cfg).

func LDAPMainWorker

func LDAPMainWorker(ctx context.Context, cfg config.File, logger *slog.Logger, channel Channel, poolName string, deps LDAPWorkerDeps)

LDAPMainWorker orchestrates LDAP lookup operations, manages a connection pool, and processes incoming requests in a loop. It now uses a priority queue instead of channels for better request handling.

func LDAPModifyWithCtx

func LDAPModifyWithCtx(ctx context.Context) lua.LGFunction

LDAPModifyWithCtx is a WithCtx-factory alias returning the same function as LuaLDAPModify(ctx).

func LDAPSearchWithCtx

func LDAPSearchWithCtx(ctx context.Context) lua.LGFunction

LDAPSearchWithCtx is a WithCtx-factory alias returning the same function as LuaLDAPSearch(ctx).

func LDAPWorkerPoolName

func LDAPWorkerPoolName(poolName string) string

LDAPWorkerPoolName maps public default aliases to the internal worker pool name.

func LoadCacheFromRedis

func LoadCacheFromRedis(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, key string, ucp *bktype.PositivePasswordCache) (isRedisErr bool, err error)

LoadCacheFromRedis retrieves cache data from Redis Hash based on a provided key and populates the given structure. It increments Redis read metrics and logs errors or debug information appropriately during the operation. Returns whether the error originated from Redis and any encountered error during retrieval or unmarshaling.

func LoadCacheFromRedisWithSF

func LoadCacheFromRedisWithSF(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, key string, ucp *bktype.PositivePasswordCache) (isRedisErr bool, err error)

LoadCacheFromRedisWithSF is a wrapper around LoadCacheFromRedis that uses singleflight to avoid redundant Redis lookups.

func LoaderLDAPStateless

func LoaderLDAPStateless() lua.LGFunction

LoaderLDAPStateless returns an empty, stateless module table for nauthilus_ldap. It is intended to be preloaded once per VM (base environment). Per-request bindings will later clone this table and inject bound functions via WithCtx factories.

func LoaderModLDAP

func LoaderModLDAP(ctx context.Context, cfg config.File) lua.LGFunction

LoaderModLDAP initializes and loads the LDAP module into the Lua state with predefined functions for LDAP operations.

func LookupUserAccountFromRedis

func LookupUserAccountFromRedis(ctx context.Context, cfg config.File, redisClient rediscli.Client, username, protocol, oidcClientID string) (accountName string, err error)

LookupUserAccountFromRedis returns the user account value from the user Redis hash.

func LuaLDAPEndpoint

func LuaLDAPEndpoint(cfg config.File) lua.LGFunction

LuaLDAPEndpoint provides the exported LuaLDAPEndpoint function.

func LuaLDAPModify

func LuaLDAPModify(ctx context.Context) lua.LGFunction

LuaLDAPModify is a function that modifies LDAP entries based on the given Lua table input. It validates the input table, creates an LDAP modification request, and sends it via priority queue. The function returns results via Lua stack, "OK" on success, or an error message if the operation fails.

func LuaLDAPModifyAssert

func LuaLDAPModifyAssert(ctx context.Context) lua.LGFunction

LuaLDAPModifyAssert requires an explicit assertion before delegating to the queued modifier.

func LuaLDAPSearch

func LuaLDAPSearch(ctx context.Context) lua.LGFunction

LuaLDAPSearch initializes and registers an LDAP search function for Lua, handling inputs, validation, and processing.

func LuaMainWorker

func LuaMainWorker(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, channel Channel, backendName string) (err error)

LuaMainWorker processes Lua script requests in a loop until the context is canceled. It compiles the Lua script and handles requests using a dedicated goroutine for each. It now uses a priority queue instead of channels for better request handling.

func PluginPasswordCacheName

func PluginPasswordCacheName(name string) string

PluginPasswordCacheName isolates native backend instances with a reserved internal NUL separator.

func PositiveCacheKeys

func PositiveCacheKeys(cfg config.File, channel Channel, prefix string, protocols, accounts []string) config.StringSet

PositiveCacheKeys is the shared inventory for password and identity cache invalidation. The identity epoch additionally invalidates aliases that cannot yet be resolved to an account.

func PositiveCacheProtocols

func PositiveCacheProtocols(cfg config.File) []string

PositiveCacheProtocols includes plugin-only configurations in account lookup and purge walks. Plugin keys are protocol-independent; their payload separately binds the request scope.

func PositivePasswordCacheKey

func PositivePasswordCacheKey(prefix, cacheName, account string) string

PositivePasswordCacheKey builds the shared Redis namespace used by writes, reads and invalidation.

func PrepareLuaBackendScripts

func PrepareLuaBackendScripts(cfg config.File) error

PrepareLuaBackendScripts compiles every restart-bound backend before workers start.

func PrepareLuaBackendScriptsWithModules

func PrepareLuaBackendScriptsWithModules(cfg config.File, modules *luaseal.Modules) error

PrepareLuaBackendScriptsWithModules binds every restart-bound backend to one boot-owned module snapshot.

func ResolveAccountIdentifier

func ResolveAccountIdentifier(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, identifier, protocol, oidcClientID, guid string) (accountName string)

ResolveAccountIdentifier resolves an identifier that may be either a username or an account name. It first tries to look up a mapping in the USER hash; if not found, it treats the identifier as an account name.

func SaveUserDataToRedis

func SaveUserDataToRedis(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, guid string, key string, ttl time.Duration, cache *bktype.PositivePasswordCache)

SaveUserDataToRedis is a generic routine to store a cache object on Redis using Redis Hash for better memory efficiency. It stores each field of the PositivePasswordCache structure as a separate hash field, with complex fields serialized as JSON.

func SaveWebAuthnToRedis

func SaveWebAuthnToRedis(ctx context.Context, logger *slog.Logger, cfg config.File, redisClient rediscli.Client, user *User, ttl time.Duration) error

SaveWebAuthnToRedis saves a user's WebAuthn credentials to Redis with a specified TTL using Redis Hash. Returns an error if serialization or Redis storage operation fails.

func SetLuaLDAPQueue

func SetLuaLDAPQueue(enqueuer LDAPRequestEnqueuer)

SetLuaLDAPQueue replaces the Lua LDAP queue enqueuer (nil restores defaults).

func SetUserAccountMapping

func SetUserAccountMapping(ctx context.Context, cfg config.File, redisClient rediscli.Client, username, protocol, oidcClientID, account string) error

SetUserAccountMapping writes/updates the username → account mapping in Redis.

func TrySignalDone

func TrySignalDone(ch chan bktype.Done)

TrySignalDone provides the exported TrySignalDone function.

Types

type Channel

type Channel interface {
	// GetLdapChannel retrieves and returns the LDAPChannel instance associated with the implementation of the Channel interface.
	GetLdapChannel() LDAPChannel

	// GetLuaChannel retrieves and returns the LuaChannel instance associated with the Channel interface implementation.
	GetLuaChannel() LuaChannel
}

Channel is an interface comprising methods to retrieve LDAPChannel and LuaChannel instances.

func NewChannel

func NewChannel(cfg config.File) Channel

NewChannel initializes and returns a new instance of the Channel interface implementation.

type IdentityCache

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

IdentityCache stores encrypted identity snapshots independently of password evidence. Its persistent prefix-wide epoch fences lookups started before administrative invalidation.

func NewIdentityCache

func NewIdentityCache(cfg config.File, client rediscli.Client) *IdentityCache

NewIdentityCache constructs a cache using the injected Redis authority and encryption manager.

func (*IdentityCache) Generation

func (c *IdentityCache) Generation(ctx context.Context) (string, error)

Generation captures the authority epoch before a lookup and safely initializes a missing epoch.

func (*IdentityCache) Invalidate

func (c *IdentityCache) Invalidate(ctx context.Context) error

Invalidate fences every identity entry, including concurrent first lookups of unknown aliases. Broad invalidation is deliberate: canonical identity may be unknown until LDAP returns.

func (*IdentityCache) Load

func (c *IdentityCache) Load(ctx context.Context, key, scope string) ([]byte, error)

Load reads both snapshot and epoch from the writer to avoid accepting stale replica state.

func (*IdentityCache) Store

func (c *IdentityCache) Store(ctx context.Context, key, epoch, scope string, data []byte, ttl time.Duration) error

Store publishes the immutable snapshot with its original epoch and an atomic fixed TTL. A concurrent flush can leave an old-epoch entry, but Load will never accept that entry.

type LDAPAuthQueue

type LDAPAuthQueue interface {
	AddPoolName(poolName string)
	SetMaxQueueLength(poolName string, length int)
	PopWithContext(ctx context.Context, poolName string) *bktype.LDAPAuthRequest
}

LDAPAuthQueue abstracts the authentication request queue for LDAP workers.

type LDAPChannel

type LDAPChannel interface {
	// GetLookupEndChan returns a channel that signals the completion of lookup operations.
	GetLookupEndChan(poolName string) chan bktype.Done

	// GetAuthEndChan returns the channel used to signal the completion of authentication operations.
	GetAuthEndChan(poolName string) chan bktype.Done

	// GetPoolNames retrieves and returns a list of names for all configured LDAP connection pools.
	GetPoolNames() []string

	// AddChannel creates and initializes all necessary channels for the specified LDAP connection pool by poolName.
	AddChannel(poolName string) error
}

LDAPChannel defines an interface for managing LDAP-related channels for communication and operation handling.

func NewLDAPChannel

func NewLDAPChannel(poolName string) LDAPChannel

NewLDAPChannel provides the exported NewLDAPChannel function.

type LDAPEndpointMetadata

type LDAPEndpointMetadata struct {
	PoolName string
	Scheme   string
	Host     string
	Port     int
}

LDAPEndpointMetadata contains configured trace-safe LDAP endpoint fields.

func LDAPEndpoints

func LDAPEndpoints(cfg config.File, poolName string) ([]LDAPEndpointMetadata, error)

LDAPEndpoints returns all configured endpoints for a default or named pool.

type LDAPPoolFactory

type LDAPPoolFactory interface {
	NewPool(ctx context.Context, cfg config.File, logger *slog.Logger, poolType int, poolName string) ldappool.LDAPPool
}

LDAPPoolFactory creates LDAP pools for lookup or authentication workers.

type LDAPQueue

type LDAPQueue interface {
	AddPoolName(poolName string)
	SetMaxQueueLength(poolName string, length int)
	PopWithContext(ctx context.Context, poolName string) *bktype.LDAPRequest
}

LDAPQueue abstracts the shared lookup request queue for LDAP workers.

type LDAPRequestEnqueuer

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

LDAPRequestEnqueuer enqueues LDAP lookup requests with a priority.

type LDAPWorkerDeps

type LDAPWorkerDeps struct {
	Queue       LDAPQueue
	AuthQueue   LDAPAuthQueue
	PoolFactory LDAPPoolFactory
}

LDAPWorkerDeps provides injectable dependencies for LDAP worker startup.

type LuaChannel

type LuaChannel interface {
	// GetLookupEndChan returns a channel used to signal the completion of lookup operations.
	GetLookupEndChan(backendName string) chan bktype.Done

	// GetBackendNames returns a list of all available backend names configured in the LuaChannel implementation.
	GetBackendNames() []string

	// AddChannel adds a new channel for the specified backend identified by the backendName.
	// Returns an error if the backendName is invalid or the channel could not be created.
	AddChannel(backendName string) error
}

LuaChannel defines an interface for managing Lua-related channels used for communication and request handling.

func NewLuaChannel

func NewLuaChannel(backendName string) LuaChannel

NewLuaChannel creates and returns a new instance of LuaChannel, initialized as a LuaChannelImpl.

type LuaChannelImpl

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

LuaChannelImpl describes the exported LuaChannelImpl type.

func (*LuaChannelImpl) AddChannel

func (c *LuaChannelImpl) AddChannel(backendName string) error

AddChannel initializes channels for request and completion handling for a specified backend name. Returns an error if the backend name is invalid.

func (*LuaChannelImpl) GetBackendNames

func (c *LuaChannelImpl) GetBackendNames() []string

GetBackendNames retrieves a list of backend names from the LuaChannelImpl's lookupEndChan map.

func (*LuaChannelImpl) GetLookupEndChan

func (c *LuaChannelImpl) GetLookupEndChan(backendName string) chan bktype.Done

GetLookupEndChan returns a channel of type Done that signals the end of a lookup operation.

type User

type User struct {
	ID          string `redis:"Id"`
	Name        string `redis:"name"`
	DisplayName string `redis:"display_name"`

	Credentials             []mfa.PersistentCredential `redis:"credentials"`
	Attributes              bktype.AttributeMapping    `redis:"-"`
	Groups                  []string                   `redis:"-"`
	GroupDistinguishedNames []string                   `redis:"-"`
	TOTPSecretField         string                     `redis:"totp_secret_field"`
	TOTPRecoveryField       string                     `redis:"totp_recovery_field"`
}

User represents the user model

func GetWebAuthnFromRedis

func GetWebAuthnFromRedis(ctx context.Context, cfg config.File, logger *slog.Logger, redisClient rediscli.Client, uniqueUserID string) (user *User, err error)

GetWebAuthnFromRedis retrieves a User object from Redis Hash using the provided unique user ID. Returns the User object or an error if retrieval or unmarshaling fails.

func NewUser

func NewUser(name string, displayName string, id string) *User

NewUser creates and returns a new User

func (*User) AddCredential

func (u *User) AddCredential(cred webauthn.Credential, name string)

AddCredential associates the credential to the user

func (*User) WebAuthnCredentials

func (u *User) WebAuthnCredentials() []webauthn.Credential

WebAuthnCredentials returns credentials owned by the user

func (*User) WebAuthnDisplayName

func (u *User) WebAuthnDisplayName() string

WebAuthnDisplayName returns the user's display name

func (*User) WebAuthnID

func (u *User) WebAuthnID() []byte

WebAuthnID returns the user's ID

func (*User) WebAuthnIcon

func (u *User) WebAuthnIcon() string

WebAuthnIcon is not (yet) implemented

func (*User) WebAuthnName

func (u *User) WebAuthnName() string

WebAuthnName returns the user's username

Directories

Path Synopsis
Package accountcache provides accountcache functionality.
Package accountcache provides accountcache functionality.
Package bktype provides bktype functionality.
Package bktype provides bktype functionality.
Package ldapendpoint parses LDAP URIs into secret-free endpoint metadata.
Package ldapendpoint parses LDAP URIs into secret-free endpoint metadata.
Package ldappool provides ldappool functionality.
Package ldappool provides ldappool functionality.
Package priorityqueue provides priorityqueue functionality.
Package priorityqueue provides priorityqueue functionality.
Package remote implements edge-side backends backed by a Nauthilus authority.
Package remote implements edge-side backends backed by a Nauthilus authority.

Jump to

Keyboard shortcuts

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