import socket from unittest.mock import patch import pytest from fastapi import HTTPException from backend.core.url_guard import assert_safe_url def _mock_resolve(ip: str): """Return a socket.getaddrinfo patch that resolves any hostname to `ip`.""" return patch("backend.core.url_guard.socket.getaddrinfo", return_value=[(None, None, None, None, (ip, 0))]) # ── Scheme checks ───────────────────────────────────────────────────────────── def test_blocks_ftp_scheme(): with pytest.raises(HTTPException) as exc: assert_safe_url("ftp://example.com/file") assert exc.value.status_code == 400 def test_blocks_file_scheme(): with pytest.raises(HTTPException): assert_safe_url("file:///etc/passwd") def test_blocks_no_hostname(): with pytest.raises(HTTPException): assert_safe_url("http:///path") # ── Private / loopback IP checks ────────────────────────────────────────────── def test_blocks_localhost_ip(): with _mock_resolve("127.0.0.1"): with pytest.raises(HTTPException) as exc: assert_safe_url("http://localhost/api") assert exc.value.status_code == 400 def test_blocks_10x_range(): with _mock_resolve("10.0.0.1"): with pytest.raises(HTTPException): assert_safe_url("http://internal.corp/api") def test_blocks_192168_range(): with _mock_resolve("192.168.1.100"): with pytest.raises(HTTPException): assert_safe_url("http://router.local/api") def test_blocks_172_16_range(): with _mock_resolve("172.16.0.5"): with pytest.raises(HTTPException): assert_safe_url("http://private.example.com/api") def test_blocks_link_local(): with _mock_resolve("169.254.169.254"): with pytest.raises(HTTPException): assert_safe_url("http://metadata.example.com/api") # ── Allow public addresses ───────────────────────────────────────────────────── def test_allows_public_ip(): with _mock_resolve("93.184.216.34"): # example.com assert_safe_url("https://example.com/api") # should not raise def test_allows_http_and_https(): with _mock_resolve("93.184.216.34"): assert_safe_url("http://example.com/api") assert_safe_url("https://example.com/api")