mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-04 01:48:57 +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.
581 lines
21 KiB
Python
581 lines
21 KiB
Python
import base64
|
|
import json
|
|
import logging
|
|
import os
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from collections.abc import Callable
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from queue import SimpleQueue
|
|
from typing import Final
|
|
from unittest.mock import Mock, patch
|
|
|
|
import pytest
|
|
import respx
|
|
|
|
import litellm
|
|
from litellm._logging import redact_internal_details_from_client_message
|
|
from litellm.integrations.custom_secret_manager import CustomSecretManager
|
|
from litellm.secret_managers.main import (
|
|
_cached_azure_oidc_token_provider,
|
|
get_secret,
|
|
normalize_nonempty_secret_str,
|
|
resolve_local_oidc_reference,
|
|
secret_manager_would_be_consulted,
|
|
)
|
|
from litellm.types.secret_managers.main import KeyManagementSettings, KeyManagementSystem
|
|
|
|
# Set up logging for debugging
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
# Mock HTTPHandler and oidc_cache
|
|
class MockHTTPHandler:
|
|
def __init__(self, timeout):
|
|
self.timeout = timeout
|
|
self.status_code = 200
|
|
self.text = "mocked_token"
|
|
self.json_data = {"value": "mocked_token"}
|
|
|
|
def get(self, url, params=None, headers=None, timeout=None):
|
|
# Store params for audience verification
|
|
self.last_params = params
|
|
logger.debug(
|
|
f"MockHTTPHandler.get called with url={url}, params={params}, headers={headers}"
|
|
)
|
|
mock_response = Mock()
|
|
mock_response.status_code = self.status_code
|
|
mock_response.text = self.text
|
|
mock_response.json.return_value = self.json_data
|
|
return mock_response
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_oidc_cache():
|
|
cache = Mock()
|
|
cache.get_cache.return_value = None
|
|
cache.set_cache = Mock()
|
|
return cache
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_env():
|
|
with patch.dict(os.environ, {}, clear=True):
|
|
yield os.environ
|
|
|
|
|
|
def test_oidc_google_success():
|
|
"""Test Google OIDC token fetch with mocked handler (no real network calls)."""
|
|
secret_name = "oidc/google/[invalid url, do not cite]"
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_get_http_handler = Mock(return_value=mock_handler)
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
with patch(
|
|
"litellm.secret_managers.main.HTTPHandler",
|
|
side_effect=lambda timeout=None: mock_handler,
|
|
):
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "mocked_token"
|
|
assert mock_handler.last_params == {"audience": "[invalid url, do not cite]"}
|
|
mock_oidc_cache.set_cache.assert_called_once_with(
|
|
key=secret_name, value="mocked_token", ttl=3540
|
|
)
|
|
|
|
|
|
def test_oidc_google_cached():
|
|
"""Test Google OIDC uses cache and does not call HTTP (no real network calls)."""
|
|
secret_name = "oidc/google/[invalid url, do not cite]"
|
|
mock_get_http_handler = Mock()
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = "cached_token"
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
with patch(
|
|
"litellm.secret_managers.main.HTTPHandler",
|
|
Mock(side_effect=AssertionError("HTTPHandler should not be used")),
|
|
):
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "cached_token", f"Expected cached token, got {result}"
|
|
mock_oidc_cache.get_cache.assert_called_with(key=secret_name)
|
|
mock_get_http_handler.assert_not_called()
|
|
|
|
|
|
def _jwt_with_exp(exp: int) -> str:
|
|
header = base64.urlsafe_b64encode(json.dumps({"alg": "RS256"}).encode()).rstrip(b"=").decode()
|
|
payload = base64.urlsafe_b64encode(json.dumps({"exp": exp}).encode()).rstrip(b"=").decode()
|
|
return f"{header}.{payload}.signature"
|
|
|
|
|
|
def test_oidc_google_cache_ttl_capped_by_token_exp():
|
|
"""A token the metadata server returns near its expiry must not be cached past
|
|
its exp claim; the cached-entry TTL is exp - now - 60s, not the 59m default."""
|
|
secret_name = "oidc/google/https://example.com/api"
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_handler.text = _jwt_with_exp(int(time.time()) + 300)
|
|
mock_get_http_handler = Mock(return_value=mock_handler)
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == mock_handler.text
|
|
mock_oidc_cache.set_cache.assert_called_once()
|
|
ttl = mock_oidc_cache.set_cache.call_args.kwargs["ttl"]
|
|
assert 0 < ttl <= 240
|
|
|
|
|
|
def test_oidc_google_expired_token_not_cached():
|
|
"""An already-expired token is returned (STS gives the authoritative error) but
|
|
never cached, so the next call fetches a fresh token instead of replaying it."""
|
|
secret_name = "oidc/google/https://example.com/api"
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_handler.text = _jwt_with_exp(int(time.time()) - 10)
|
|
mock_get_http_handler = Mock(return_value=mock_handler)
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == mock_handler.text
|
|
mock_oidc_cache.set_cache.assert_not_called()
|
|
|
|
|
|
def test_oidc_google_long_lived_token_still_capped_at_default_ttl():
|
|
"""A token expiring far in the future must not extend the cache past the
|
|
59m policy ceiling; exp only ever shortens the TTL."""
|
|
secret_name = "oidc/google/https://example.com/api"
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_handler.text = _jwt_with_exp(int(time.time()) + 7200)
|
|
mock_get_http_handler = Mock(return_value=mock_handler)
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == mock_handler.text
|
|
mock_oidc_cache.set_cache.assert_called_once_with(
|
|
key=secret_name, value=mock_handler.text, ttl=3540
|
|
)
|
|
|
|
|
|
def test_oidc_google_non_jwt_token_keeps_default_ttl():
|
|
"""A token without a readable exp claim falls back to the 59m default TTL."""
|
|
secret_name = "oidc/google/https://example.com/api"
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_get_http_handler = Mock(return_value=mock_handler)
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "mocked_token"
|
|
mock_oidc_cache.set_cache.assert_called_once_with(
|
|
key=secret_name, value="mocked_token", ttl=3540
|
|
)
|
|
|
|
|
|
def test_oidc_google_failure():
|
|
"""Test Google OIDC raises when provider returns error (no real network calls)."""
|
|
secret_name = "oidc/google/https://example.com/api"
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_handler.status_code = 400
|
|
mock_get_http_handler = Mock(return_value=mock_handler)
|
|
mock_oidc_cache = Mock()
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
|
|
with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
|
|
with patch(
|
|
"litellm.secret_managers.main._get_oidc_http_handler",
|
|
mock_get_http_handler,
|
|
):
|
|
with patch(
|
|
"litellm.secret_managers.main.HTTPHandler",
|
|
side_effect=lambda timeout=None: mock_handler,
|
|
):
|
|
with pytest.raises(ValueError, match="Google OIDC provider failed"):
|
|
get_secret(secret_name)
|
|
|
|
|
|
|
|
def test_oidc_google_fetches_the_token_from_the_metadata_host_gce_metadata_host_names(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setenv("GCE_METADATA_HOST", "127.0.0.1:8930")
|
|
audience: Final = f"https://vllm.example.test/{uuid.uuid4().hex}"
|
|
|
|
with respx.mock(assert_all_called=True) as metadata:
|
|
metadata.get(
|
|
"http://127.0.0.1:8930/computeMetadata/v1/instance/service-accounts/default/identity",
|
|
params={"audience": audience},
|
|
headers={"Metadata-Flavor": "Google"},
|
|
).respond(200, text="metadata-host-token")
|
|
token: Final = get_secret(f"oidc/google/{audience}")
|
|
|
|
assert token == "metadata-host-token"
|
|
|
|
def test_oidc_google_secret_outside_a_model_api_key_keeps_its_metadata_wait_when_gce_metadata_timeout_is_set(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setenv("GCE_METADATA_TIMEOUT", "1")
|
|
audience: Final = f"https://sts.example.test/{uuid.uuid4().hex}"
|
|
|
|
with respx.mock(assert_all_called=True) as metadata:
|
|
identity: Final = metadata.get(
|
|
"http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity",
|
|
params={"audience": audience},
|
|
).respond(200, text="web-identity-token")
|
|
token: Final = get_secret(f"oidc/google/{audience}")
|
|
waits: Final = identity.calls.last.request.extensions["timeout"]
|
|
|
|
assert token == "web-identity-token"
|
|
assert waits == {"connect": 5.0, "read": 600.0, "write": 600.0, "pool": 600.0}
|
|
|
|
|
|
def test_oidc_circleci_success(monkeypatch):
|
|
monkeypatch.setenv("CIRCLE_OIDC_TOKEN", "circleci_token")
|
|
|
|
secret_name = "oidc/circleci/test-audience"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "circleci_token"
|
|
|
|
|
|
def test_oidc_circleci_v2_returns_the_environment_token(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
token: Final = "circleci-v2-token"
|
|
monkeypatch.setenv("CIRCLE_OIDC_TOKEN_V2", token)
|
|
|
|
assert get_secret("oidc/circleci_v2/test-audience") == token
|
|
|
|
|
|
def test_oidc_circleci_failure(monkeypatch):
|
|
monkeypatch.delenv("CIRCLE_OIDC_TOKEN", raising=False)
|
|
secret_name = "oidc/circleci/test-audience"
|
|
|
|
with pytest.raises(ValueError, match="CIRCLE_OIDC_TOKEN not found in environment"):
|
|
get_secret(secret_name)
|
|
|
|
|
|
@patch("litellm.secret_managers.main.oidc_cache")
|
|
@patch("litellm.secret_managers.main._get_oidc_http_handler")
|
|
def test_oidc_github_success(mock_get_http_handler, mock_oidc_cache, mock_env):
|
|
mock_env["ACTIONS_ID_TOKEN_REQUEST_URL"] = "https://github.com/token"
|
|
mock_env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = "github_token"
|
|
mock_oidc_cache.get_cache.return_value = None
|
|
mock_handler = MockHTTPHandler(timeout=600.0)
|
|
mock_get_http_handler.return_value = mock_handler
|
|
|
|
secret_name = "oidc/github/github-audience"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "mocked_token", f"Expected token 'mocked_token', got {result}"
|
|
assert mock_handler.last_params == {"audience": "github-audience"}
|
|
logger.debug(f"set_cache call args: {mock_oidc_cache.set_cache.call_args}")
|
|
mock_oidc_cache.set_cache.assert_called_once()
|
|
mock_oidc_cache.set_cache.assert_called_with(
|
|
key=secret_name, value="mocked_token", ttl=295
|
|
)
|
|
|
|
|
|
def test_oidc_github_missing_env():
|
|
secret_name = "oidc/github/github-audience"
|
|
|
|
with pytest.raises(
|
|
ValueError,
|
|
match="ACTIONS_ID_TOKEN_REQUEST_URL or ACTIONS_ID_TOKEN_REQUEST_TOKEN not found in environment",
|
|
):
|
|
get_secret(secret_name)
|
|
|
|
|
|
def test_oidc_azure_file_success(mock_env, tmp_path):
|
|
token_file = tmp_path / "token.txt"
|
|
token_file.write_text("azure_token")
|
|
mock_env["AZURE_FEDERATED_TOKEN_FILE"] = str(token_file)
|
|
|
|
secret_name = "oidc/azure/azure-audience"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "azure_token"
|
|
|
|
|
|
@patch("litellm.secret_managers.main.get_azure_ad_token_provider")
|
|
def test_oidc_azure_ad_token_success(mock_get_azure_ad_token_provider, monkeypatch):
|
|
# Force-unset so we always hit the Azure AD token provider path (CI may set AZURE_FEDERATED_TOKEN_FILE)
|
|
monkeypatch.delenv("AZURE_FEDERATED_TOKEN_FILE", raising=False)
|
|
|
|
# Mock the token provider function that gets returned and called
|
|
mock_token_provider = Mock(return_value="azure_ad_token")
|
|
mock_get_azure_ad_token_provider.return_value = mock_token_provider
|
|
|
|
# Also mock the Azure Identity SDK to prevent any real Azure calls
|
|
with patch("azure.identity.get_bearer_token_provider") as mock_bearer:
|
|
mock_bearer.return_value = mock_token_provider
|
|
|
|
secret_name = "oidc/azure/api://azure-audience"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "azure_ad_token"
|
|
mock_get_azure_ad_token_provider.assert_called_once_with(
|
|
azure_scope="api://azure-audience"
|
|
)
|
|
mock_token_provider.assert_called_once_with()
|
|
|
|
|
|
def test_concurrent_azure_oidc_reads_build_one_token_provider(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.delenv("AZURE_FEDERATED_TOKEN_FILE", raising=False)
|
|
callers: Final = 8
|
|
start: Final = threading.Barrier(callers)
|
|
builds: Final = SimpleQueue[str | None]()
|
|
everyone_building: Final = threading.Event()
|
|
release: Final = threading.Event()
|
|
|
|
def held_build(azure_scope: str | None = None) -> Callable[[], str]:
|
|
builds.put(azure_scope)
|
|
if builds.qsize() >= callers:
|
|
everyone_building.set()
|
|
release.wait(5)
|
|
return lambda: "identity-token"
|
|
|
|
def read() -> str | None:
|
|
start.wait(5)
|
|
return get_secret("oidc/azure/api://concurrent-audience")
|
|
|
|
_cached_azure_oidc_token_provider.cache_clear()
|
|
with (
|
|
patch("litellm.secret_managers.main.get_azure_ad_token_provider", side_effect=held_build),
|
|
ThreadPoolExecutor(max_workers=callers) as pool,
|
|
):
|
|
calls: Final = tuple(pool.submit(read) for _ in range(callers))
|
|
assert builds.get(timeout=5) == "api://concurrent-audience"
|
|
everyone_building.wait(0.5)
|
|
release.set()
|
|
tokens: Final = tuple(call.result(timeout=5) for call in calls)
|
|
_cached_azure_oidc_token_provider.cache_clear()
|
|
|
|
assert tokens == ("identity-token",) * callers
|
|
assert builds.qsize() == 0
|
|
|
|
|
|
def test_oidc_file_success(tmp_path, monkeypatch):
|
|
token_file = tmp_path / "token.txt"
|
|
token_file.write_text("file_token")
|
|
monkeypatch.setenv("LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS", str(tmp_path))
|
|
|
|
secret_name = f"oidc/file/{token_file}"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "file_token"
|
|
|
|
|
|
def test_oidc_file_reads_a_token_under_a_directory_named_oidc(tmp_path, monkeypatch):
|
|
token_dir: Final = tmp_path / "oidc"
|
|
token_dir.mkdir()
|
|
(token_dir / "token").write_text("nested_token")
|
|
monkeypatch.setenv("LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS", str(tmp_path))
|
|
|
|
assert get_secret(f"oidc/file/{token_dir}/token") == "nested_token"
|
|
|
|
|
|
def test_oidc_file_rejects_path_outside_allowlist(tmp_path, monkeypatch):
|
|
outside_file = tmp_path / "outside.txt"
|
|
outside_file.write_text("should_not_read")
|
|
# Allowlist a different directory.
|
|
allowed_dir = tmp_path / "allowed"
|
|
allowed_dir.mkdir()
|
|
monkeypatch.setenv("LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS", str(allowed_dir))
|
|
|
|
with pytest.raises(ValueError, match="outside the allowed credential directories"):
|
|
get_secret(f"oidc/file/{outside_file}")
|
|
|
|
|
|
def test_oidc_file_rejects_relative_path_with_a_hint_client_redaction_leaves_whole(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("LITELLM_OIDC_ALLOWED_CREDENTIAL_DIRS", str(tmp_path))
|
|
with pytest.raises(ValueError, match="must be absolute") as excinfo:
|
|
get_secret("oidc/file/relative/path/token")
|
|
hint: Final = str(excinfo.value)
|
|
assert redact_internal_details_from_client_message(hint) == hint
|
|
|
|
|
|
def test_oidc_env_success(mock_env):
|
|
mock_env["CUSTOM_TOKEN"] = "env_token"
|
|
|
|
secret_name = "oidc/env/CUSTOM_TOKEN"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "env_token"
|
|
|
|
|
|
def test_oidc_env_path_success(mock_env, tmp_path):
|
|
token_file = tmp_path / "token.txt"
|
|
token_file.write_text("env_path_token")
|
|
mock_env["TOKEN_PATH"] = str(token_file)
|
|
|
|
secret_name = "oidc/env_path/TOKEN_PATH"
|
|
result = get_secret(secret_name)
|
|
|
|
assert result == "env_path_token"
|
|
|
|
|
|
def test_unsupported_oidc_provider():
|
|
secret_name = "oidc/unsupported/unsupported-audience"
|
|
|
|
with pytest.raises(ValueError, match="Unsupported OIDC provider"):
|
|
get_secret(secret_name)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("raw", "expected"),
|
|
[
|
|
(None, None),
|
|
("", None),
|
|
(" \t\n", None),
|
|
("abc", "abc"),
|
|
(" xyz ", "xyz"),
|
|
],
|
|
)
|
|
def test_normalize_nonempty_secret_str(raw, expected):
|
|
assert normalize_nonempty_secret_str(raw) == expected
|
|
|
|
|
|
class _SpySecretManager(CustomSecretManager):
|
|
"""Records every name the manager is actually asked for."""
|
|
|
|
def __init__(self, asked):
|
|
self.asked = asked
|
|
|
|
def sync_read_secret(self, secret_name, optional_params=None, timeout=None, **kwargs):
|
|
self.asked.append(secret_name)
|
|
return "a-value"
|
|
|
|
async def async_read_secret(self, secret_name, optional_params=None, timeout=None, **kwargs):
|
|
self.asked.append(secret_name)
|
|
return "a-value"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("access_mode", "hosted_keys", "secret_name", "expected"),
|
|
[
|
|
("read_only", None, "ANY_NAME", True),
|
|
("read_only", ["ALLOWED"], "ALLOWED", True),
|
|
("read_only", ["ALLOWED"], "NOT_ALLOWED", False),
|
|
("read_and_write", ["ALLOWED"], "ALLOWED", True),
|
|
("write_only", None, "ANY_NAME", False),
|
|
("write_only", ["ALLOWED"], "ALLOWED", False),
|
|
],
|
|
)
|
|
def test_secret_manager_would_be_consulted_matches_get_secret(
|
|
monkeypatch, access_mode, hosted_keys, secret_name, expected
|
|
):
|
|
"""The predicate must agree with what get_secret actually does, not with a reading of it.
|
|
|
|
Callers use it to tell "the manager does not have this key" apart from "the manager was
|
|
never asked", so a predicate that drifts from get_secret's gating makes them state a
|
|
lookup that never happened.
|
|
"""
|
|
asked = []
|
|
monkeypatch.setattr(litellm, "secret_manager_client", _SpySecretManager(asked))
|
|
monkeypatch.setattr(litellm, "_key_management_system", KeyManagementSystem.CUSTOM)
|
|
monkeypatch.setattr(
|
|
litellm,
|
|
"_key_management_settings",
|
|
KeyManagementSettings(access_mode=access_mode, hosted_keys=hosted_keys),
|
|
)
|
|
monkeypatch.delenv(secret_name, raising=False)
|
|
|
|
predicted = secret_manager_would_be_consulted(f"os.environ/{secret_name}")
|
|
get_secret(f"os.environ/{secret_name}")
|
|
|
|
assert {"predicted": predicted, "actually_consulted": bool(asked)} == {
|
|
"predicted": expected,
|
|
"actually_consulted": expected,
|
|
}
|
|
|
|
|
|
def test_secret_manager_would_be_consulted_is_false_without_a_client(monkeypatch):
|
|
monkeypatch.setattr(litellm, "secret_manager_client", None)
|
|
|
|
assert secret_manager_would_be_consulted("os.environ/ANY_NAME") is False
|
|
|
|
|
|
class _FixedValueSecretManager(CustomSecretManager):
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
def sync_read_secret(self, secret_name, optional_params=None, timeout=None):
|
|
return self.value
|
|
|
|
async def async_read_secret(self, secret_name, optional_params=None, timeout=None):
|
|
return self.value
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("stored", "expected"),
|
|
[
|
|
("True", True),
|
|
("False", False),
|
|
("1", "1"),
|
|
("[True]", "[True]"),
|
|
("'True'", "'True'"),
|
|
("sk-not-a-literal", "sk-not-a-literal"),
|
|
("", ""),
|
|
],
|
|
)
|
|
def test_get_secret_turns_only_boolean_literals_from_the_secret_manager_into_bools(monkeypatch, stored, expected):
|
|
monkeypatch.setattr(litellm, "secret_manager_client", _FixedValueSecretManager(stored))
|
|
monkeypatch.setattr(litellm, "_key_management_system", KeyManagementSystem.CUSTOM)
|
|
monkeypatch.setattr(litellm, "_key_management_settings", KeyManagementSettings(access_mode="read_only"))
|
|
monkeypatch.delenv("STORED_FLAG", raising=False)
|
|
|
|
secret = get_secret("os.environ/STORED_FLAG")
|
|
|
|
assert secret == expected
|
|
assert type(secret) is type(expected)
|
|
|
|
|
|
def test_an_unresolvable_reference_cannot_forge_a_server_log_line(
|
|
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
monkeypatch.delenv("LIT_UNSET_SA_TOKEN", raising=False)
|
|
|
|
with caplog.at_level(logging.WARNING, logger="LiteLLM"):
|
|
resolve_local_oidc_reference("oidc/env/LIT_UNSET_SA_TOKEN\nFORGED ENTRY")
|
|
|
|
assert "LIT_UNSET_SA_TOKEN" in caplog.text
|
|
assert "\nFORGED" not in caplog.text
|