utils
mlflow_secrets_auth.utils
¶
Utility functions for MLflow secrets auth providers.
This module centralizes
- Logger setup with environment-driven log levels.
- Safe logging with automatic redaction of sensitive substrings.
- Secret parsing with automatic format detection (JSON vs. plain string).
- URL allowlist checks.
- Small helpers (duration formatting, TTL validation, masking).
- Retry functionality with exponential backoff and jitter.
format_duration(seconds)
¶
Format a duration in seconds into a short human-readable string.
Examples:
45 -> "45s" 125 -> "2m 5s" 3600 -> "1h"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
seconds
|
int
|
Duration in seconds. |
required |
Returns:
Type | Description |
---|---|
str
|
Short human-readable representation. |
Source code in src/mlflow_secrets_auth/utils.py
is_host_allowed(url, allowed_hosts)
¶
Return whether the URL's host is in the provided allowlist.
Supports exact hostname matches and wildcard patterns using shell-style globbing (e.g., "*.corp.example.com" matches "api.corp.example.com").
Hostname matching is case-insensitive as per DNS standards.
Examples:
- "example.com" matches exactly "example.com"
- "*.corp.example.com" matches "api.corp.example.com", "web.corp.example.com"
- "mlflow.*.com" matches "mlflow.prod.com", "mlflow.staging.com"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url
|
str
|
Full URL to check. |
required |
allowed_hosts
|
list[str] | None
|
List of allowed hostname patterns, or None to allow all. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if allowed (or no allowlist configured), otherwise False. |
Source code in src/mlflow_secrets_auth/utils.py
mask_secret(secret, show_chars=DEFAULT_SHOW_CHARS)
¶
Mask a secret for safe logging.
For short inputs (<= 2 * show_chars) returns a generic "***" to avoid revealing almost the entire secret.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
secret
|
str
|
Secret value. |
required |
show_chars
|
int
|
Number of leading and trailing characters to keep. |
DEFAULT_SHOW_CHARS
|
Returns:
Type | Description |
---|---|
str
|
Masked representation of the secret. |
Source code in src/mlflow_secrets_auth/utils.py
parse_secret_json(secret_value)
¶
Parse secret material with automatic format detection.
Accepts either
- JSON object with one of:
- {"token": "
"} - {"username": "...", "password": "..."}
- {"token": "
- Plain string:
- "username:password" → {"username": "...", "password": "..."}
- "
" → {"token": " "}
Whitespace is stripped from string fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
secret_value
|
str
|
Raw secret value. |
required |
Returns:
Type | Description |
---|---|
dict[str, str]
|
A normalized dict with either {"token": "..."} or {"username": "...", "password": "..."}. |
Raises:
Type | Description |
---|---|
ValueError
|
If the JSON object is invalid or missing required fields. |
Source code in src/mlflow_secrets_auth/utils.py
retry_with_jitter(fn, attempts=3, base_delay=0.1, backoff=2.0, max_delay=1.0, jitter=0.4, sleep=time.sleep)
¶
Retry a function with exponential backoff and jitter.
Calls fn
up to attempts
times with exponential backoff and ±jitter%,
capped by max_delay
. If all attempts fail, reraises the last exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn
|
Callable[[], T]
|
Function to call (should take no arguments). |
required |
attempts
|
int
|
Maximum number of attempts (must be >= 1). |
3
|
base_delay
|
float
|
Initial delay in seconds. |
0.1
|
backoff
|
float
|
Exponential backoff multiplier. |
2.0
|
max_delay
|
float
|
Maximum delay between attempts in seconds. |
1.0
|
jitter
|
float
|
Jitter factor as a proportion (e.g., 0.4 = ±40%). |
0.4
|
sleep
|
Callable[[float], None]
|
Sleep function (mainly for testing). |
sleep
|
Returns:
Type | Description |
---|---|
T
|
Result of the successful function call. |
Raises:
Type | Description |
---|---|
Exception
|
The last exception encountered if all attempts fail. |
Source code in src/mlflow_secrets_auth/utils.py
safe_log(logger, level, message, *args)
¶
Log a message with automatic redaction of sensitive data.
The message is first formatted with args
(printf-style) and only then
passed through the redactor to avoid leaking secrets via formatting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logger
|
Logger
|
Target logger. |
required |
level
|
int
|
Logging level (e.g., |
required |
message
|
str
|
Format string. |
required |
*args
|
Any
|
Arguments for printf-style substitution. |
()
|
Source code in src/mlflow_secrets_auth/utils.py
setup_logger(name)
¶
Create or configure a namespaced logger.
The logger level is always driven by the MLFLOW_SECRETS_LOG_LEVEL
env var.
A single stream handler is attached once; propagation is disabled to avoid
duplicated messages under test runners or frameworks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Logger name (typically package.module). |
required |
Returns:
Type | Description |
---|---|
Logger
|
A configured |
Source code in src/mlflow_secrets_auth/utils.py
validate_ttl(ttl_seconds, *, default=DEFAULT_TTL_SECONDS, min_ttl=MIN_TTL_SECONDS, max_ttl=MAX_TTL_SECONDS)
¶
Validate and clamp a TTL value.
Rules
- If
ttl_seconds
is None or <= 0, usedefault
. - Clamp the final value between
min_ttl
andmax_ttl
(inclusive).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ttl_seconds
|
int | None
|
Requested TTL in seconds. |
required |
default
|
int
|
Fallback TTL when input is invalid or not provided. |
DEFAULT_TTL_SECONDS
|
min_ttl
|
int
|
Minimum allowed TTL (inclusive). |
MIN_TTL_SECONDS
|
max_ttl
|
int
|
Maximum allowed TTL (inclusive). |
MAX_TTL_SECONDS
|
Returns:
Type | Description |
---|---|
int
|
A valid TTL in seconds. |