"""Tests for the SSRF guard used by connectors and the MCP client."""

from __future__ import annotations

import pytest
from legate.config import Settings
from legate.security.ssrf import SSRFError, validate_public_url

# Guard active (blocks private targets).
STRICT = Settings(allow_private_connector_urls=False)
# Guard disabled (trusted single-tenant opt-in).
RELAXED = Settings(allow_private_connector_urls=True)


@pytest.mark.parametrize(
    "url",
    [
        "http://127.0.0.1/x",  # loopback
        "https://10.0.0.5/admin",  # private
        "http://192.168.1.10",  # private
        "http://169.254.169.254/latest/meta-data",  # cloud metadata (link-local)
        "http://[::1]/",  # IPv6 loopback
        "http://0.0.0.0",  # unspecified
    ],
)
def test_blocks_internal_targets(url: str) -> None:
    with pytest.raises(SSRFError):
        validate_public_url(url, settings=STRICT)


@pytest.mark.parametrize("url", ["https://8.8.8.8", "https://93.184.216.34/path"])
def test_allows_public_ip(url: str) -> None:
    assert validate_public_url(url, settings=STRICT) == url


@pytest.mark.parametrize("url", ["ftp://example.com", "file:///etc/passwd", "gopher://x"])
def test_rejects_non_http_schemes(url: str) -> None:
    with pytest.raises(SSRFError):
        validate_public_url(url, settings=STRICT)


def test_rejects_missing_host() -> None:
    with pytest.raises(SSRFError):
        validate_public_url("http://", settings=STRICT)


def test_opt_in_bypasses_the_guard() -> None:
    # With the flag on, an internal URL is allowed (and no DNS is attempted).
    assert validate_public_url("http://127.0.0.1:9000/rpc", settings=RELAXED)
    assert validate_public_url("http://internal-host.local/rpc", settings=RELAXED)
