|
| 1 | +"""Tests for the SSRF guard used by connectors and the MCP client.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import pytest |
| 6 | +from legate.config import Settings |
| 7 | +from legate.security.ssrf import SSRFError, validate_public_url |
| 8 | + |
| 9 | +# Guard active (blocks private targets). |
| 10 | +STRICT = Settings(allow_private_connector_urls=False) |
| 11 | +# Guard disabled (trusted single-tenant opt-in). |
| 12 | +RELAXED = Settings(allow_private_connector_urls=True) |
| 13 | + |
| 14 | + |
| 15 | +@pytest.mark.parametrize( |
| 16 | + "url", |
| 17 | + [ |
| 18 | + "http://127.0.0.1/x", # loopback |
| 19 | + "https://10.0.0.5/admin", # private |
| 20 | + "http://192.168.1.10", # private |
| 21 | + "http://169.254.169.254/latest/meta-data", # cloud metadata (link-local) |
| 22 | + "http://[::1]/", # IPv6 loopback |
| 23 | + "http://0.0.0.0", # unspecified |
| 24 | + ], |
| 25 | +) |
| 26 | +def test_blocks_internal_targets(url: str) -> None: |
| 27 | + with pytest.raises(SSRFError): |
| 28 | + validate_public_url(url, settings=STRICT) |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.parametrize("url", ["https://8.8.8.8", "https://93.184.216.34/path"]) |
| 32 | +def test_allows_public_ip(url: str) -> None: |
| 33 | + assert validate_public_url(url, settings=STRICT) == url |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parametrize("url", ["ftp://example.com", "file:///etc/passwd", "gopher://x"]) |
| 37 | +def test_rejects_non_http_schemes(url: str) -> None: |
| 38 | + with pytest.raises(SSRFError): |
| 39 | + validate_public_url(url, settings=STRICT) |
| 40 | + |
| 41 | + |
| 42 | +def test_rejects_missing_host() -> None: |
| 43 | + with pytest.raises(SSRFError): |
| 44 | + validate_public_url("http://", settings=STRICT) |
| 45 | + |
| 46 | + |
| 47 | +def test_opt_in_bypasses_the_guard() -> None: |
| 48 | + # With the flag on, an internal URL is allowed (and no DNS is attempted). |
| 49 | + assert validate_public_url("http://127.0.0.1:9000/rpc", settings=RELAXED) |
| 50 | + assert validate_public_url("http://internal-host.local/rpc", settings=RELAXED) |
0 commit comments