mlflow_secrets_auth
mlflow_secrets_auth
¶
MLflow Secrets-Backed RequestAuthProvider.
Public API
- SecretsAuthProviderFactory: Factory provider that delegates to the first enabled backend among Vault, AWS Secrets Manager, and Azure Key Vault.
- version: Package version string (best-effort).
This module also exposes a best-effort __version__
so the CLI info
command
can display a version even in editable installs where distribution metadata
may be unavailable.
SecretsAuthProviderFactory()
¶
Bases: SecretsBackedAuthProvider
Factory that selects and delegates to an enabled provider.
Priority order
1) HashiCorp Vault 2) AWS Secrets Manager 3) Azure Key Vault
If no provider is enabled or instantiation fails, this factory behaves as "disabled" (e.g., returns defaults/None) while preserving MLflow semantics.
Attributes:
Name | Type | Description |
---|---|---|
_actual_provider |
SecretsBackedAuthProvider | None
|
The lazily-instantiated concrete provider, if any. |
Initialize the factory with a default TTL.
Source code in src/mlflow_secrets_auth/__init__.py
base
¶
Base classes and abstractions for MLflow secrets-backed authentication providers.
This module defines
- Lightweight
requests.auth.AuthBase
implementations for Bearer, Basic, and custom-header auth. SecretsBackedAuthProvider
, an abstract base for MLflowRequestAuthProvider
s that obtain credentials from secret managers and cache them with a TTL.
Design notes
- Providers implement
_fetch_secret
,_get_cache_key
,_get_auth_mode
, and_get_ttl
. - Caching is delegated to
cached_fetch
and TTL validation tovalidate_ttl
. - Secrets are parsed centrally via
parse_secret_json
and must resolve to either:- {"token": "
"} OR - {"username": "...", "password": "..."}
- {"token": "
- Header name can be configured; "Authorization" is normalized to the canonical header.
All logging goes through safe_log
to avoid leaking sensitive values.
BasicAuth(username, password, header_name=DEFAULT_AUTH_HEADER)
¶
Bases: AuthBase
HTTP Basic authentication for requests
.
If a non-standard header is configured, the base64 credentials are put into that header.
Attributes:
Name | Type | Description |
---|---|---|
username |
Basic auth username. |
|
password |
Basic auth password. |
|
header_name |
Target header (defaults to "Authorization"). |
Initialize basic authentication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
username
|
str
|
Username for basic auth. |
required |
password
|
str
|
Password for basic auth. |
required |
header_name
|
str
|
HTTP header to inject (defaults to "Authorization"). |
DEFAULT_AUTH_HEADER
|
Source code in src/mlflow_secrets_auth/base.py
__call__(r)
¶
Attach the basic auth header to the outgoing request.
Source code in src/mlflow_secrets_auth/base.py
BearerAuth(token, header_name=DEFAULT_AUTH_HEADER)
¶
Bases: AuthBase
Bearer token authentication for requests
.
The token is injected as: <header_name>: Bearer <token>
Attributes:
Name | Type | Description |
---|---|---|
token |
Opaque bearer token. |
|
header_name |
Target header (defaults to "Authorization"). |
Initialize bearer authentication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token
|
str
|
Bearer token string. |
required |
header_name
|
str
|
HTTP header to inject (defaults to "Authorization"). |
DEFAULT_AUTH_HEADER
|
Source code in src/mlflow_secrets_auth/base.py
__call__(r)
¶
Attach the bearer token header to the outgoing request.
CustomHeaderAuth(token, header_name)
¶
Bases: AuthBase
Custom header authentication for requests
(token placed as-is).
Attributes:
Name | Type | Description |
---|---|---|
token |
Opaque token to inject. |
|
header_name |
Target header. |
Initialize custom header authentication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token
|
str
|
Token value to inject directly. |
required |
header_name
|
str
|
Header name where the token is placed. |
required |
Source code in src/mlflow_secrets_auth/base.py
__call__(r)
¶
SecretData
¶
Bases: TypedDict
Structured representation of parsed secret material.
SecretsBackedAuthProvider(provider_name, default_ttl=DEFAULT_TTL_SECONDS)
¶
Bases: RequestAuthProvider
, ABC
Abstract base class for secrets-backed MLflow auth providers.
Subclasses implement secret retrieval for a specific backend (e.g., Vault, AWS, Azure) and supply configuration inputs (cache key, auth mode, TTL).
This class handles
- Provider enablement checks.
- Host allowlisting for
get_request_auth
. - Cache + TTL validation.
- Secret parsing and Auth object construction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
provider_name
|
str
|
Stable identifier used for logging and configuration. |
required |
default_ttl
|
int
|
Fallback TTL in seconds if configured TTL is invalid. |
DEFAULT_TTL_SECONDS
|
Attributes:
Name | Type | Description |
---|---|---|
provider_name |
Provider identifier. |
|
default_ttl |
Default TTL for cache. |
|
logger |
Namespaced logger instance. |
Initialize the provider base.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
provider_name
|
str
|
Identifier of the provider (e.g., "vault"). |
required |
default_ttl
|
int
|
Default cache TTL in seconds. |
DEFAULT_TTL_SECONDS
|
Source code in src/mlflow_secrets_auth/base.py
get_auth()
¶
Return a requests
Auth object (no URL filtering).
This method is used by MLflow when a per-request URL is not available.
Returns:
Type | Description |
---|---|
AuthBase | None
|
A |
Source code in src/mlflow_secrets_auth/base.py
get_name()
¶
Return the provider name (instance method in recent MLflow versions).
Returns:
Type | Description |
---|---|
str
|
Provider name for MLflow plugin discovery. |
get_request_auth(url)
¶
Return a requests
Auth object for a given MLflow request URL.
Applies host allowlisting to avoid credential leakage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url
|
str
|
Full request URL for an MLflow call. |
required |
Returns:
Type | Description |
---|---|
AuthBase | None
|
A |
Source code in src/mlflow_secrets_auth/base.py
cache
¶
TTL cache implementation for secrets.
Provides a lightweight, thread-safe cache with monotonic-clock-based TTLs and a
simple decorator (cached_fetch
) to memoize zero-argument callables.
Design goals
- Monotonic time to avoid issues when the wall clock changes.
- Thread safety via
RLock
. - No caching of failures: exceptions from the wrapped callable return
None
and are not stored. - Global cache instance for convenience, with helpers to clear and inspect size.
TTLCache()
¶
Thread-safe TTL cache (monotonic-clock based).
Initialize an empty TTL cache with thread safety.
Source code in src/mlflow_secrets_auth/cache.py
clear()
¶
delete(key)
¶
Remove a key from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Cache key to remove. |
required |
get(key)
¶
Get a value from the cache if present and not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Cache key. |
required |
Returns:
Type | Description |
---|---|
Any | None
|
The cached value if present and valid, otherwise None. |
Source code in src/mlflow_secrets_auth/cache.py
invalidate_prefix(prefix)
¶
Remove all keys starting with a prefix.
Useful for provider-wide invalidation using e.g. f"{provider_name}:"
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prefix
|
str
|
Prefix to match. |
required |
Source code in src/mlflow_secrets_auth/cache.py
set(key, value, ttl_seconds)
¶
Set a value in the cache with a TTL.
Non-positive or sub-minimum TTLs are treated as "no caching" (the key is removed). TTLs larger than MAX_TTL_SECONDS are capped.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Cache key. |
required |
value
|
Any
|
Value to store. |
required |
ttl_seconds
|
float
|
Time-to-live in seconds. |
required |
Source code in src/mlflow_secrets_auth/cache.py
size()
¶
Return the current cache size, pruning expired entries first.
Returns:
Type | Description |
---|---|
int
|
Number of live (non-expired) entries. |
Source code in src/mlflow_secrets_auth/cache.py
cached_fetch(cache_key, ttl_seconds=DEFAULT_TTL_SECONDS)
¶
Cache a zero-argument function's result with a TTL.
Exceptions raised by the wrapped function are swallowed and result in None
,
which is not cached. Successful non-None results are cached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cache_key
|
str
|
Unique cache key for the function result. |
required |
ttl_seconds
|
int
|
Time-to-live for the cached value. |
DEFAULT_TTL_SECONDS
|
Returns:
Type | Description |
---|---|
Callable[[Callable[[], T]], Callable[[], T | None]]
|
A decorator that wraps a |
Source code in src/mlflow_secrets_auth/cache.py
clear_cache()
¶
delete_cache_key(key)
¶
Remove a single cache entry by key.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
Cache key to remove. |
required |
cli
¶
Command-line interface (CLI) for MLflow Secrets Auth.
Subcommands
- info - Show version, enabled providers, and configuration snapshot.
- doctor - Run diagnostics against the configured provider.
doctor_command(args)
¶
Run diagnostics against the configured provider.
Steps
1) Resolve enabled provider. 2) Validate provider configuration (auth mode, TTL, header). 3) Fetch secret and construct an auth object. 4) Optional dry-run: issue a HEAD request to the given URL's origin.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
Namespace
|
Parsed CLI args (supports |
required |
Returns:
Type | Description |
---|---|
int
|
Process exit code (0 on success, non-zero on error). |
Source code in src/mlflow_secrets_auth/cli.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
|
get_enabled_provider()
¶
Return the first enabled provider as (name, instance), or (None, None).
Returns:
Type | Description |
---|---|
ProviderTuple
|
Tuple of provider name and instance, or (None, None) if none enabled. |
Source code in src/mlflow_secrets_auth/cli.py
info_command(_)
¶
Show plugin version and configuration snapshot.
Returns:
Type | Description |
---|---|
int
|
Process exit code (0 on success, non-zero on error). |
Source code in src/mlflow_secrets_auth/cli.py
main()
¶
Run the CLI entry point.
Returns:
Type | Description |
---|---|
int
|
Process exit code (0 on success, non-zero on error). |
Source code in src/mlflow_secrets_auth/cli.py
config
¶
Configuration utilities for MLflow secrets auth providers.
This module centralizes environment-driven configuration and safe redaction helpers.
Key env vars
- MLFLOW_SECRETS_ALLOWED_HOSTS: Comma-separated host allowlist.
- MLFLOW_AUTH_HEADER_NAME: Custom header for auth (defaults to "Authorization").
- MLFLOW_SECRETS_LOG_LEVEL: Logging level (defaults to "INFO").
- MLFLOW_SECRETS_AUTH_ENABLE: Comma-separated list of enabled providers.
- MLFLOW_SECRETS_AUTH_ENABLE_
: Per-provider boolean toggle (e.g., AWS_SECRETS_MANAGER).
get_allowed_hosts()
¶
Return the host allowlist from MLFLOW_SECRETS_ALLOWED_HOSTS.
Supports both exact hostnames and wildcard patterns using shell-style globbing.
Examples:
MLFLOW_SECRETS_ALLOWED_HOSTS="mlflow.example.com,.corp.example.com" MLFLOW_SECRETS_ALLOWED_HOSTS="api.prod.com,.staging.com,localhost"
Wildcard patterns
- "*.corp.example.com" matches any subdomain of corp.example.com
- "mlflow.*.com" matches mlflow with any middle component
- "api-*" matches hostnames starting with "api-"
Returns:
Type | Description |
---|---|
list[str] | None
|
A list of hostname patterns, or None if not configured. |
Source code in src/mlflow_secrets_auth/config.py
get_auth_header_name()
¶
Return the configured auth header name.
Defaults to "Authorization" when MLFLOW_AUTH_HEADER_NAME is unset.
Returns:
Type | Description |
---|---|
str
|
Header name as a string. |
Source code in src/mlflow_secrets_auth/config.py
get_env_bool(name, default=False)
¶
Return an environment variable parsed as a boolean.
Recognized truthy values (case-insensitive): {"1", "true", "yes", "on"}.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Environment variable name. |
required |
default
|
bool
|
Fallback when the variable is unset. |
False
|
Returns:
Type | Description |
---|---|
bool
|
Parsed boolean value. |
Source code in src/mlflow_secrets_auth/config.py
get_env_int(name, default)
¶
Return an environment variable parsed as int.
On parsing error or if unset, returns default
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Environment variable name. |
required |
default
|
int
|
Fallback value. |
required |
Returns:
Type | Description |
---|---|
int
|
Parsed integer or |
Source code in src/mlflow_secrets_auth/config.py
get_env_var(name, default=None)
¶
Return an environment variable or a default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Environment variable name. |
required |
default
|
str | None
|
Value to return if not set. |
None
|
Returns:
Type | Description |
---|---|
str | None
|
The environment value as a string, or |
Source code in src/mlflow_secrets_auth/config.py
get_log_level()
¶
Return the configured log level for secrets auth.
Defaults to "INFO" and uppercases the value for consistency.
Returns:
Type | Description |
---|---|
str
|
Uppercased logging level string (e.g., "INFO", "DEBUG"). |
Source code in src/mlflow_secrets_auth/config.py
is_provider_enabled(provider_name)
¶
Return whether a specific provider is enabled.
Two mechanisms
1) Global list: MLFLOW_SECRETS_AUTH_ENABLE="vault,aws-secrets-manager,azure-key-vault"
2) Per-provider boolean: MLFLOW_SECRETS_AUTH_ENABLE_
Parameters:
Name | Type | Description | Default |
---|---|---|---|
provider_name
|
str
|
Provider slug (case-insensitive), e.g. "vault". |
required |
Returns:
Type | Description |
---|---|
bool
|
True if enabled via either mechanism, False otherwise. |
Source code in src/mlflow_secrets_auth/config.py
mask_secret(value, mask_char=DEFAULT_MASK_CHAR, show_chars=DEFAULT_SHOW_CHARS)
¶
Mask a secret value for safe logging.
Examples:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
str
|
Secret value to mask. |
required |
mask_char
|
str
|
Masking character (default '*'). |
DEFAULT_MASK_CHAR
|
show_chars
|
int
|
Number of leading and trailing chars to keep (default 4). |
DEFAULT_SHOW_CHARS
|
Returns:
Type | Description |
---|---|
str
|
Masked representation with the center portion obfuscated. |
Source code in src/mlflow_secrets_auth/config.py
redact_sensitive_data(text)
¶
Redact common credential patterns from text.
Safely handles patterns with different group counts. Intended for logs and messages.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
Input string possibly containing sensitive material. |
required |
Returns:
Type | Description |
---|---|
str
|
Redacted string with secrets masked. |
Source code in src/mlflow_secrets_auth/config.py
constants
¶
Constants for MLflow Secrets Auth.
This module centralizes all configuration constants, environment variable names, default values, and magic strings used throughout the project.
messages
¶
User-facing messages for MLflow Secrets Auth.
This module centralizes all user-facing messages including CLI output, error messages, log messages, and help text.
providers
¶
Empty file to make providers a package.
aws_secrets_manager
¶
AWS Secrets Manager authentication provider.
AWSSecretsManagerAuthProvider()
¶
Bases: SecretsBackedAuthProvider
Authentication provider using AWS Secrets Manager.
Requires the optional dependency boto3
.
Environment variables
AWS_REGION: AWS region (e.g., "eu-west-1"). Required. MLFLOW_AWS_SECRET_ID: Secret identifier or ARN. Required. MLFLOW_AWS_AUTH_MODE: "bearer" (default) or "basic". MLFLOW_AWS_TTL_SEC: Cache TTL in seconds (defaults to provider's default TTL).
Initialize the provider with a default TTL and lazy AWS client.
Source code in src/mlflow_secrets_auth/providers/aws_secrets_manager.py
azure_key_vault
¶
Azure Key Vault authentication provider.
AzureKeyVaultAuthProvider()
¶
Bases: SecretsBackedAuthProvider
Authentication provider using Azure Key Vault.
Requires optional dependencies: azure-identity
and azure-keyvault-secrets
.
Environment variables
AZURE_KEY_VAULT_URL: Full Key Vault URL (e.g., "https://myvault.vault.azure.net"). Required. MLFLOW_AZURE_SECRET_NAME: Secret name to retrieve. Required. MLFLOW_AZURE_AUTH_MODE: "bearer" (default) or "basic". MLFLOW_AZURE_TTL_SEC: Cache TTL in seconds (defaults to provider's default TTL).
Initialize the provider with a default TTL and a lazy SecretClient.
Source code in src/mlflow_secrets_auth/providers/azure_key_vault.py
vault
¶
HashiCorp Vault authentication provider.
VaultAuthProvider()
¶
Bases: SecretsBackedAuthProvider
Authentication provider using HashiCorp Vault.
Supports token and AppRole authentication via the hvac
client (optional dependency).
Secrets are retrieved from KV v2 when possible with a graceful fallback to KV v1.
Environment variables
VAULT_ADDR: Vault server address, e.g. "https://vault.example.com" VAULT_TOKEN: Vault token for direct authentication (optional). VAULT_ROLE_ID: AppRole role ID (used if VAULT_TOKEN is not provided). VAULT_SECRET_ID: AppRole secret ID (used if VAULT_TOKEN is not provided). MLFLOW_VAULT_SECRET_PATH: Secret path (e.g. "secret/mlflow/auth" or "secret/data/mlflow/auth"). MLFLOW_VAULT_AUTH_MODE: "bearer" (default) or "basic". MLFLOW_VAULT_TTL_SEC: Cache TTL in seconds (defaults to provider's default TTL).
Notes
- When using KV v2, this implementation auto-detects common path formats and
reads via
client.secrets.kv.v2.read_secret_version
. - For KV v1, it falls back to
client.secrets.kv.v1.read_secret
. - Secret dictionaries are JSON-encoded for centralized parsing in the base class.
Initialize the provider with a default TTL and a lazy hvac client.
Source code in src/mlflow_secrets_auth/providers/vault.py
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. |