236 lines
10 KiB
Python
236 lines
10 KiB
Python
# #region Test.EndpointLocality [C:4] [TYPE Module] [SEMANTICS test,security,locality,llm,perimeter,t008b]
|
|
# @BRIEF 050 T008b / MCPX-FR-020: the enterprise-perimeter locality guard denies non-local
|
|
# LLM/VLM endpoint configuration by default — typed, pre-persistence, with documented
|
|
# env overrides; PII-bearing provider traffic stays inside the local perimeter.
|
|
# @RELATION VERIFIES -> [Core.EndpointLocality]
|
|
# @RELATION VERIFIES -> [Services.LlmProvider.CreateProvider]
|
|
# @TEST_INVARIANT deny_by_default -> VERIFIED_BY: [public_endpoints_denied, unset_endpoint_denied]
|
|
# @TEST_INVARIANT fail_closed -> VERIFIED_BY: [unresolvable_host_denied, spoofed_path_not_local]
|
|
# @TEST_INVARIANT typed_pre_persistence -> VERIFIED_BY: [create_denied_persists_nothing, update_denied_mutates_nothing]
|
|
# @TEST_EDGE private ranges -> 127.x/10.x/172.16-31.x/192.168.x/::1 accepted.
|
|
# @TEST_EDGE overrides -> opt-out flag and exact-host allowlist open the documented escape hatches.
|
|
|
|
import os
|
|
import socket
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from src.core.utils.endpoint_locality import (
|
|
EndpointNotLocalError,
|
|
_host_is_local,
|
|
enforce_local_endpoint,
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _clean_guard_env(monkeypatch):
|
|
monkeypatch.delenv("LLM_ALLOW_NONLOCAL_ENDPOINTS", raising=False)
|
|
monkeypatch.delenv("LLM_NONLOCAL_ENDPOINT_ALLOWED_HOSTS", raising=False)
|
|
monkeypatch.delenv("LLM_LOCAL_HOST_SUFFIXES", raising=False)
|
|
|
|
|
|
def _fake_getaddrinfo(*addresses):
|
|
"""socket.getaddrinfo double resolving the host to the given addresses."""
|
|
|
|
def _resolver(host, port, *args, **kwargs):
|
|
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, 0)) for address in addresses]
|
|
|
|
return _resolver
|
|
|
|
|
|
def _failing_getaddrinfo(host, port, *args, **kwargs):
|
|
raise socket.gaierror(-2, "Name or service not known")
|
|
|
|
|
|
# #region Test.EndpointLocality.Accepted [C:3] [TYPE Function] [SEMANTICS test,locality,accept]
|
|
# @ingroup Test.EndpointLocality
|
|
# @BRIEF Perimeter-local endpoints pass the guard without DNS or exception.
|
|
@pytest.mark.parametrize("url", [
|
|
"http://localhost:1234/v1",
|
|
"http://127.0.0.1:8000/v1",
|
|
"http://[::1]:8000/v1",
|
|
"http://0.0.0.0:9999/v1",
|
|
"http://host.docker.internal:1234/v1",
|
|
"http://10.0.5.7:8000/v1",
|
|
"https://192.168.1.10/v1",
|
|
"http://172.16.0.1:8080/v1",
|
|
"http://172.31.255.254/v1",
|
|
])
|
|
def test_local_endpoints_accepted(url):
|
|
enforce_local_endpoint(url, context="test") # must not raise
|
|
|
|
|
|
def test_local_endpoints_accepted_with_dns(monkeypatch):
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("10.1.2.3"))
|
|
enforce_local_endpoint("https://llm.mycorp.example/v1", context="test")
|
|
|
|
|
|
def test_enterprise_suffix_accepted_without_resolution(monkeypatch):
|
|
# Split-horizon DNS: suffix-allowlisted host passes even when resolution fails.
|
|
monkeypatch.setattr(socket, "getaddrinfo", _failing_getaddrinfo)
|
|
enforce_local_endpoint("http://vllm.mycorp.internal:8000/v1", context="test")
|
|
is_local, reason = _host_is_local("vllm.mycorp.internal")
|
|
assert is_local and reason == "enterprise_suffix"
|
|
# #endregion Test.EndpointLocality.Accepted
|
|
|
|
|
|
# #region Test.EndpointLocality.Denied [C:4] [TYPE Function] [SEMANTICS test,locality,deny,fail-closed]
|
|
# @ingroup Test.EndpointLocality
|
|
# @BRIEF Public, spoofed, unresolvable, malformed and unset endpoints are denied typed.
|
|
def test_public_dns_endpoint_denied(monkeypatch):
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("104.18.11.22"))
|
|
with pytest.raises(EndpointNotLocalError) as exc:
|
|
enforce_local_endpoint("https://api.openai.com/v1", context="test")
|
|
assert "resolves_to_public_address" in str(exc.value)
|
|
assert exc.value.reason == "resolves_to_public_address"
|
|
|
|
|
|
def test_mixed_resolution_denied(monkeypatch):
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("10.0.0.1", "93.184.216.34"))
|
|
with pytest.raises(EndpointNotLocalError) as exc:
|
|
enforce_local_endpoint("https://dual.example/v1", context="test")
|
|
assert exc.value.reason == "resolves_to_public_address"
|
|
|
|
|
|
def test_public_ip_literal_denied():
|
|
with pytest.raises(EndpointNotLocalError) as exc:
|
|
enforce_local_endpoint("http://8.8.8.8:8000/v1", context="test")
|
|
assert exc.value.reason == "public_ip_literal"
|
|
|
|
|
|
def test_spoofed_path_not_local(monkeypatch):
|
|
# The substring sniff ("localhost" in url) is not the guard: host decides.
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("104.18.11.22"))
|
|
with pytest.raises(EndpointNotLocalError):
|
|
enforce_local_endpoint("https://api.openai.com/localhost/v1", context="test")
|
|
|
|
|
|
def test_unresolvable_host_denied(monkeypatch):
|
|
monkeypatch.setattr(socket, "getaddrinfo", _failing_getaddrinfo)
|
|
with pytest.raises(EndpointNotLocalError) as exc:
|
|
enforce_local_endpoint("https://no-such-host.invalid/v1", context="test")
|
|
assert exc.value.reason == "unresolvable_host"
|
|
|
|
|
|
@pytest.mark.parametrize("url,reason", [
|
|
("", "endpoint_unset_defaults_to_public_cloud"),
|
|
(None, "endpoint_unset_defaults_to_public_cloud"),
|
|
("ftp://localhost/v1", "unsupported_scheme"),
|
|
("not a url", "unsupported_scheme"),
|
|
])
|
|
def test_unset_and_malformed_denied(url, reason):
|
|
with pytest.raises(EndpointNotLocalError) as exc:
|
|
enforce_local_endpoint(url, context="test")
|
|
assert exc.value.reason == reason
|
|
|
|
|
|
def test_error_is_value_error_with_typed_message():
|
|
err = EndpointNotLocalError("public_ip_literal", "8.8.8.8")
|
|
assert isinstance(err, ValueError)
|
|
assert str(err).startswith("endpoint_not_local:public_ip_literal.")
|
|
assert "LLM_NONLOCAL_ENDPOINT_ALLOWED_HOSTS" in str(err)
|
|
assert err.host == "8.8.8.8"
|
|
# #endregion Test.EndpointLocality.Denied
|
|
|
|
|
|
# #region Test.EndpointLocality.Overrides [C:3] [TYPE Function] [SEMANTICS test,locality,override,env]
|
|
# @ingroup Test.EndpointLocality
|
|
# @BRIEF Documented escape hatches: full opt-out flag and exact-host allowlist; both default closed.
|
|
def test_opt_out_flag_disables_guard(monkeypatch):
|
|
monkeypatch.setenv("LLM_ALLOW_NONLOCAL_ENDPOINTS", "true")
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("104.18.11.22"))
|
|
enforce_local_endpoint("https://api.openai.com/v1", context="test") # must not raise
|
|
|
|
|
|
def test_host_allowlist_admits_single_host(monkeypatch):
|
|
monkeypatch.setenv("LLM_NONLOCAL_ENDPOINT_ALLOWED_HOSTS", "llm.partner.example, other.example")
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("104.18.11.22"))
|
|
enforce_local_endpoint("https://llm.partner.example/v1", context="test")
|
|
with pytest.raises(EndpointNotLocalError):
|
|
enforce_local_endpoint("https://not-allowed.example/v1", context="test")
|
|
|
|
|
|
def test_extra_local_suffixes_extendible(monkeypatch):
|
|
monkeypatch.setenv("LLM_LOCAL_HOST_SUFFIXES", ".enterprise")
|
|
monkeypatch.setattr(socket, "getaddrinfo", _failing_getaddrinfo)
|
|
enforce_local_endpoint("http://vllm.corp.enterprise/v1", context="test")
|
|
# #endregion Test.EndpointLocality.Overrides
|
|
|
|
|
|
# #region Test.EndpointLocality.ServiceBoundary [C:4] [TYPE Function] [SEMANTICS test,locality,service,boundary]
|
|
# @ingroup Test.EndpointLocality
|
|
# @BRIEF The guard fires inside the provider service BEFORE any persistence or mutation:
|
|
# a denied create stores nothing; a denied update leaves the row untouched.
|
|
# @RELATION BINDS_TO -> [Services.LlmProvider.CreateProvider]
|
|
def _config(base_url: str) -> MagicMock:
|
|
os.environ.setdefault(
|
|
"ENCRYPTION_KEY", "MldUHg5kwSAcPnnYxmhWDS6ASb6e_bWQRV5gtwHrjQ0=" # gitleaks:allow
|
|
)
|
|
config = MagicMock()
|
|
config.name = "Perimeter Test"
|
|
config.provider_type = MagicMock()
|
|
config.provider_type.value = "openai"
|
|
config.api_key = "sk-test-key"
|
|
config.base_url = base_url
|
|
config.is_active = True
|
|
config.is_multimodal = False
|
|
config.default_model = "gpt-4o"
|
|
config.max_images = None
|
|
config.context_window = None
|
|
config.max_output_tokens = None
|
|
return config
|
|
|
|
|
|
def test_create_denied_persists_nothing(monkeypatch):
|
|
from src.services.llm_provider import LLMProviderService
|
|
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("104.18.11.22"))
|
|
db = MagicMock()
|
|
with patch("src.services.llm_provider.LLMProvider") as provider_cls:
|
|
service = LLMProviderService(db)
|
|
with pytest.raises(EndpointNotLocalError):
|
|
service.create_provider(_config("https://api.openai.com/v1"))
|
|
db.add.assert_not_called()
|
|
db.commit.assert_not_called()
|
|
provider_cls.assert_not_called()
|
|
|
|
|
|
def test_update_denied_mutates_nothing(monkeypatch):
|
|
from src.models.llm import LLMProvider
|
|
from src.services.llm_provider import LLMProviderService
|
|
|
|
monkeypatch.setattr(socket, "getaddrinfo", _fake_getaddrinfo("104.18.11.22"))
|
|
db = MagicMock()
|
|
existing = MagicMock(spec=LLMProvider)
|
|
existing.base_url = "http://localhost:1234/v1"
|
|
db.query.return_value.filter.return_value.first.return_value = existing
|
|
service = LLMProviderService(db)
|
|
with pytest.raises(EndpointNotLocalError):
|
|
service.update_provider("prov-1", _config("https://api.openai.com/v1"))
|
|
db.commit.assert_not_called()
|
|
assert existing.base_url == "http://localhost:1234/v1"
|
|
# #endregion Test.EndpointLocality.ServiceBoundary
|
|
|
|
|
|
# #region Test.EndpointLocality.RouteMapping [C:3] [TYPE Function] [SEMANTICS test,locality,route,http-400]
|
|
# @ingroup Test.EndpointLocality
|
|
# @BRIEF The admin surface maps a perimeter denial to a typed HTTP 400, never a 500.
|
|
@pytest.mark.asyncio
|
|
async def test_create_route_maps_denial_to_400():
|
|
from fastapi import HTTPException
|
|
|
|
from src.api.routes.llm import create_provider
|
|
|
|
service = MagicMock()
|
|
service.create_provider.side_effect = EndpointNotLocalError("resolves_to_public_address", "api.openai.com")
|
|
config = _config("https://api.openai.com/v1")
|
|
with patch("src.api.routes.llm.LLMProviderService", return_value=service):
|
|
with pytest.raises(HTTPException) as exc:
|
|
await create_provider(config=config, current_user=MagicMock(), db=MagicMock())
|
|
assert exc.value.status_code == 400
|
|
assert "endpoint_not_local:resolves_to_public_address" in exc.value.detail
|
|
# #endregion Test.EndpointLocality.RouteMapping
|
|
|
|
# #endregion Test.EndpointLocality
|