SPB Git

Repository Public

test_watch_webhooks.py 11.6 KB 254 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/integration/test_watch_webhooks.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"""Signed webhooks: HMAC signature, timestamp, delivery id, bounded retries with backoff, no redirects, SSRF guard.4243The listener runs on the loopback port reserved by the `stack` fixture, the only loopback44destination (with the fixture site) that the SSRF guard lets through in the test environment.45"""46import asyncio47import hashlib48import hmac49import json50import socket51import time52import uuid5354import pytest55from aiohttp import web5657pytestmark = pytest.mark.pg585960class Listener:61    def __init__(self):62        self.received: list[dict] = []63        self.status = 2006465    async def handle(self, request: web.Request) -> web.Response:66        body = await request.read()67        self.received.append({"path": request.path, "method": request.method, "headers": dict(request.headers),68                              "body": body, "at": time.time()})69        if request.path == "/redirect":70            return web.Response(status=302, headers={"Location": "/followed"})71        return web.Response(status=self.status, text="ok")7273    def at(self, path: str) -> list[dict]:74        return [r for r in self.received if r["path"] == path]757677@pytest.fixture78async def hook(stack):79    lst = Listener()80    app = web.Application()81    app.router.add_route("*", "/{tail:.*}", lst.handle)82    runner = web.AppRunner(app)83    await runner.setup()84    await web.TCPSite(runner, "127.0.0.1", stack.hook_port).start()85    lst.url = f"http://127.0.0.1:{stack.hook_port}"86    await stack.maint.stop()  # deliveries are driven by the test87    await stack.start_worker(concurrency=2)88    try:89        yield lst90    finally:91        await runner.cleanup()929394async def db(stack, sql, *args):95    async with stack.orch.pool.acquire() as c:96        return await c.fetch(sql, *args)979899async def scrape_with_hook(stack, url_hook: str, path="/about") -> str:100    r = await stack.client.post("/v1/scrape", json={"url": stack.url(path), "render": "http",101                                                    "webhook": {"url": url_hook, "events": ["job.finished"]}})102    assert r.status_code == 202, r.text103    job = await stack.wait(r.json()["job_id"])104    assert job["status"] == "succeeded"105    return job["job_id"]106107108async def secret_of(stack) -> str:109    r = await stack.client.get("/v1/webhook-secret")110    assert r.status_code == 200 and r.json()["algorithm"] == "HMAC-SHA256"111    return r.json()["secret"]112113114def verify(secret: str, rec: dict) -> dict:115    """What a receiver must do: recompute the HMAC over '<timestamp>.<delivery id>.<raw body>'."""116    h = {k.lower(): v for k, v in rec["headers"].items()}117    ts, did, sig = h["x-spider-timestamp"], h["x-spider-delivery"], h["x-spider-signature"]118    want = hmac.new(secret.encode(), ts.encode() + b"." + did.encode() + b"." + rec["body"], hashlib.sha256).hexdigest()119    assert sig == f"v1={want}", "webhook signature does not verify with the tenant secret"120    assert abs(time.time() - int(ts)) < 60, "stale timestamp"121    assert h["content-type"].startswith("application/json") and h["user-agent"].startswith("SpiderBot/")122    payload = json.loads(rec["body"])123    assert payload["delivery_id"] == did and uuid.UUID(did)124    return payload125126127async def test_job_finished_webhook_is_signed_and_delivered_once(stack, hook):128    job_id = await scrape_with_hook(stack, hook.url + "/hook")129    assert hook.received == []  # nothing is sent inline with the job130    await asyncio.gather(stack.maint.tick(), stack.maint.tick())  # concurrent ticks: still one delivery131    await stack.maint.tick()132    (rec,) = hook.at("/hook")133    assert rec["method"] == "POST"134    secret = await secret_of(stack)135    payload = verify(secret, rec)136    assert payload["event"] == "job.finished" and payload["job_id"] == job_id and payload["status"] == "succeeded"137    assert payload["urls"] == {"fetched": 1}138    # a tampered body or another tenant's secret does not verify139    with pytest.raises(AssertionError, match="signature"):140        verify(secret, rec | {"body": rec["body"].replace(b"succeeded", b"failed   ")})141    with pytest.raises(AssertionError, match="signature"):142        verify("0" * 64, rec)143    (row,) = await db(stack, "select id, status, attempts, last_error from webhook_deliveries")144    assert (row["status"], row["attempts"], row["last_error"]) == ("delivered", 1, None)145    assert str(row["id"]) == payload["delivery_id"]146    assert not any(q.path.startswith("/hook") for q in stack.site.state.requests)147148149async def test_failing_receiver_gets_bounded_retries_with_backoff_then_dead(stack, hook):150    from spider.scheduler import WEBHOOK_MAX_ATTEMPTS151    hook.status = 500152    await scrape_with_hook(stack, hook.url + "/hook")153    waits = []154    for n in range(1, WEBHOOK_MAX_ATTEMPTS + 1):155        await stack.maint.tick()156        (row,) = await db(stack, "select status, attempts, last_error, extract(epoch from next_attempt_at - now()) w "157                                 "from webhook_deliveries")158        assert row["attempts"] == n and row["last_error"] == "HTTP 500", dict(row)159        assert row["status"] == ("dead" if n == WEBHOOK_MAX_ATTEMPTS else "pending")160        waits.append(float(row["w"]))161        await stack.maint.tick()  # not due yet: no early retry162        assert len(hook.at("/hook")) == n, "retried before the backoff elapsed"163        await db(stack, "update webhook_deliveries set next_attempt_at = now() where status='pending'")164    assert len(hook.at("/hook")) == WEBHOOK_MAX_ATTEMPTS == 6165    # backoff grows (15 s x 4^n, capped at one hour)166    assert [round(w / 60) for w in waits[:4]] == [1, 4, 16, 60], waits167    assert [round(w) for w in waits[:5]] == sorted(round(w) for w in waits[:5])168    # dead means dead169    await db(stack, "update webhook_deliveries set next_attempt_at = now()")170    await stack.maint.tick()171    assert len(hook.at("/hook")) == 6172    # every attempt carries the same delivery id (receivers deduplicate on it) and a valid signature173    secret = await secret_of(stack)174    assert len({verify(secret, r)["delivery_id"] for r in hook.at("/hook")}) == 1175    # recovery: a later job is delivered normally176    hook.status = 200177    await scrape_with_hook(stack, hook.url + "/hook", path="/legal")178    await stack.maint.tick()179    assert len(hook.at("/hook")) == 7180181182async def test_webhook_redirect_is_not_followed(stack, hook):183    await scrape_with_hook(stack, hook.url + "/redirect")184    await stack.maint.tick()185    assert len(hook.at("/redirect")) == 1 and hook.at("/followed") == []186    (row,) = await db(stack, "select status, attempts, last_error from webhook_deliveries")187    assert (row["status"], row["attempts"], row["last_error"]) == ("pending", 1, "HTTP 302")188189190async def test_webhook_to_a_private_destination_is_refused_without_a_connection(stack, hook):191    srv = socket.socket()192    srv.bind(("127.0.0.1", 0))193    srv.listen(5)194    srv.setblocking(False)195    port = srv.getsockname()[1]  # a loopback port that is NOT in the test allowlist196    try:197        bad = f"http://127.0.0.1:{port}/steal"198        # refused when the job is submitted ...199        r = await stack.client.post("/v1/scrape", json={"url": stack.url("/about"), "render": "http",200                                                        "webhook": {"url": bad, "events": ["job.finished"]}})201        assert r.status_code == 422 and r.json()["error"]["code"] == "destination_not_allowed", r.text202        # ... and again at delivery time (a destination can become private after submission)203        await db(stack, "insert into webhook_deliveries(tenant_id, url, event, payload) values($1,$2,'job.finished','{}')",204                 stack.tenant_id, bad)205        await stack.maint.tick()206        (row,) = await db(stack, "select status, attempts, last_error from webhook_deliveries")207        assert row["status"] == "dead" and row["last_error"].startswith("destination refused"), dict(row)208        with pytest.raises(BlockingIOError):209            srv.accept()  # no connection attempt reached the private listener210        r = await stack.client.post("/v1/monitor", json={"name": "m", "request": {211            "url": stack.url("/about"), "webhook": {"url": "http://169.254.169.254/latest", "events": ["change.detected"]}}})212        assert r.status_code == 422 and r.json()["error"]["code"] == "destination_not_allowed"213    finally:214        srv.close()215216217async def test_change_detected_webhook_follows_the_cooldown(stack, hook):218    r = await stack.client.post("/v1/monitor", json={219        "name": "harbour", "interval_s": 3600, "cooldown_s": 3600, "watch": ["content"],220        "request": {"url": stack.url("/cond/changing"), "render": "http",221                    "webhook": {"url": hook.url + "/changes", "events": ["change.detected"]}}})222    assert r.status_code == 201, r.text223    sid = r.json()["id"]224225    async def run():226        n0 = len(await db(stack, "select 1 from jobs where schedule_id=$1", sid))227        assert (await stack.client.post(f"/v1/monitors/{sid}/run-now")).status_code == 200228        for _ in range(400):229            await stack.maint.tick()230            rows = await db(stack, "select status, stats from jobs where schedule_id=$1", sid)231            if len(rows) == n0 + 1 and all("compared" in j["stats"] for j in rows):232                return233            await asyncio.sleep(0.05)234        raise AssertionError("monitor run did not finish")235236    await run()237    assert hook.received == []238    stack.site.state.bump()239    await run()240    await stack.maint.tick()241    (rec,) = hook.at("/changes")242    payload = verify(await secret_of(stack), rec)243    assert payload["event"] == "change.detected" and payload["schedule_id"] == sid244    assert payload["kinds"] == ["content"] and payload["url"] == stack.url("/cond/changing")245    assert payload["summary"]["text"]["added"] == ["A north wind picked up before noon."]246    (ev,) = (await stack.client.get("/v1/changes", params={"schedule_id": sid})).json()["items"]247    assert ev["change_id"] == payload["change_id"] and ev["alerted"] is True248    stack.site.state.bump()  # second change inside the cooldown: recorded, not sent249    await run()250    await stack.maint.tick()251    evs = (await stack.client.get("/v1/changes", params={"schedule_id": sid})).json()["items"]252    assert [e["alerted"] for e in evs] == [False, True]  # newest first253    assert len(hook.at("/changes")) == 1254
Files main
Menu

Theme