Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyStringField(src string, dest *string)
- func AssertNoForbiddenSymbols(t *testing.T, targetPath string)
- func ByteSize(bytes uint64) string
- func ComparePasswords(hashPassword string, plainPassword string) (bool, error)
- func ContextWithHTTPRequestCancellation(parent context.Context, req *http.Request) (context.Context, context.CancelFunc)
- func DNSResolverPeer(cfg config.File) (host string, port int, ok bool)
- func DNSResolverPeerFromAddress(addr string) (host string, port int, ok bool)
- func DebugModule(ctx context.Context, cfg config.File, logger *slog.Logger, ...)
- func DebugModuleWithCfg(ctx context.Context, cfg config.File, logger *slog.Logger, ...)
- func DetachedHTTPRequest(parent context.Context, req *http.Request) *http.Request
- func DirectPeerIsTrustedProxy(ctx *gin.Context, cfg config.File, logger *slog.Logger) bool
- func EscapeLDAPFilter(s string) string
- func ExpandLDAPFilter(filter string, macroSource *MacroSource) string
- func FormatDurationMs(d time.Duration) string
- func GenerateRandomString(n int) (string, error)
- func GenerateRandomStringFromAlphabet(n int, alphabet string) (string, error)
- func GetCtxWithDeadlineLDAPModify(cfg config.File) (context.Context, context.CancelFunc)
- func GetCtxWithDeadlineLDAPSearch(cfg config.File) (context.Context, context.CancelFunc)
- func GetCtxWithDeadlineRedisRead(ctx context.Context, cfg config.File) (context.Context, context.CancelFunc)
- func GetCtxWithDeadlineRedisWrite(ctx context.Context, cfg config.File) (context.Context, context.CancelFunc)
- func GetDefaultEnvironment() config.Environment
- func GetHash(value string) string
- func GetHashBytes(value []byte) string
- func HTTPRequestContextError(req *http.Request) error
- func HTTPRequestDone(req *http.Request) <-chan struct{}
- func IsHTTPRequestCanceled(logger *slog.Logger, req *http.Request, session, phase string) bool
- func IsInNetwork(ctx context.Context, cfg config.File, logger *slog.Logger, ...) (matchIP bool)
- func IsInNetworkWithCfg(ctx context.Context, cfg config.File, logger *slog.Logger, ...) (matchIP bool)
- func IsSoftWhitelisted(ctx context.Context, cfg config.File, logger *slog.Logger, ...) bool
- func NewDNSResolver(cfg config.File) (resolver *net.Resolver)
- func NewHTTPClient(cfg config.File) *http.Client
- func NewHTTPClientTransport(cfg config.File) *http.Transport
- func PreparePasswordBytesWithConfig(password []byte, cfg config.File) ([]byte, bool)
- func PreparedPasswordHashWithConfig(password secret.Value, cfg config.File) string
- func ProcessXForwardedFor(ctx *gin.Context, cfg config.File, logger *slog.Logger, ...)
- func ProtoErrToFields(err error) (fields []zap.Field)
- func ReadBoundedRequestBody(reader io.Reader, limit int64) ([]byte, error)
- func RemoveCRLFFromQueryOrFilter(value string, sep string) string
- func RemoveFromCommaSeparatedList(list, value string) string
- func RequestClientIPWithConfig(ctx *gin.Context, cfg config.File, logger *slog.Logger) string
- func RequestResource(httpCtx *gin.Context, httpReq *http.Request, fallback string) string
- func ResolveIPAddress(ctx context.Context, cfg config.File, address string) (hostname string)
- func SetDefaultEnvironment(env config.Environment)
- func SetDefaultLogger(logger *slog.Logger)
- func ShouldSetSecureCookie() bool
- func URLPartialDecode(value string) string
- func ValidateUsername(username string) bool
- func WithNotAvailable(value string) string
- type CryptPassword
- type HTTPRequestContextScope
- type MacroSource
- type RedisLogger
Constants ¶
const ( // DefaultHTTPRequestBodyLimit is the shared fallback limit for hook request bodies. DefaultHTTPRequestBodyLimit int64 = 1 << 20 )
Variables ¶
var ( // ErrRequestBodyTooLarge reports that a request body exceeded its configured limit. ErrRequestBodyTooLarge = errors.New("request body too large") )
var ForbiddenSymbols = []string{
forbiddenConfig + ".GetFile",
forbiddenConfig + ".GetEnvironment",
forbiddenRedis + ".GetClient",
forbiddenLog + ".Logger",
}
ForbiddenSymbols defines a list of symbols that should not be used in certain packages.
Functions ¶
func ApplyStringField ¶
ApplyStringField updates the string pointer `dest` with the value of `src` if `src` is non-empty.
func AssertNoForbiddenSymbols ¶
AssertNoForbiddenSymbols checks if the given package (identified by its import path) uses any of the forbidden symbols. Note: This relies on 'go tool nm' and might not catch all dynamic usages, but it's a good compile-time check for direct references.
func ByteSize ¶
ByteSize formats a given number of bytes into a human-readable string representation. If the number is less than 1024, it will be displayed in bytes (e.g., "256B"). Otherwise, the number will be converted into a larger unit (e.g., 1.5KB, 20MB, etc.).
func ComparePasswords ¶
ComparePasswords takes a plain password and creates a hash. Then it compares the hashed passwords and returns true, if both passwords are equal. If an error occurs, the result is false for the compare operation and the error is returned. This function uses constant-time comparison to prevent timing attacks.
func ContextWithHTTPRequestCancellation ¶
func ContextWithHTTPRequestCancellation(parent context.Context, req *http.Request) (context.Context, context.CancelFunc)
ContextWithHTTPRequestCancellation derives a context from parent and forwards HTTP request cancellation into it.
func DNSResolverPeer ¶
DNSResolverPeer returns the configured resolver peer (host/port) for tracing. For loopback/localhost resolvers ok is false to avoid creating a misleading remote node in downstream service graphs.
func DNSResolverPeerFromAddress ¶
DNSResolverPeerFromAddress normalizes a DNS resolver address (optionally including scheme and port) and returns host/port information suitable for tracing attributes.
If the address points to loopback (e.g. 127.0.0.1, ::1, localhost), ok is false.
func DebugModule ¶
func DebugModule(ctx context.Context, cfg config.File, logger *slog.Logger, module definitions.DbgModule, keyvals ...any)
DebugModule provides the exported DebugModule function.
func DebugModuleWithCfg ¶
func DebugModuleWithCfg(ctx context.Context, cfg config.File, logger *slog.Logger, module definitions.DbgModule, keyvals ...any)
DebugModuleWithCfg logs debug information for a specific module if it is enabled in the configuration and logger is specified.
func DetachedHTTPRequest ¶
DetachedHTTPRequest clones req onto a long-lived parent context. This is used for background work that must not inherit client disconnects.
func DirectPeerIsTrustedProxy ¶
DirectPeerIsTrustedProxy reports whether the immediate peer matches trusted_proxies.
func EscapeLDAPFilter ¶
EscapeLDAPFilter escapes a string for safe embedding into an LDAP filter per RFC 4515. It replaces the following characters:
\ -> \\5c * -> \\2a ( -> \\28 ) -> \\29 NUL-> \\00
func ExpandLDAPFilter ¶
func ExpandLDAPFilter(filter string, macroSource *MacroSource) string
ExpandLDAPFilter replaces legacy placeholders and macros using LDAP-safe escaping. It supports both `%s` and `%{...}` syntax.
func FormatDurationMs ¶
FormatDurationMs formats a time.Duration as milliseconds with a fixed precision. The output is always in milliseconds using three fractional digits, e.g., "12.345ms". This ensures consistent latency units across logs regardless of the duration magnitude.
func GenerateRandomString ¶
GenerateRandomString generates a cryptographically secure random string of a given length.
func GenerateRandomStringFromAlphabet ¶
GenerateRandomStringFromAlphabet generates a cryptographically secure random string from the provided alphabet.
func GetCtxWithDeadlineLDAPModify ¶
GetCtxWithDeadlineLDAPModify creates a context with a timeout for LDAP modify operations. Falls back to LDAPSearch timeout when LDAPModify is not configured.
func GetCtxWithDeadlineLDAPSearch ¶
GetCtxWithDeadlineLDAPSearch creates a context with a timeout for LDAP account searches. Parent context is the service context to avoid coupling to HTTP request lifetimes.
func GetCtxWithDeadlineRedisRead ¶
func GetCtxWithDeadlineRedisRead(ctx context.Context, cfg config.File) (context.Context, context.CancelFunc)
GetCtxWithDeadlineRedisRead creates a context with a timeout derived from the Redis read timeout configuration. If the provided context is nil, it initializes a new context using svcctx.Get(). When configuration is not loaded (e.g., in unit tests), it falls back to a sane default timeout. Returns the derived context and its corresponding cancel function.
func GetCtxWithDeadlineRedisWrite ¶
func GetCtxWithDeadlineRedisWrite(ctx context.Context, cfg config.File) (context.Context, context.CancelFunc)
GetCtxWithDeadlineRedisWrite creates a context with a timeout derived from the Redis write timeout configuration. If the provided context is nil, it initializes a new context using svcctx.Get(). When configuration is not loaded (e.g., in unit tests), it falls back to a sane default timeout. Returns the derived context and its corresponding cancel function.
func GetDefaultEnvironment ¶
func GetDefaultEnvironment() config.Environment
GetDefaultEnvironment returns the process-wide default environment for util.
func GetHashBytes ¶
GetHashBytes creates the full lowercase SHA-256 hash of prepared password bytes.
func HTTPRequestContextError ¶
HTTPRequestContextError returns the current error state of the HTTP request context.
func HTTPRequestDone ¶
HTTPRequestDone returns the request cancellation channel if available.
func IsHTTPRequestCanceled ¶
IsHTTPRequestCanceled reports whether the HTTP request context is canceled and emits an info log when it is.
func IsInNetwork ¶
func IsInNetwork(ctx context.Context, cfg config.File, logger *slog.Logger, networkList []string, guid, clientIP string) (matchIP bool)
IsInNetwork checks if an IP address is part of a list of networks. It iterates through the networkList and checks each network if it contains the given IP address. The function returns true if there is a match. The function logs any network errors encountered during the process. The function logs the information about checking a network for the given authentication object. The function logs the IP address of the client along with the IP address or network being checked.
func IsInNetworkWithCfg ¶
func IsInNetworkWithCfg(ctx context.Context, cfg config.File, logger *slog.Logger, networkList []string, guid, clientIP string) (matchIP bool)
IsInNetworkWithCfg provides the exported IsInNetworkWithCfg function.
func IsSoftWhitelisted ¶
func IsSoftWhitelisted(ctx context.Context, cfg config.File, logger *slog.Logger, username, clientIP, guid string, softWhitelist config.SoftWhitelist) bool
IsSoftWhitelisted checks whether a given clientIP is in the soft whitelist associated with a username. Returns true if the clientIP matches any networks in the soft whitelist, otherwise false.
func NewDNSResolver ¶
NewDNSResolver initializes and returns a new DNS resolver based on the provided configuration.
func NewHTTPClient ¶
NewHTTPClient creates and returns a new instance of http.Client configured with settings from the provided config.File.
func NewHTTPClientTransport ¶
NewHTTPClientTransport creates an HTTP transport configured from server runtime settings without tracing wrappers.
func PreparePasswordBytesWithConfig ¶
PreparePasswordBytesWithConfig prepares a password only when request configuration is available.
func PreparedPasswordHashWithConfig ¶
PreparedPasswordHashWithConfig returns the full Redis hash of one request password. It returns an empty string for empty passwords or when no configuration is available.
func ProcessXForwardedFor ¶
func ProcessXForwardedFor(ctx *gin.Context, cfg config.File, logger *slog.Logger, clientIP, clientPort *string, xssl *string)
ProcessXForwardedFor processes the X-Forwarded-For header in the given Gin context, extracting the forwarded address and updating the client IP and port accordingly. If the forwarded address is not empty, the function checks if the client IP is in the list of trusted proxies. If it is not, a warning message is logged and the function returns. If the client IP is in the list of trusted proxies, the function logs the matching of the client IP with the forwarded address and updates the client IP to the forwarded address. If the forwarded address contains multiple IP addresses separated by a comma, the first IP address is used as the client IP. The client port is set to "N/A".
func ProtoErrToFields ¶
ProtoErrToFields provides the exported ProtoErrToFields function.
func ReadBoundedRequestBody ¶
ReadBoundedRequestBody reads at most limit plus one byte to detect oversized bodies.
func RemoveCRLFFromQueryOrFilter ¶
RemoveCRLFFromQueryOrFilter provides the exported RemoveCRLFFromQueryOrFilter function.
func RemoveFromCommaSeparatedList ¶
RemoveFromCommaSeparatedList removes all occurrences of value from a comma-separated list and returns the remaining items joined by commas.
func RequestClientIPWithConfig ¶
RequestClientIPWithConfig resolves the client IP from trusted forwarding headers using the Nauthilus proxy configuration before falling back to the direct peer address. Without a configuration no proxy is trusted, so the direct peer address is returned.
func RequestResource ¶
RequestResource derives a Prometheus resource label from HTTP context/request data. It prefers the Gin route FullPath when available, then falls back to URL path or a stable fallback label.
func ResolveIPAddress ¶
ResolveIPAddress returns the hostname for a given IP address.
func SetDefaultEnvironment ¶
func SetDefaultEnvironment(env config.Environment)
SetDefaultEnvironment sets the process-wide default environment for util.
func SetDefaultLogger ¶
SetDefaultLogger provides the exported SetDefaultLogger function.
func ShouldSetSecureCookie ¶
func ShouldSetSecureCookie() bool
ShouldSetSecureCookie reports whether cookies should be marked as Secure. It returns false in developer mode to allow HTTP callbacks.
func URLPartialDecode ¶
URLPartialDecode decodes valid percent-escaped byte sequences in a string and leaves invalid escape sequences untouched.
Behavior: - Decodes only "%XX" where X are hexadecimal digits. - Does not treat '+' as space. - Leaves malformed escapes unchanged (e.g. "%2G", trailing "%").
func ValidateUsername ¶
ValidateUsername validates the given username against the usernamePattern regular expression. It takes a string username as input and returns a boolean value representing whether the username is valid or not. The usernamePattern regular expression allows any character except "(", ")", "{", SP, CTL, "%", "*", "\", except empty string. The function returns true if the username matches the pattern, and false otherwise.
func WithNotAvailable ¶
WithNotAvailable returns a default "not available" string if the given value is an empty string.
Types ¶
type CryptPassword ¶
type CryptPassword struct {
definitions.Algorithm
definitions.PasswordOption
Password string
Salt []byte
}
CryptPassword is a container for an encrypted password typically used in SQL fields.
func (*CryptPassword) Generate ¶
func (c *CryptPassword) Generate(plainPassword string, salt []byte, alg definitions.Algorithm, pwOption definitions.PasswordOption) ( string, error, )
Generate creates the encrypted form of a plain text password. It sets the Algorithm, PasswordOption, Salt, and Password fields of the CryptPassword struct and returns the generated password string.
func (*CryptPassword) GetParameters ¶
func (c *CryptPassword) GetParameters(cryptedPassword string) ( salt []byte, alg definitions.Algorithm, pwOption definitions.PasswordOption, err error, )
GetParameters splits an encoded password into its components. It extracts the salt, algorithm, and password option from the crypted password and sets the corresponding fields in the CryptPassword struct.
type HTTPRequestContextScope ¶
type HTTPRequestContextScope struct {
// contains filtered or unexported fields
}
HTTPRequestContextScope owns one temporary context replacement on an HTTP request pointer.
func NewHTTPRequestContextScope ¶
func NewHTTPRequestContextScope(requestContext context.Context, target **http.Request) *HTTPRequestContextScope
NewHTTPRequestContextScope installs requestContext on target until Restore is called.
func (*HTTPRequestContextScope) Restore ¶
func (s *HTTPRequestContextScope) Restore()
Restore reinstates the request pointer that was active before the scope began.
type MacroSource ¶
type MacroSource struct {
Username string
UserDN string
Account string
XLocalIP string
XPort string
ClientIP string
XClientPort string
TOTPSecret string
Protocol config.Protocol
}
MacroSource holds all values that might be used in macros.
func (*MacroSource) ReplaceMacros ¶
func (m *MacroSource) ReplaceMacros(source string) (dest string)
ReplaceMacros replaces several macros with values found in the Authentication object.
%Modifiers{long variables}
Modifiers: (Optional): L - Lower U - Upper
R - Reverse the string T - Trim the string
Long variavles: user - full username, i.e. localpart@domain.tld username - the local part of {user}, if user has a domain part, else user and username are the same domain - the domain part of {user}. Empty string, if {user} did not contain a domain part service - The service name, i.e. imap, pop3, lmtp local_ip - local IP address local_port - local port remote_ip - remote client IP address remote_port - remote client port. account - authenticated account name user_dn - LDAP distinguished name of the current user
type RedisLogger ¶
type RedisLogger struct {
// contains filtered or unexported fields
}
RedisLogger implements the interface redis.Logging
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package contentneg implements server-driven content negotiation against the HTTP Accept header following RFC 9110 section 12.5.1.
|
Package contentneg implements server-driven content negotiation against the HTTP Accept header following RFC 9110 section 12.5.1. |
|
Package crypto provides crypto functionality.
|
Package crypto provides crypto functionality. |
|
Package keygen provides keygen functionality.
|
Package keygen provides keygen functionality. |