mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-29 01:03:17 +00:00
* test(secret_managers): cover oidc/google api_key references resolved per request Unit tests send a metadata server ID token for an admin oidc/google/<audience> api_key, reuse it within its lifetime, refresh it before it expires, fetch it off the event loop, fail closed with a 401 that names only the kind, and honor GCE_METADATA_HOST. The integration file scripts a metadata server and checks the bearer the upstream receives for config, stored credential and DB credential sources, plus a metadata failure * feat(secret_managers): resolve oidc/google api_key references per request An admin-set oidc/google/<audience> api_key now resolves on each call to the GCE metadata server's ID token for that audience, cached until a minute before it expires. Async callers fetch on a cache miss in a worker thread, so the event loop never waits on the metadata server. A failed fetch answers 401 naming only the kind, and GCE_METADATA_HOST points the fetch at another metadata server. * fix(oidc): bound the Google metadata fetch and answer 503 when it fails A Google OIDC api_key fetch now waits at most GCE_METADATA_TIMEOUT seconds (default 3), runs on its own thread pool instead of the loop's default executor, and sends the token read from the cache at call start even if it expires mid-call. A metadata timeout, network error, or 5xx answers a retryable 503, while a 4xx or empty token stays a 401. The expiry and empty-token warnings log the secret name on one line. * test(oidc): expect 503 when the metadata server answers 5xx in the integration test * fix(oidc): answer 503 on token-count routes during a metadata outage and fall back on a bad GCE_METADATA_TIMEOUT * fix(secret_managers): keep get_secret's metadata wait, share concurrent google token fetches, refuse oidc/google on pass-through A model's api_key fetch keeps the 3 second GCE_METADATA_TIMEOUT wait while get_secret callers keep the handler default. Any metadata transport error answers a retryable 503. Async cache misses for one reference share one fetch, and a call the reference may not go to is refused before any fetch. Pass-through routes answer 401 for an oidc/google credential instead of sending the reference text. The metadata client is closed after each fetch, and the unused sync resolver is removed. * fix(utils): refuse an oidc/google api_key on pass-through calls before any fetch A router-model or credential-name pass-through call with an oidc/google reference now fails before the metadata fetch and sends nothing upstream, since the pass-through config never sends the resolved key. The single-flight test also waits on the fetch-start signal with a bounded window instead of a fixed sleep.
541 lines
21 KiB
Python
541 lines
21 KiB
Python
import ast
|
|
import base64
|
|
import os
|
|
import time
|
|
import traceback
|
|
from collections.abc import Callable
|
|
from dataclasses import dataclass
|
|
from typing import Final, TypeAlias
|
|
|
|
import httpx
|
|
from pydantic import TypeAdapter, ValidationError
|
|
|
|
import litellm
|
|
from litellm._logging import verbose_logger
|
|
from litellm.caching.caching import DualCache
|
|
from litellm.litellm_core_utils.env_utils import get_env_float
|
|
from litellm.litellm_core_utils.single_flight import single_flight_lru_cache
|
|
from litellm.llms.custom_httpx.http_handler import HTTPHandler
|
|
from litellm.secret_managers.get_azure_ad_token_provider import (
|
|
get_azure_ad_token_provider,
|
|
)
|
|
from litellm.secret_managers.secret_manager_handler import get_secret_from_manager
|
|
from litellm.types.llms.base import LiteLLMBaseModel
|
|
|
|
oidc_cache: Final = DualCache()
|
|
|
|
_PARSED_LITERAL: Final = TypeAdapter(object)
|
|
_SECRET_MANAGER_CLIENT: Final = TypeAdapter(object)
|
|
|
|
|
|
@single_flight_lru_cache
|
|
def _cached_azure_oidc_token_provider(audience: str) -> Callable[[], str]:
|
|
return get_azure_ad_token_provider(azure_scope=audience)
|
|
|
|
|
|
_OIDC_TOKEN_EXPIRY_MARGIN_SECONDS: Final = 60
|
|
|
|
|
|
class _OidcTokenClaims(LiteLLMBaseModel):
|
|
exp: float | None = None
|
|
|
|
|
|
def _oidc_token_cache_ttl(oidc_token: str, max_ttl: int) -> int:
|
|
"""Cache TTL for a fetched OIDC token: ``max_ttl``, capped so the cache entry
|
|
never outlives the token's own ``exp`` claim (minus a safety margin).
|
|
Falls back to ``max_ttl`` when the token carries no readable ``exp``."""
|
|
segments: Final = oidc_token.split(".")
|
|
if len(segments) != 3:
|
|
return max_ttl
|
|
payload: Final = segments[1]
|
|
try:
|
|
decoded: Final = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
|
|
claims: Final = _OidcTokenClaims.model_validate_json(decoded)
|
|
if claims.exp is None:
|
|
return max_ttl
|
|
exp: Final = int(claims.exp)
|
|
except (ValueError, OverflowError, ValidationError):
|
|
return max_ttl
|
|
return min(max_ttl, exp - int(time.time()) - _OIDC_TOKEN_EXPIRY_MARGIN_SECONDS)
|
|
|
|
|
|
_DEFAULT_OIDC_ALLOWED_CREDENTIAL_DIRS: Final = ("/var/run/secrets", "/run/secrets")
|
|
|
|
|
|
class OidcPathNotAllowedError(ValueError):
|
|
"""An ``oidc/file/`` path was rejected by the credential-directory allowlist."""
|
|
|
|
|
|
def _get_oidc_allowed_credential_dirs() -> list[str]:
|
|
"""
|
|
Return the absolute, normalized list of directories from which
|
|
``oidc/file/`` is permitted to read token files.
|
|
|
|
Defaults to standard container credential mount points. Operators can
|
|
override via the ``LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS`` environment
|
|
variable (comma-separated list of absolute paths).
|
|
"""
|
|
override: Final = os.getenv("LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS")
|
|
raw_dirs: Final = (
|
|
[d.strip() for d in override.split(",") if d.strip()]
|
|
if override
|
|
else list(_DEFAULT_OIDC_ALLOWED_CREDENTIAL_DIRS)
|
|
)
|
|
return [os.path.realpath(d) for d in raw_dirs]
|
|
|
|
|
|
def _resolve_oidc_file_path(requested_path: str) -> str:
|
|
"""
|
|
Resolve ``requested_path`` and verify it falls within one of the allowed
|
|
credential directories. Raises ``ValueError`` otherwise.
|
|
"""
|
|
if not os.path.isabs(requested_path):
|
|
raise OidcPathNotAllowedError(
|
|
"oidc/file path must be absolute. Use the format "
|
|
"'oidc/file//<absolute path>' (note the leading slash "
|
|
"after 'oidc/file/')."
|
|
)
|
|
resolved: Final = os.path.realpath(requested_path)
|
|
for allowed in _get_oidc_allowed_credential_dirs():
|
|
try:
|
|
if os.path.commonpath([resolved, allowed]) == allowed:
|
|
return resolved
|
|
except ValueError:
|
|
# commonpath raises when paths are on different drives (Windows);
|
|
# treat as not-matching and continue.
|
|
continue
|
|
raise OidcPathNotAllowedError(
|
|
"oidc/file path is outside the allowed credential directories. "
|
|
"Set LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS to extend the allowlist."
|
|
)
|
|
|
|
|
|
def _get_oidc_http_handler(timeout: httpx.Timeout | None = None) -> HTTPHandler:
|
|
"""
|
|
Factory function to create HTTPHandler for OIDC requests.
|
|
This function can be mocked in tests.
|
|
|
|
Args:
|
|
timeout: Optional timeout for HTTP requests. Defaults to 600.0 seconds with 5.0 connect timeout.
|
|
|
|
Returns:
|
|
HTTPHandler instance configured for OIDC requests.
|
|
"""
|
|
if timeout is None:
|
|
timeout = httpx.Timeout(timeout=600.0, connect=5.0)
|
|
return HTTPHandler(timeout=timeout)
|
|
|
|
|
|
######### Secret Manager ############################
|
|
# checks if user has passed in a secret manager client
|
|
# if passed in then checks the secret there
|
|
def str_to_bool(value: str | None) -> bool | None:
|
|
"""
|
|
Converts a string to a boolean if it's a recognized boolean string.
|
|
Returns None if the string is not a recognized boolean value.
|
|
|
|
:param value: The string to be checked.
|
|
:return: True or False if the string is a recognized boolean, otherwise None.
|
|
"""
|
|
if value is None:
|
|
return None
|
|
|
|
true_values: Final = {"true"}
|
|
false_values: Final = {"false"}
|
|
|
|
value_lower: Final = value.strip().lower()
|
|
|
|
if value_lower in true_values:
|
|
return True
|
|
elif value_lower in false_values:
|
|
return False
|
|
else:
|
|
return None
|
|
|
|
|
|
def get_secret_str(
|
|
secret_name: str,
|
|
default_value: str | bool | None = None,
|
|
) -> str | None:
|
|
"""
|
|
Guarantees response from 'get_secret' is either string or none. Used for fixing linting errors.
|
|
"""
|
|
value: Final = get_secret(secret_name=secret_name, default_value=default_value)
|
|
if value is not None and not isinstance(value, str):
|
|
return None
|
|
|
|
return value
|
|
|
|
|
|
LOCAL_OIDC_SECRET_PREFIXES: Final = ("oidc/file/", "oidc/env/")
|
|
GOOGLE_OIDC_SECRET_PREFIX: Final = "oidc/google/"
|
|
API_KEY_OIDC_SECRET_PREFIXES: Final = (*LOCAL_OIDC_SECRET_PREFIXES, GOOGLE_OIDC_SECRET_PREFIX)
|
|
_GOOGLE_METADATA_DEFAULT_HOST: Final = "metadata.google.internal"
|
|
_GOOGLE_METADATA_DEFAULT_TIMEOUT_SECONDS: Final = 3.0
|
|
_GOOGLE_TOKEN_UNAVAILABLE: Final = "the metadata server did not return an ID token"
|
|
|
|
|
|
def _google_metadata_identity_url() -> str:
|
|
host: Final = os.getenv("GCE_METADATA_HOST") or _GOOGLE_METADATA_DEFAULT_HOST
|
|
return f"http://{host}/computeMetadata/v1/instance/service-accounts/default/identity"
|
|
|
|
|
|
def _google_metadata_timeout() -> float:
|
|
seconds: Final = get_env_float("GCE_METADATA_TIMEOUT", _GOOGLE_METADATA_DEFAULT_TIMEOUT_SECONDS)
|
|
return seconds if seconds > 0 else _GOOGLE_METADATA_DEFAULT_TIMEOUT_SECONDS
|
|
|
|
|
|
class GoogleMetadataStatusError(ValueError):
|
|
def __init__(self, status_code: int) -> None:
|
|
super().__init__(f"Google OIDC provider failed with HTTP {status_code}")
|
|
self.status_code: Final = status_code
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class UnresolvableSecretReference:
|
|
kind: str
|
|
reason: str
|
|
retryable: bool = False
|
|
|
|
|
|
OidcResolver: TypeAlias = Callable[[str], "str | UnresolvableSecretReference"]
|
|
|
|
|
|
_OIDC_PROVIDERS: Final = frozenset({"google", "circleci", "circleci_v2", "github", "azure", "file", "env", "env_path"})
|
|
|
|
|
|
def oidc_reference_kind(reference: str) -> str:
|
|
provider: Final = reference.removeprefix("oidc/").split("/", 1)[0]
|
|
return f"oidc/{provider}" if provider in _OIDC_PROVIDERS else "oidc/<unknown kind>"
|
|
|
|
|
|
def resolve_local_oidc_reference(value: str) -> str | UnresolvableSecretReference:
|
|
"""Only local kinds resolve, since request paths must not do network I/O, and ``oidc/env_path/`` is
|
|
excluded because it bypasses the ``oidc/file/`` credential-directory allowlist."""
|
|
if not value.startswith(LOCAL_OIDC_SECRET_PREFIXES):
|
|
return value
|
|
kind: Final = oidc_reference_kind(value)
|
|
try:
|
|
secret: Final = get_secret_str(value)
|
|
except (OSError, ValueError) as exc:
|
|
return _logged_unresolvable(value, kind, _unresolvable_reason(kind, exc))
|
|
if not secret:
|
|
return _logged_unresolvable(value, kind, "it resolved to an empty value")
|
|
return secret
|
|
|
|
|
|
def resolve_api_key_oidc_reference(value: str) -> str | UnresolvableSecretReference:
|
|
if not value.startswith(GOOGLE_OIDC_SECRET_PREFIX):
|
|
return resolve_local_oidc_reference(value)
|
|
try:
|
|
token: Final = _google_id_token(
|
|
value, value.removeprefix(GOOGLE_OIDC_SECRET_PREFIX), timeout=_google_metadata_timeout()
|
|
)
|
|
except (httpx.HTTPError, httpx.InvalidURL, ValueError) as exc:
|
|
return _logged_unresolvable(
|
|
value,
|
|
"oidc/google",
|
|
_GOOGLE_TOKEN_UNAVAILABLE,
|
|
f"{type(exc).__name__}: {exc}",
|
|
retryable=_metadata_server_failed_to_answer(exc),
|
|
)
|
|
if not token:
|
|
return _logged_unresolvable(value, "oidc/google", "it resolved to an empty value")
|
|
return token
|
|
|
|
|
|
def _metadata_server_failed_to_answer(exc: httpx.HTTPError | httpx.InvalidURL | ValueError) -> bool:
|
|
match exc:
|
|
case httpx.TransportError():
|
|
return True
|
|
case GoogleMetadataStatusError(status_code=status_code):
|
|
return status_code >= 500
|
|
case _:
|
|
return False
|
|
|
|
|
|
def _google_id_token(reference: str, audience: str, timeout: float | None) -> str:
|
|
cached: Final = cached_oidc_token(reference)
|
|
if cached is not None:
|
|
return cached
|
|
oidc_client: Final = _get_oidc_http_handler()
|
|
try:
|
|
# https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
|
|
response: Final = oidc_client.get(
|
|
_google_metadata_identity_url(),
|
|
params={"audience": audience},
|
|
headers={"Metadata-Flavor": "Google"},
|
|
timeout=timeout,
|
|
)
|
|
finally:
|
|
oidc_client.close()
|
|
if response.status_code != 200:
|
|
raise GoogleMetadataStatusError(response.status_code)
|
|
token: Final = response.text
|
|
ttl: Final = _oidc_token_cache_ttl(token, 3600 - 60)
|
|
if not token:
|
|
verbose_logger.warning("Google OIDC token for %s is empty; not caching it", _single_line(reference))
|
|
elif ttl > 0:
|
|
oidc_cache.set_cache(key=reference, value=token, ttl=ttl)
|
|
else:
|
|
verbose_logger.warning(
|
|
"Google OIDC token for %s is already expired or expires within %ss; not caching it",
|
|
_single_line(reference),
|
|
_OIDC_TOKEN_EXPIRY_MARGIN_SECONDS,
|
|
)
|
|
return token
|
|
|
|
|
|
def cached_oidc_token(reference: str) -> str | None:
|
|
cached: Final = oidc_cache.get_cache(key=reference) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] # DualCache.get_cache is untyped
|
|
return cached if isinstance(cached, str) and cached else None
|
|
|
|
|
|
def _logged_unresolvable(
|
|
reference: str, kind: str, reason: str, detail: str | None = None, retryable: bool = False
|
|
) -> UnresolvableSecretReference:
|
|
verbose_logger.warning(
|
|
"Secret reference %s could not be resolved: %s",
|
|
_single_line(reference),
|
|
reason if detail is None else f"{reason} ({_single_line(detail)})",
|
|
)
|
|
return UnresolvableSecretReference(kind=kind, reason=reason, retryable=retryable)
|
|
|
|
|
|
def _single_line(text: str) -> str:
|
|
return text.replace("\r", "").replace("\n", "")
|
|
|
|
|
|
def _unresolvable_reason(kind: str, exc: OSError | ValueError) -> str:
|
|
match exc:
|
|
case UnicodeDecodeError():
|
|
return "the file is not UTF-8 text"
|
|
case OidcPathNotAllowedError():
|
|
return str(exc)
|
|
case OSError(strerror=str() as strerror):
|
|
return strerror
|
|
case _ if kind == "oidc/env":
|
|
return "the environment variable is not set"
|
|
case _:
|
|
return "the file could not be read"
|
|
|
|
|
|
def normalize_nonempty_secret_str(val: str | None) -> str | None:
|
|
"""
|
|
Strip whitespace and treat None, '', and whitespace-only strings as unset.
|
|
|
|
Use when pairing secrets (mutual exclusion, optional auth) so whitespace-only
|
|
values do not count as present.
|
|
"""
|
|
if val is None:
|
|
return None
|
|
stripped: Final = val.strip()
|
|
return stripped if stripped else None
|
|
|
|
|
|
def get_secret_bool(
|
|
secret_name: str,
|
|
default_value: bool | None = None,
|
|
) -> bool | None:
|
|
"""
|
|
Guarantees response from 'get_secret' is either boolean or none. Used for fixing linting errors.
|
|
|
|
Args:
|
|
secret_name: The name of the secret to get.
|
|
default_value: The default value to return if the secret is not found.
|
|
|
|
Returns:
|
|
The secret value as a boolean or None if the secret is not found.
|
|
"""
|
|
_secret_value: Final = get_secret(secret_name, default_value)
|
|
if _secret_value is None:
|
|
return None
|
|
elif isinstance(_secret_value, bool):
|
|
return _secret_value
|
|
else:
|
|
return str_to_bool(_secret_value)
|
|
|
|
|
|
def get_secret(
|
|
secret_name: str,
|
|
default_value: str | bool | None = None,
|
|
):
|
|
key_management_system: Final = litellm._key_management_system
|
|
key_management_settings: Final = litellm._key_management_settings
|
|
secret = None
|
|
|
|
if secret_name.startswith("os.environ/"):
|
|
secret_name = secret_name.replace("os.environ/", "")
|
|
|
|
# Example: oidc/google/https://bedrock-runtime.us-east-1.amazonaws.com/model/stability.stable-diffusion-xl-v1/invoke
|
|
if secret_name.startswith("oidc/"):
|
|
secret_name_split: Final = secret_name.removeprefix("oidc/")
|
|
oidc_provider, oidc_aud = secret_name_split.split("/", 1)
|
|
oidc_aud = "/".join(secret_name_split.split("/")[1:])
|
|
# TODO: Add caching for HTTP requests
|
|
if oidc_provider == "google":
|
|
return _google_id_token(secret_name, oidc_aud, timeout=None)
|
|
elif oidc_provider == "circleci":
|
|
# https://circleci.com/docs/openid-connect-tokens/
|
|
env_secret = os.getenv("CIRCLE_OIDC_TOKEN")
|
|
if env_secret is None:
|
|
raise ValueError("CIRCLE_OIDC_TOKEN not found in environment")
|
|
return env_secret
|
|
elif oidc_provider == "circleci_v2":
|
|
# https://circleci.com/docs/openid-connect-tokens/
|
|
env_secret = os.getenv("CIRCLE_OIDC_TOKEN_V2")
|
|
if env_secret is None:
|
|
raise ValueError("CIRCLE_OIDC_TOKEN_V2 not found in environment")
|
|
return env_secret
|
|
elif oidc_provider == "github":
|
|
# https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-cloud-providers#using-custom-actions
|
|
actions_id_token_request_url: Final = os.getenv("ACTIONS_ID_TOKEN_REQUEST_URL")
|
|
actions_id_token_request_token: Final = os.getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
|
|
if actions_id_token_request_url is None or actions_id_token_request_token is None:
|
|
raise ValueError(
|
|
"ACTIONS_ID_TOKEN_REQUEST_URL or ACTIONS_ID_TOKEN_REQUEST_TOKEN not found in environment"
|
|
)
|
|
|
|
oidc_token = oidc_cache.get_cache(key=secret_name)
|
|
if oidc_token is not None:
|
|
return oidc_token
|
|
|
|
oidc_client = _get_oidc_http_handler()
|
|
response = oidc_client.get(
|
|
actions_id_token_request_url,
|
|
params={"audience": oidc_aud},
|
|
headers={
|
|
"Authorization": f"Bearer {actions_id_token_request_token}",
|
|
"Accept": "application/json; api-version=2.0",
|
|
},
|
|
)
|
|
if response.status_code == 200:
|
|
oidc_token = response.json().get("value", None)
|
|
oidc_cache.set_cache(key=secret_name, value=oidc_token, ttl=300 - 5)
|
|
return oidc_token
|
|
else:
|
|
raise ValueError("Github OIDC provider failed")
|
|
elif oidc_provider == "azure":
|
|
# https://azure.github.io/azure-workload-identity/docs/quick-start.html
|
|
azure_federated_token_file: Final = os.getenv("AZURE_FEDERATED_TOKEN_FILE")
|
|
if azure_federated_token_file is None:
|
|
verbose_logger.warning(
|
|
"AZURE_FEDERATED_TOKEN_FILE not found in environment will use Azure AD token provider"
|
|
)
|
|
azure_token_provider: Final = _cached_azure_oidc_token_provider(oidc_aud)
|
|
try:
|
|
oidc_token = azure_token_provider()
|
|
if oidc_token is None:
|
|
raise ValueError("Azure OIDC provider returned None token")
|
|
return oidc_token
|
|
except Exception as e:
|
|
error_msg: Final = f"Azure OIDC provider failed: {e}"
|
|
verbose_logger.error(error_msg)
|
|
raise ValueError(error_msg)
|
|
with open(azure_federated_token_file, "r") as f:
|
|
oidc_token = f.read()
|
|
return oidc_token
|
|
elif oidc_provider == "file":
|
|
# Load token from a file within an allowed credential directory.
|
|
safe_path: Final = _resolve_oidc_file_path(oidc_aud)
|
|
with open(safe_path, "r") as f:
|
|
oidc_token = f.read()
|
|
return oidc_token
|
|
elif oidc_provider == "env":
|
|
# Load token directly from an environment variable
|
|
oidc_token = os.getenv(oidc_aud)
|
|
if oidc_token is None:
|
|
raise ValueError(f"Environment variable {oidc_aud} not found")
|
|
return oidc_token
|
|
elif oidc_provider == "env_path":
|
|
# Load token from a file path specified in an environment variable
|
|
token_file_path: Final = os.getenv(oidc_aud)
|
|
if token_file_path is None:
|
|
raise ValueError(f"Environment variable {oidc_aud} not found")
|
|
with open(token_file_path, "r") as f:
|
|
oidc_token = f.read()
|
|
return oidc_token
|
|
else:
|
|
raise ValueError("Unsupported OIDC provider")
|
|
|
|
try:
|
|
if _should_read_secret_from_secret_manager() and litellm.secret_manager_client is not None:
|
|
try:
|
|
client: Final = _SECRET_MANAGER_CLIENT.validate_python(litellm.secret_manager_client)
|
|
key_manager = "local"
|
|
if key_management_system is not None:
|
|
key_manager = key_management_system.value
|
|
|
|
if key_management_settings is not None:
|
|
if (
|
|
key_management_settings.hosted_keys is not None
|
|
and secret_name not in key_management_settings.hosted_keys
|
|
): # allow user to specify which keys to check in hosted key manager
|
|
key_manager = "local"
|
|
|
|
# Delegate to the secret manager handler
|
|
secret = get_secret_from_manager(
|
|
client=client,
|
|
key_manager=key_manager,
|
|
secret_name=secret_name,
|
|
key_management_settings=key_management_settings,
|
|
)
|
|
except Exception as e: # check if it's in os.environ
|
|
verbose_logger.error(
|
|
"Defaulting to os.environ value for key=%s. An exception occurred - %s.\n\n%s",
|
|
secret_name,
|
|
e,
|
|
traceback.format_exc(),
|
|
)
|
|
secret = os.getenv(secret_name)
|
|
try:
|
|
if isinstance(secret, str):
|
|
secret_value_as_bool = _PARSED_LITERAL.validate_python(ast.literal_eval(secret))
|
|
if isinstance(secret_value_as_bool, bool):
|
|
return secret_value_as_bool
|
|
else:
|
|
return secret
|
|
except Exception:
|
|
return secret
|
|
else:
|
|
secret = os.environ.get(secret_name)
|
|
secret_value_as_bool = str_to_bool(secret) if secret is not None else None
|
|
if secret_value_as_bool is not None and isinstance(secret_value_as_bool, bool):
|
|
return secret_value_as_bool
|
|
else:
|
|
return secret
|
|
except Exception as e:
|
|
if default_value is not None:
|
|
return default_value
|
|
else:
|
|
raise e
|
|
|
|
|
|
def secret_manager_would_be_consulted(secret_name: str) -> bool:
|
|
"""
|
|
Returns True if a `get_secret` read for `secret_name` would actually reach the hosted manager.
|
|
|
|
Mirrors the gating `get_secret` applies below: the manager has to be up and readable, and
|
|
`hosted_keys`, when set, is an allowlist of the names it is consulted for. Callers use this to
|
|
tell "the manager does not have this key" apart from "the manager was never asked".
|
|
"""
|
|
if not _should_read_secret_from_secret_manager():
|
|
return False
|
|
key_management_settings: Final = litellm._key_management_settings
|
|
if key_management_settings is None or key_management_settings.hosted_keys is None:
|
|
return True
|
|
return secret_name.removeprefix("os.environ/") in key_management_settings.hosted_keys
|
|
|
|
|
|
def _should_read_secret_from_secret_manager() -> bool:
|
|
"""
|
|
Returns True if the secret manager should be used to read the secret, False otherwise
|
|
|
|
- If the secret manager client is not set, return False
|
|
- If the `_key_management_settings` access mode is "read_only" or "read_and_write", return True
|
|
- Otherwise, return False
|
|
"""
|
|
key_management_settings: Final = litellm._key_management_settings
|
|
if litellm.secret_manager_client is None or key_management_settings is None:
|
|
return False
|
|
return key_management_settings.access_mode in ("read_only", "read_and_write")
|