Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/security/test_netguard.py8# Module : Tests9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""SSRF guard: address classes, URL forms, DNS answers, egress proxy."""42import asyncio43import socket4445import pytest4647from spider.netguard import EgressProxy, NetGuard, SsrfBlocked, ip_block_reason4849BLOCKED = ["127.0.0.1", "127.8.9.1", "10.0.0.1", "10.67.0.1", "172.16.5.4", "192.168.2.1", "169.254.169.254",50 "100.64.0.1", "0.0.0.0", "224.0.0.1", "255.255.255.255", "198.18.0.1", "192.0.2.1", "::1", "::",51 "fe80::1", "fc00::1", "fd12:3456::1", "ff02::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1",52 "::ffff:169.254.169.254", "64:ff9b::7f00:1", "2002:7f00:1::1", "2002:a00:1::1", "::127.0.0.1",53 "2001:db8::1", "fe80::1%en0", "2001:0:4136:e378:8000:63bf:f5ff:fffe"]54PUBLIC = ["1.1.1.1", "8.8.8.8", "51.161.112.61", "2606:4700:4700::1111", "2001:4860:4860::8888"]555657@pytest.mark.parametrize("ip", BLOCKED)58def test_blocked_addresses(ip):59 assert ip_block_reason(ip) is not None606162@pytest.mark.parametrize("ip", PUBLIC)63def test_public_addresses(ip):64 assert ip_block_reason(ip) is None656667@pytest.mark.parametrize("url", [68 "file:///etc/passwd", "ftp://example.com/", "gopher://example.com/", "http://user:pw@example.com/",69 "http://localhost/", "http://foo.localhost/", "http://printer.local/", "http://127.0.0.1/",70 "http://[::1]/", "http://[::ffff:127.0.0.1]/", "http://169.254.169.254/latest/meta-data/",71 "http://10.67.0.1:8080/", "http://example.com:22/", "http://example.com:5432/", "http://example.com:6379/",72 "http:///nohost", "http://metadata.google.internal/", "http://[fe80::1]/", "https://192.168.2.72/",73])74def test_check_url_refuses(url):75 with pytest.raises(SsrfBlocked):76 NetGuard().check_url(url)777879def test_check_url_accepts_public():80 assert NetGuard().check_url("https://example.com/a?b=1") == ("example.com", 443, "https")81 assert NetGuard().check_url("http://1.1.1.1:8080/") == ("1.1.1.1", 8080, "http")828384def test_kill_switch():85 g = NetGuard(deny_hosts={"blocked.example"})86 for h in ("blocked.example", "www.blocked.example"):87 with pytest.raises(SsrfBlocked) as e:88 g.check_url(f"https://{h}/")89 assert e.value.reason == "kill_switch"909192async def _resolve_with(monkeypatch, answers):93 loop = asyncio.get_running_loop()9495 async def fake(host, port, **kw):96 return [(socket.AF_INET6 if ":" in a else socket.AF_INET, socket.SOCK_STREAM, 6, "", (a, port)) for a in answers]97 monkeypatch.setattr(loop, "getaddrinfo", fake)98 return await NetGuard().resolve("rebind.example", 80)99100101async def test_name_resolving_to_private_is_refused(monkeypatch):102 with pytest.raises(SsrfBlocked):103 await _resolve_with(monkeypatch, ["10.0.0.5"])104105106async def test_mixed_public_private_answer_is_refused(monkeypatch):107 # DNS rebinding style answer: one public, one loopback -> whole name refused108 with pytest.raises(SsrfBlocked):109 await _resolve_with(monkeypatch, ["93.184.216.34", "127.0.0.1"])110111112async def test_public_answer_returns_pinned_addresses(monkeypatch):113 assert await _resolve_with(monkeypatch, ["93.184.216.34"]) == [(socket.AF_INET, "93.184.216.34")]114115116async def test_decimal_and_hex_ip_forms_are_refused():117 # the OS resolver turns these into 127.0.0.1; the check runs on the resolved address118 for host in ("2130706433", "0x7f.0.0.1", "017700000001"):119 try:120 await NetGuard().resolve(host, 80)121 except (SsrfBlocked, OSError):122 continue123 pytest.fail(f"{host} was accepted")124125126async def _proxy_request(proxy, raw: bytes) -> bytes:127 r, w = await asyncio.open_connection("127.0.0.1", proxy.port)128 w.write(raw)129 await w.drain()130 data = await asyncio.wait_for(r.read(4096), 10)131 w.close()132 return data133134135async def test_egress_proxy_blocks_internal_targets():136 async def handler(r, w): # a "secret" internal service that must never be reached137 handler.hits += 1138 w.write(b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nsecret")139 await w.drain()140 w.close()141 handler.hits = 0142 srv = await asyncio.start_server(handler, "127.0.0.1", 0)143 port = srv.sockets[0].getsockname()[1]144 proxy = await EgressProxy(NetGuard()).start()145 try:146 for raw in (f"GET http://127.0.0.1:{port}/ HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",147 f"CONNECT 127.0.0.1:{port} HTTP/1.1\r\n\r\n",148 f"GET http://localhost:{port}/ HTTP/1.1\r\n\r\n",149 "CONNECT 169.254.169.254:80 HTTP/1.1\r\n\r\n",150 f"CONNECT [::1]:{port} HTTP/1.1\r\n\r\n",151 "GET ftp://example.com/ HTTP/1.1\r\n\r\n"):152 out = await _proxy_request(proxy, raw.encode())153 assert out.startswith(b"HTTP/1.1 403"), (raw, out[:80])154 assert b"X-Spider-Blocked" in out155 assert handler.hits == 0156 assert len(proxy.guard.blocked_log) >= 5157 # the same target passes only with the explicit test allowance158 allowed = await EgressProxy(NetGuard(test_allow=frozenset({("127.0.0.1", port)}))).start()159 out = await _proxy_request(allowed, f"GET http://127.0.0.1:{port}/x HTTP/1.1\r\nHost: a\r\n\r\n".encode())160 assert out.startswith(b"HTTP/1.1 200") and handler.hits == 1161 await allowed.close()162 finally:163 await proxy.close()164 srv.close()165166167def test_test_allowance_refused_outside_test_env(monkeypatch):168 from spider.config import Settings169 monkeypatch.setenv("SPIDER_TEST_ALLOW_HOSTS", "127.0.0.1:1234")170 monkeypatch.setenv("SPIDER_ENV", "production")171 with pytest.raises(RuntimeError):172 Settings().test_allow()173 monkeypatch.setenv("SPIDER_ENV", "test")174 assert Settings().test_allow() == frozenset({("127.0.0.1", 1234)})175176177# --------------------------------------------------------------------------- spellings of an address178OBFUSCATED_LOOPBACK = [179 "http://2130706433/", "http://0x7f000001/", "http://0177.0.0.1/", "http://127.1/", "http://0x7f.0.0.1/",180 "http://017700000001/", "http://127.0.1/", "http://0/", "http://0x7f.1/",181 "http://127.0.0.1/", # full-width digits182 "http://127。0。0。1/", # ideographic full stops183 "http://①②⑦.0.0.1/", # circled digits184 "http://localhost/", # full-width "localhost"185 "http://[::ffff:7f00:1]/", "http://[0:0:0:0:0:0:0:1]/", "http://LOCALHOST./", "http://127.0.0.1./",186]187188189@pytest.mark.parametrize("url", OBFUSCATED_LOOPBACK)190def test_obfuscated_addresses_are_refused_before_any_resolution(url):191 """No DNS or socket call is needed to refuse these: check_url is synchronous."""192 with pytest.raises(SsrfBlocked):193 NetGuard().check_url(url)194195196def test_decimal_spelling_of_a_public_address_is_refused_too():197 # 134744072 is 8.8.8.8 for inet_aton and a host name for everything else: ambiguity is refused198 with pytest.raises(SsrfBlocked) as e:199 NetGuard().check_url("http://134744072/")200 assert e.value.reason == "ambiguous_ip_literal"201 assert NetGuard().check_url("http://8.8.8.8/") == ("8.8.8.8", 80, "http")202203204def test_internationalised_names_are_still_accepted():205 host, port, _ = NetGuard().check_url("https://café.example/")206 assert host == "xn--caf-dma.example" and port == 443207 assert NetGuard().check_url("https://1example.com/")[0] == "1example.com"208 assert NetGuard().check_url("https://example.123abc/")[0] == "example.123abc"209210211def test_kill_switch_outranks_the_test_allowance():212 g = NetGuard(test_allow=frozenset({("127.0.0.1", 8765)}))213 assert g.check_url("http://127.0.0.1:8765/") == ("127.0.0.1", 8765, "http")214 g.deny_hosts = {"127.0.0.1"}215 with pytest.raises(SsrfBlocked) as e:216 g.check_url("http://127.0.0.1:8765/")217 assert e.value.reason == "kill_switch"218219220def test_test_allowance_is_an_exact_host_and_port():221 g = NetGuard(test_allow=frozenset({("127.0.0.1", 8765)}))222 for url in ("http://127.0.0.1:8766/", "http://127.0.0.1/", "http://localhost:8765/", "http://127.0.0.2:8765/",223 "http://[::1]:8765/"):224 with pytest.raises(SsrfBlocked):225 g.check_url(url)226