libs

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2025 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var LogLeveler *slog.LevelVar

Functions

func ConfigRoute

func ConfigRoute(c echo.Context) error

ConfigRoute returns the application's configuration for default roles and group-to-role mappings. This endpoint allows clients to discover which roles users will receive based on their groups.

func Decrypt

func Decrypt(ctx context.Context, encryptedString string, keyString string) (string, error)

Decrypt decrypts an AES-256-GCM encrypted string back to plaintext. The encryptedString parameter must be a hexadecimal string produced by Encrypt. The key parameter must be the same 64-character hexadecimal key used during encryption.

func EncodeForCacheKey added in v1.2.0

func EncodeForCacheKey(username string) string

EncodeForCacheKey encodes a username for safe use as a cache key. It uses URL encoding to ensure special characters don't interfere with cache key format.

func Encrypt

func Encrypt(ctx context.Context, stringToEncrypt string, keyString string) (string, error)

Encrypt encrypts a plaintext string using the AES-256-GCM cipher. The key parameter must be a 64-character hexadecimal string (representing 32 bytes). Returns the ciphertext as a hexadecimal string with the nonce prepended.

func GenerateKey

func GenerateKey(ctx context.Context) (string, error)

GenerateKey generates a cryptographically secure random key suitable for AES-256 encryption. The key is returned as a hexadecimal-encoded string (64 characters representing 32 bytes).

func GenerateTemporaryUserPassword

func GenerateTemporaryUserPassword(ctx context.Context) (string, error)

GenerateTemporaryUserPassword creates a cryptographically secure temporary password for user authentication. The password is 32 characters long and contains a mix of digits, symbols, and upper/lower case letters with no repeated characters.

func GetAppName added in v1.1.0

func GetAppName() string

GetAppName retrieves the application name from environment variables. It first checks OTEL_SERVICE_NAME, then APP_NAME, and defaults to "elastauth" if neither is set.

func GetUserRoles

func GetUserRoles(ctx context.Context, userGroups []string) []string

GetUserRoles determines the roles that should be assigned to a user based on their group membership. If the user belongs to mapped groups, their roles are retrieved from the group_mappings configuration. If no mapped groups are found, default_roles are used.

func HandleSecretKey added in v1.0.6

func HandleSecretKey(ctx context.Context) error

HandleSecretKey manages the encryption secret key configuration. If the generateKey flag is set, it generates a new key, prints it, and exits. If no secret key is configured, it generates a random one and logs a warning.

func HealthRoute

func HealthRoute(c echo.Context) error

HealthRoute responds to health checks with a JSON response containing the application status. This endpoint is typically used by load balancers or monitoring systems to verify the application is running.

func InitConfiguration added in v1.0.6

func InitConfiguration() error

InitConfiguration initializes the application configuration from command-line flags, environment variables (prefixed with ELASTAUTH_), and a YAML configuration file. It sets up viper to read from these sources and establishes default values for various settings.

func IsSensitiveField added in v1.2.0

func IsSensitiveField(fieldName string) bool

IsSensitiveField checks whether a field name represents sensitive data that should be redacted in logs. It looks for common sensitive keywords like "password", "secret", "key", "token", "credential", and "auth".

func MainRoute

func MainRoute(c echo.Context) error

MainRoute is the main authentication handler that processes user authentication requests. It extracts user information from request headers, validates input, generates temporary passwords, optionally upserts the user to Elasticsearch, caches encrypted passwords, and returns basic auth credentials. The route supports caching to improve performance on repeated requests for the same user.

func ParseAndValidateGroups added in v1.2.0

func ParseAndValidateGroups(groupsHeader string, enableWhitelist bool, whitelist []string) ([]string, error)

ParseAndValidateGroups parses a comma-separated string of group names and validates each one. If enableWhitelist is true, only groups in the provided whitelist are accepted. Returns a slice of validated group names or an error if validation fails.

func SafeLogError added in v1.2.0

func SafeLogError(err error) string

SafeLogError returns a generic error message that does not expose implementation details. This should be used when displaying errors to end users or in logs where sensitive information should not be disclosed.

func SanitizeForLogging added in v1.2.0

func SanitizeForLogging(data interface{}) interface{}

