SPB Git

Repository Public

test_ssrf.py 12.3 KB 235 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/security/test_ssrf.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: private destinations are refused at submission and never connected to (seeds, redirects, webhooks)."""42import asyncio43import hashlib44import hmac45import json4647import pytest48from aiohttp import web49from apihelpers import assert_error, db, until, wait_job5051from spider.config import Settings52from spider.engine.http import HttpEngine53from spider.netguard import NetGuard5455FULLWIDTH_LOOPBACK = "127.0.0.1"565758class Listener:59    """A local "internal service". Any TCP connection to it is a hit, whatever is sent."""6061    def __init__(self):62        self.hits, self.requests, self.server, self.port = 0, [], None, 06364    async def start(self, port: int = 0) -> "Listener":65        async def handle(r: asyncio.StreamReader, w: asyncio.StreamWriter):66            self.hits += 167            try:68                head = await asyncio.wait_for(r.readuntil(b"\r\n\r\n"), 5)69                n = 070                for line in head.split(b"\r\n"):71                    if line.lower().startswith(b"content-length:"):72                        n = int(line.split(b":")[1])73                body = await asyncio.wait_for(r.readexactly(n), 5) if n else b""74                self.requests.append((head.decode("latin-1"), body))75                w.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 6\r\nConnection: close\r\n\r\nsecret")76                await w.drain()77            except (asyncio.IncompleteReadError, TimeoutError, ConnectionError):78                pass79            finally:80                w.close()81        self.server = await asyncio.start_server(handle, "127.0.0.1", port)82        self.port = self.server.sockets[0].getsockname()[1]83        return self8485    async def close(self):86        self.server.close()87        await self.server.wait_closed()888990@pytest.fixture91async def secret():92    s = await Listener().start()93    yield s94    await s.close()959697def _private_urls(stack=None, port: int = 80) -> list[str]:98    urls = [99        "http://127.0.0.1/", "http://localhost:8900/", "http://169.254.169.254/", "http://[::1]/", "http://10.67.0.1/",100        "file:///etc/passwd", "http://user:pass@example.com/", "http://example.com:22/",101        "http://2130706433/", "http://0x7f000001/", "http://0177.0.0.1/", "http://127.1/", "http://0x7f.0.0.1/",102        f"http://{FULLWIDTH_LOOPBACK}/", "http://127。0。0。1/", "http://[::ffff:127.0.0.1]/",103        "http://192.168.2.1/", "http://100.64.0.1/", "http://172.16.0.9:8080/", "http://0.0.0.0/",104        "http://metadata.google.internal/", "http://printer.local/", "gopher://example.com/", "ftp://example.com/x",105        "http://example.com:6379/", "http://example.com:5432/", "http://@127.0.0.1/", "http://[fe80::1]/",106        "http://169.254.169.254/latest/meta-data/iam/security-credentials/",107    ]108    if stack is not None:109        urls += [f"http://127.0.0.1:{stack.port}/v1/health",          # the gateway itself110                 f"http://localhost:{stack.site.port}/",              # the fixture site by another name111                 f"http://user:pw@127.0.0.1:{stack.site.port}/",      # credentials, even on an allowed host112                 f"http://127.0.0.1:{port}/"]                         # another loopback port113    return urls114115116@pytest.mark.pg117async def test_private_seeds_are_refused_at_submission(stack, secret):118    c = stack.client119    good = stack.url("/about")120    for bad in _private_urls(stack, secret.port):121        for route, body in (122                ("/v1/scrape", {"url": bad}), ("/v1/crawl", {"url": bad}), ("/v1/crawl", {"urls": [good, bad]}),123                ("/v1/crawl", {"url": good, "sitemap": bad}), ("/v1/crawl", {"sitemap": bad}), ("/v1/map", {"url": bad}),124                ("/v1/screenshot", {"url": bad}), ("/v1/deep-capture", {"url": bad}),125                ("/v1/extract", {"url": bad, "extract": {"schema": {"type": "object", "properties": {}}}}),126                ("/v1/monitor", {"name": "m", "request": {"url": bad}}),127                ("/v1/scrape", {"url": good, "webhook": {"url": bad}}),128                ("/v1/monitor", {"name": "m", "request": {"url": good, "webhook": {"url": bad}}})):129            e = assert_error(await c.post(route, json=body), 422, "destination_not_allowed")130            assert ":pass@" not in json.dumps(e) and "pw@" not in json.dumps(e), "credentials echoed in the error"131        r = await c.post("/v1/batch", json={"items": [{"kind": "scrape", "request": {"url": bad}}]})132        assert r.status_code == 202 and r.json()["accepted"] == 0, r.text133        assert r.json()["items"][0]["error"]["code"] == "destination_not_allowed"134    for table in ("jobs", "tasks", "urls", "schedules", "webhook_deliveries", "sites"):135        assert await db(stack, f"select count(*) from {table}", one=True) == 0, table136    assert secret.hits == 0137    # control: the same routes accept the fixture site, so the refusals above are about the destination138    assert (await c.post("/v1/scrape", json={"url": good, "render": "http"})).status_code == 202139    for junk in ("not a url", "/relative/path", "", "   ", "http://", "http://exa mple.com/" + "a" * 3000):140        r = await c.post("/v1/scrape", json={"url": junk})141        assert r.status_code == 422 and r.json()["error"]["code"] in ("invalid_url", "destination_not_allowed"), r.text142143144async def test_engine_never_connects_to_any_spelling_of_loopback(tmp_path, secret, monkeypatch):145    monkeypatch.setenv("SPIDER_ENV", "test")146    p = secret.port147    engine = HttpEngine(NetGuard(), Settings())148    try:149        for url in (f"http://127.0.0.1:{p}/", f"http://localhost:{p}/", f"http://{FULLWIDTH_LOOPBACK}:{p}/",150                    f"http://2130706433:{p}/", f"http://0x7f000001:{p}/", f"http://127.1:{p}/", f"http://0177.0.0.1:{p}/",151                    f"http://[::1]:{p}/", f"http://[::ffff:127.0.0.1]:{p}/", f"http://127。0。0。1:{p}/",152                    f"http://0.0.0.0:{p}/", f"http://user:pw@127.0.0.1:{p}/"):153            res = await engine.fetch(url, out_dir=tmp_path)154            assert not res.ok and res.error_class == "ssrf", (url, res.error_class, res.error_detail)155            assert res.status == 0 and res.body_path is None156        assert secret.hits == 0, "the engine opened a connection to a loopback service"157        # control: the listener does count a connection when its exact host:port is allowed158        allowed = HttpEngine(NetGuard(test_allow=frozenset({("127.0.0.1", p)})), Settings())159        res = await allowed.fetch(f"http://127.0.0.1:{p}/", out_dir=tmp_path, check_robots=False)160        await allowed.close()161        assert res.ok and secret.hits == 1162    finally:163        await engine.close()164165166async def test_redirects_to_private_addresses_are_not_followed(tmp_path, secret, monkeypatch):167    monkeypatch.setenv("SPIDER_ENV", "test")168    p = secret.port169    targets = [f"http://127.0.0.1:{p}/", f"http://localhost:{p}/", f"http://{FULLWIDTH_LOOPBACK}:{p}/",170               f"http://2130706433:{p}/", f"http://127.1:{p}/", f"http://[::1]:{p}/", f"//127.0.0.1:{p}/x",171               f"http://127。0。0。1:{p}/", "http://169.254.169.254/latest/meta-data/", "file:///etc/passwd",172               f"http://user:pw@127.0.0.1:{p}/", f"http://[::ffff:7f00:1]:{p}/"]173174    async def go(request: web.Request):175        raise web.HTTPFound(location=targets[int(request.match_info["i"])])176    app = web.Application()177    app.router.add_get("/go/{i}", go)178    runner = web.AppRunner(app)179    await runner.setup()180    site = web.TCPSite(runner, "127.0.0.1", 0)181    await site.start()182    port = site._server.sockets[0].getsockname()[1]183    engine = HttpEngine(NetGuard(test_allow=frozenset({("127.0.0.1", port)})), Settings())184    try:185        for i, target in enumerate(targets):186            res = await engine.fetch(f"http://127.0.0.1:{port}/go/{i}", out_dir=tmp_path)187            assert not res.ok and res.error_class == "ssrf", (target, res.error_class, res.error_detail)188            assert len(res.redirects) == 1189        assert secret.hits == 0, "a redirect led the engine to a loopback service"190    finally:191        await engine.close()192        await runner.cleanup()193194195@pytest.mark.pg196async def test_webhook_to_private_address_never_connects(stack, secret):197    """Delivery re-validates the destination: a private webhook URL already in the queue is dead-lettered."""198    await stack.start_worker()199    hook = await Listener().start(stack.hook_port)  # the one webhook destination the test environment allows200    try:201        r = await stack.client.post("/v1/scrape", json={"url": stack.url("/about"), "render": "http",202                                                         "webhook": {"url": f"http://127.0.0.1:{stack.hook_port}/hook"}})203        assert r.status_code == 202, r.text204        job = await wait_job(stack.client, r.json()["job_id"])205        # deliveries that could only exist if validation at submission had been bypassed206        bad = [f"http://127.0.0.1:{secret.port}/hook", f"http://localhost:{secret.port}/hook",207               f"http://{FULLWIDTH_LOOPBACK}:{secret.port}/hook", f"http://2130706433:{secret.port}/hook",208               f"http://[::1]:{secret.port}/hook", f"http://127.1:{secret.port}/", f"http://user:pw@127.0.0.1:{stack.hook_port}/",209               "http://169.254.169.254/latest/meta-data/", "file:///etc/passwd"]210        for u in bad:211            await db(stack, "insert into webhook_deliveries(tenant_id, job_id, url, event, payload) "212                            "values($1,$2,$3,'job.finished','{}')", stack.tenant_id, job["job_id"], u)213214        async def settled():215            await stack.maint.deliver_webhooks()216            return not await db(stack, "select count(*) from webhook_deliveries where status='pending'", one=True)217        await until(settled, what="webhook deliveries to settle")218        rows = {r["url"]: r for r in await db(stack, "select url, status, attempts, last_error from webhook_deliveries")}219        for u in bad:220            assert rows[u]["status"] == "dead" and rows[u]["attempts"] == 1, rows[u]221            assert rows[u]["last_error"].startswith("destination refused"), rows[u]222        assert secret.hits == 0, "a webhook delivery connected to a private address"223        # control: the allowed destination received exactly the signed delivery224        good = rows[f"http://127.0.0.1:{stack.hook_port}/hook"]225        assert good["status"] == "delivered" and hook.hits == 1, good226        head, body = hook.requests[0]227        headers = {k.lower(): v.strip() for k, v in (ln.split(":", 1) for ln in head.split("\r\n")[1:] if ":" in ln)}228        secret_key = (await stack.client.get("/v1/webhook-secret")).json()["secret"]229        signed = headers["x-spider-timestamp"].encode() + b"." + headers["x-spider-delivery"].encode() + b"." + body230        assert headers["x-spider-signature"] == "v1=" + hmac.new(secret_key.encode(), signed, hashlib.sha256).hexdigest()231        payload = json.loads(body)232        assert payload["job_id"] == job["job_id"] and payload["finished_at"].endswith("Z")233    finally:234        await hook.close()235
Files main
Menu

Theme