Spaces:
Runtime error
Runtime error
Download backend/tests/test_url_guard.py from Amitkasar/ai-api-testing: direct link, hf CLI and curl.
- Browser
- Download file 2.6 kB
-
https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/backend/tests/test_url_guard.py
- Command line
-
hf download hf://spaces/Amitkasar/ai-api-testing/backend/tests/test_url_guard.py
-
curl -L -o test_url_guard.py https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/backend/tests/test_url_guard.py
2.6 kB
| 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") | |