SanitizeForLogging recursively processes data structures and redacts sensitive fields to prevent credentials and secrets from being logged. It handles maps, structs, slices, and other types by checking field names against a list of sensitive keywords.

func UpsertUser

func UpsertUser(ctx context.Context, username string, elasticsearchUser ElasticsearchUser) error

UpsertUser creates or updates a user in Elasticsearch with the provided credentials and configuration. It sends the user data to the Elasticsearch security API using basic authentication. If the user already exists, their data will be updated; otherwise, a new user is created.

func ValidateConfiguration added in v1.2.0

func ValidateConfiguration(ctx context.Context) error

ValidateConfiguration performs comprehensive validation of all configuration parameters. It checks required settings, secret key format, cache type, log levels, and other configuration options.

func ValidateEmail added in v1.2.0

func ValidateEmail(email string) error

ValidateEmail validates the format and length of an email address. Valid emails follow standard RFC 5322 basic format requirements and must be between 1 and 320 characters long.

func ValidateGroupName added in v1.2.0

func ValidateGroupName(group string) error

ValidateGroupName validates the format and length of a group name. Valid group names must be between 1 and 255 characters long and cannot contain control characters.

func ValidateName added in v1.2.0

func ValidateName(name string) error

ValidateName validates the format and length of a user's full name. Valid names must not exceed 500 characters and cannot contain control characters (except tab, newline, and carriage return).

func ValidateRequiredConfig added in v1.2.0

func ValidateRequiredConfig(ctx context.Context) error

ValidateRequiredConfig checks that all required configuration parameters are set. Required parameters include Elasticsearch credentials, host, and the encryption secret key.

func ValidateSecretKey added in v1.2.0

func ValidateSecretKey(key string) error

ValidateSecretKey validates that the secret key is properly configured as a 64-character hexadecimal string representing a 32-byte (256-bit) AES key.

func ValidateUsername added in v1.2.0

func ValidateUsername(username string) error

ValidateUsername validates the format and length of a username. Valid usernames contain only alphanumeric characters, dots, underscores, hyphens, and at-signs, and must be between 1 and 255 characters long.

func WebserverInit added in v1.0.6

func WebserverInit(ctx context.Context)

WebserverInit initializes the webserver and sets up all the routes. It configures the server based on settings from the viper configuration library. It also adds support for metrics if enabled with the `enable_metrics` flag. Lastly, it starts the server on the `listen` address specified in the configuration.

Types

type ElasticsearchConnectionDetails

type ElasticsearchConnectionDetails struct {
	URL      string
	Username string
	Password string
}

ElasticsearchConnectionDetails holds the connection configuration for an Elasticsearch cluster. It includes the cluster URL, username, and password required for authentication.

type ElasticsearchUser

type ElasticsearchUser struct {
	Enabled  bool                      `json:"enabled"`
	Email    string                    `json:"email"`
	Password string                    `json:"password"`
	Metadata ElasticsearchUserMetadata `json:"metadata"`
	FullName string                    `json:"full_name"`
	Roles    []string                  `json:"roles"`
}

ElasticsearchUser represents a user object in Elasticsearch with authentication credentials, metadata, and role assignments for access control.

type ElasticsearchUserMetadata

type ElasticsearchUserMetadata struct {
	Groups []string `json:"groups"`
}

ElasticsearchUserMetadata contains additional metadata about an Elasticsearch user, particularly the groups they belong to for access control purposes.

type ErrorResponse

type ErrorResponse struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

The type `ErrorResponse` is a struct that contains a message and code for error responses in Go. @property {string} Message - Message is a string property that represents the error message that will be returned in the response when an error occurs. @property {int} Code - The `Code` property is an integer that represents an error code. It is used to identify the type of error that occurred. For example, a code of 404 might indicate that a requested resource was not found, while a code of 500 might indicate a server error.

type HealthResponse

type HealthResponse struct {
	Status string `json:"status"`
}

The HealthResponse type is a struct in Go that contains a single field called Status, which is a string that will be represented as "status" in JSON. @property {string} Status - The `Status` property is a string field that represents the status of a health response. It is tagged with `json:"status"` which indicates that when this struct is serialized to JSON, the field name will be "status".

Jump to

Keyboard shortcuts

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