SPB Git

Repository Public

test_tenant_isolation.py 17.0 KB 283 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/security/test_tenant_isolation.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"""Tenant isolation: another tenant's objects do not exist (404, never 403, never data)."""42import asyncio43import time4445import pytest46from apihelpers import (47    all_results,48    assert_error,49    client_for,50    db,51    finished_crawl,52    make_key,53    make_tenant,54    sha256,55    wait_job,56)5758pytestmark = pytest.mark.pg59SCHEMA = {"type": "object", "properties": {"title": {"type": "string"}}}606162async def _tenant_a_world(stack) -> dict:63    """Everything tenant A owns: a finished crawl, a schema, a connector, a monitor, a change event, a session."""64    a = stack.client65    job = await finished_crawl(stack, max_pages=5)66    items = await all_results(a, job["job_id"])67    schema = (await a.post("/v1/schemas", json={"name": "article", "json_schema": SCHEMA})).json()68    con = await a.post("/v1/connectors", json={"name": "blog", "domain": "127.0.0.1", "schema_id": schema["schema_id"],69                                               "rules": {"title": {"css": "h1"}}})70    assert con.status_code == 201, con.text71    mon = await a.post("/v1/monitor", json={"name": "watch-a", "request": {"url": stack.url("/cond/etag"), "render": "http"}})72    assert mon.status_code == 201, mon.text73    change = await db(stack, "insert into change_events(tenant_id, schedule_id, url, snapshot_a, snapshot_b, kinds, summary) "74                             "values($1,$2,$3,$4,$5,$6,$7) returning id", stack.tenant_id, mon.json()["id"],75                      items[0]["url"], items[0]["snapshot_id"], items[1]["snapshot_id"], ["content"], {"kinds": ["content"]},76                      one=True)77    return {"job": job, "items": items, "schema_id": schema["schema_id"], "connector_id": con.json()["connector_id"],78            "schedule_id": mon.json()["id"], "change_id": str(change),79            "artifacts": [x for it in items for x in it["artifacts"]]}808182async def test_other_tenant_gets_404_for_everything(stack):83    w = await _tenant_a_world(stack)84    a = stack.client85    jid, site = w["job"]["job_id"], w["job"]["site_id"]86    snap_a, snap_a2 = w["items"][0]["snapshot_id"], w["items"][1]["snapshot_id"]87    art = w["artifacts"][0]88    tid_b, _, b = await make_tenant(stack)89    # tenant B is a working tenant with its own data: the 404s below are not an empty-API artefact90    r = await b.post("/v1/scrape", json={"url": stack.url("/blog/post-1"), "render": "http"})91    assert r.status_code == 202, r.text92    job_b = await wait_job(b, r.json()["job_id"])93    assert job_b["status"] == "succeeded", job_b94    snap_b = (await all_results(b, job_b["job_id"]))[0]["snapshot_id"]9596    # ---- A's identifiers are 404 for B on every route that takes one97    denied = [98        ("GET", f"/v1/jobs/{jid}", None), ("GET", f"/v1/jobs/{jid}/results", None), ("GET", f"/v1/jobs/{jid}/events", None),99        ("GET", f"/v1/jobs/{jid}/frontier", None), ("POST", f"/v1/jobs/{jid}/cancel", None),100        ("POST", f"/v1/jobs/{jid}/pause", None), ("POST", f"/v1/jobs/{jid}/retry", None), ("DELETE", f"/v1/jobs/{jid}", None),101        *[("GET", f"/v1/jobs/{jid}/export?format={f}", None) for f in ("jsonl", "csv", "markdown", "html", "zip")],102        *[("GET", f"/v1/artifacts/{x['artifact_id']}", None) for x in w["artifacts"]],103        ("GET", f"/v1/snapshots/{snap_a}", None),104        ("GET", f"/v1/sites/{site}/graph", None), ("GET", f"/v1/sites/{site}/coverage", None),105        ("GET", f"/v1/sites/{site}/graph?job_id={jid}", None), ("GET", f"/v1/sites/{site}/coverage?job_id={jid}", None),106        ("GET", f"/v1/sites/{job_b['site_id']}/graph?job_id={jid}", None),107        *[("POST", f"/v1/monitors/{w['schedule_id']}/{act}", None) for act in ("disable", "enable", "run-now", "delete")],108        ("POST", f"/v1/connectors/{w['connector_id']}/validate", None),109        ("POST", f"/v1/connectors/{w['connector_id']}/status?status=disabled", None),110        ("POST", "/v1/connectors", {"name": "steal", "domain": "x.example", "rules": {}, "schema_id": w["schema_id"]}),111        ("POST", "/v1/extract", {"url": stack.url("/about"), "extract": {"schema_id": w["schema_id"]}}),112        ("POST", "/v1/extract", {"url": stack.url("/about"), "extract": {"connector_id": w["connector_id"]}}),113        ("POST", "/v1/ocr", {"artifact_id": art["artifact_id"]}),114        ("POST", "/v1/vision", {"artifact_ids": [art["artifact_id"]]}),115        ("POST", "/v1/diff", {"snapshot_a": snap_a, "snapshot_b": snap_a2}),116        ("POST", "/v1/diff", {"snapshot_a": snap_b, "snapshot_b": snap_a}),117        ("POST", "/v1/diff", {"snapshot_a": snap_a, "snapshot_b": snap_b}),118        ("DELETE", f"/v1/keys/{await _key_id(stack)}", None), ("POST", f"/v1/keys/{await _key_id(stack)}/rotate", None),119    ]120    for method, url, body in denied:121        r = await b.request(method, url, json=body)122        e = assert_error(r, 404, "not_found")123        assert stack.site.base_url not in r.text and jid not in e["message"], r.text124    # the owner sees every one of these objects (the identifiers used above are real)125    assert (await a.get(f"/v1/jobs/{jid}")).status_code == 200126    assert (await a.get(f"/v1/snapshots/{snap_a}")).status_code == 200127    assert (await a.get(f"/v1/artifacts/{art['artifact_id']}")).status_code == 200128    assert (await a.post("/v1/diff", json={"snapshot_a": snap_a, "snapshot_b": snap_a2})).status_code == 200129    assert_error(await a.post("/v1/ocr", json={"artifact_id": art["artifact_id"]}), 422, "not_an_image")130131    # ---- B's listings contain nothing of A132    for url, key in (("/v1/jobs", "items"), ("/v1/sites", "items"), ("/v1/monitors", "items"), ("/v1/schemas", "items"),133                     ("/v1/connectors", "items"), ("/v1/changes", "items"),134                     (f"/v1/changes?schedule_id={w['schedule_id']}", "items"),135                     (f"/v1/snapshots?url={w['items'][0]['url']}", "items")):136        r = await b.get(url)137        assert r.status_code == 200, r.text138        ids = r.text139        for secret in (jid, site, snap_a, w["schedule_id"], w["schema_id"], w["connector_id"], w["change_id"]):140            assert secret not in ids, f"{url} leaks {secret}"141    assert [j["job_id"] for j in (await b.get("/v1/jobs")).json()["items"]] == [job_b["job_id"]]142    assert (await b.get("/v1/monitors")).json()["items"] == [] and (await b.get("/v1/changes")).json()["items"] == []143    assert (await a.get("/v1/changes")).json()["items"][0]["change_id"] == w["change_id"]144    # search: B finds its own page only, whatever filter it sends145    word = "ferry" if "ferry" in w["items"][0]["content"]["markdown"].lower() else w["items"][0]["title"].split()[0]146    hits_a = (await a.post("/v1/search", json={"query": word})).json()["items"]147    assert len(hits_a) >= 2148    for body in ({"query": word}, {"query": word, "site_id": site}, {"query": word, "domain": "127.0.0.1"}):149        hits = (await b.post("/v1/search", json=body)).json()["items"]150        assert {h["snapshot_id"] for h in hits} <= {snap_b}, hits151    # accounting and audit are per tenant152    assert (await b.get("/v1/storage")).json()["artifacts"] == await db(153        stack, "select count(*) from artifacts where tenant_id=$1", tid_b, one=True)154    audit_b = (await b.get("/v1/audit")).text155    assert jid not in audit_b and w["schema_id"] not in audit_b and w["connector_id"] not in audit_b156    assert all(t["n"] <= 3 for t in (await b.get("/v1/queue")).json()["tasks"])157    usage_b = {(u["metric"]): u["value"] for u in (await b.get("/v1/usage")).json()["items"]}158    assert usage_b["jobs"] == 1 and usage_b["pages"] == 1159160    # ---- nothing B tried had an effect on A161    assert (await a.get(f"/v1/jobs/{jid}")).json()["status"] == w["job"]["status"]162    mon = [m for m in (await a.get("/v1/monitors")).json()["items"] if m["schedule_id"] == w["schedule_id"]]163    assert mon and mon[0]["enabled"] is True164    assert (await a.get("/v1/me")).status_code == 200  # A's key was neither revoked nor rotated165    assert await db(stack, "select count(*) from connectors where name='steal'", one=True) == 0166    assert await db(stack, "select count(*) from jobs where tenant_id=$1", tid_b, one=True) == 1167168169async def _key_id(stack) -> str:170    return (await stack.client.get("/v1/me")).json()["key_id"]171172173async def test_other_tenant_cannot_close_sessions_or_reuse_idempotency_keys(stack):174    _, _, b = await make_tenant(stack)175    kid = await _key_id(stack)176    browser = client_for(stack)177    assert (await browser.post("/v1/session", json={"api_key": stack.admin_key})).status_code == 200178    assert_error(await b.delete(f"/v1/keys/{kid}"), 404, "not_found")179    assert_error(await b.post(f"/v1/keys/{kid}/rotate"), 404, "not_found")180    assert (await browser.get("/v1/me")).status_code == 200, "another tenant closed this tenant's dashboard session"181    # idempotency keys live in a per-tenant namespace: no conflict, no replay of the other tenant's job182    body = {"url": stack.url("/about"), "render": "http"}183    ja = (await stack.client.post("/v1/scrape", json=body, headers={"Idempotency-Key": "shared-key"})).json()184    rb = await b.post("/v1/scrape", json=body | {"priority": 7}, headers={"Idempotency-Key": "shared-key"})185    assert rb.status_code == 202, rb.text186    assert rb.json()["job_id"] != ja["job_id"] and "idempotent_replay" not in rb.json()187188189async def test_signed_artifact_url_until_expiry_and_tamper_proof(stack):190    from spider import auth191    job = await finished_crawl(stack, max_pages=3)192    items = await all_results(stack.client, job["job_id"])193    arts = [x for it in items for x in it["artifacts"]]194    a1, a2 = arts[0], next(x for x in arts if x["sha256"] != arts[0]["sha256"])195    anon = client_for(stack)196    r = await anon.get(a1["url"])  # no Authorization header, no cookie197    assert r.status_code == 200 and sha256(r.content) == a1["sha256"] == r.headers["x-spider-sha256"]198    exp, sig = a1["url"].split("exp=")[1].split("&sig=")199    assert 0 < int(exp) - time.time() <= 300, "signed URLs must be short-lived"200    tampered = {201        "id swapped": f"/v1/artifacts/{a2['artifact_id']}?exp={exp}&sig={sig}",202        "exp extended": f"/v1/artifacts/{a1['artifact_id']}?exp={int(exp) + 3600}&sig={sig}",203        "sig altered": f"/v1/artifacts/{a1['artifact_id']}?exp={exp}&sig={sig[:-1]}{'0' if sig[-1] != '0' else '1'}",204        "sig truncated": f"/v1/artifacts/{a1['artifact_id']}?exp={exp}&sig={sig[:32]}",205        "sig empty": f"/v1/artifacts/{a1['artifact_id']}?exp={exp}&sig=",206        "sig non-ascii": f"/v1/artifacts/{a1['artifact_id']}?exp={exp}&sig=%C3%A9%C3%A9",207        "sig upper-case": f"/v1/artifacts/{a1['artifact_id']}?exp={exp}&sig={sig.upper()}x",208        "exp not a number": f"/v1/artifacts/{a1['artifact_id']}?exp=never&sig={sig}",209        "exp float": f"/v1/artifacts/{a1['artifact_id']}?exp={exp}.0&sig={sig}",210        "exp negative": f"/v1/artifacts/{a1['artifact_id']}?exp=-1&sig={sig}",211        "sig only": f"/v1/artifacts/{a1['artifact_id']}?sig={sig}",212        "other tenant in signature": f"/v1/artifacts/{a1['artifact_id']}?" + auth.signed_artifact_query(213            stack.settings.secret(), a1["artifact_id"], "00000000-0000-0000-0000-000000000000"),214        "wrong secret": f"/v1/artifacts/{a1['artifact_id']}?" + auth.signed_artifact_query(215            b"not-the-secret", a1["artifact_id"], stack.tenant_id),216        "unknown artifact": f"/v1/artifacts/00000000-0000-0000-0000-000000000000?exp={exp}&sig={sig}",217    }218    for name, url in tampered.items():219        r = await anon.get(url)220        assert r.status_code in (401, 404), f"{name}: {r.status_code}"221        assert_error(r, r.status_code)222        assert a1["sha256"] not in r.headers.get("x-spider-sha256", "") and len(r.content) < 400, name223    # expiry: a URL signed for three seconds works now and stops working afterwards224    short = f"/v1/artifacts/{a1['artifact_id']}?" + auth.signed_artifact_query(225        stack.settings.secret(), a1["artifact_id"], stack.tenant_id, ttl_s=3)226    assert (await anon.get(short)).status_code == 200227    await asyncio.sleep(4.1)228    assert_error(await anon.get(short), 404, "not_found")229    # the signed URL of one tenant's artifact is refused to nobody, but another tenant's *key* still gets 404230    _, _, b = await make_tenant(stack)231    assert_error(await b.get(f"/v1/artifacts/{a1['artifact_id']}"), 404, "not_found")232    _, wo = await make_key(stack, ["write"])  # same tenant, but no read scope233    assert_error(await client_for(stack, wo).get(f"/v1/artifacts/{a1['artifact_id']}"), 404, "not_found")234235236async def test_blob_deduplication_does_not_leak_across_tenants(stack):237    """Two tenants collecting identical bytes share one blob on disk and nothing else."""238    await stack.start_worker()239    body = {"url": stack.url("/legal"), "render": "http"}240    ja = await wait_job(stack.client, (await stack.client.post("/v1/scrape", json=body)).json()["job_id"])241    arts_a = (await all_results(stack.client, ja["job_id"]))[0]["artifacts"]242    html_a = next(x for x in arts_a if x["kind"] == "html")243    storage_before = (await stack.client.get("/v1/storage")).json()244    tid_b, _, b = await make_tenant(stack)245    rb = await b.post("/v1/scrape", json=body)246    jb = await wait_job(b, rb.json()["job_id"])247    res_b = await b.get(f"/v1/jobs/{jb['job_id']}/results")248    arts_b = res_b.json()["items"][0]["artifacts"]249    html_b = next(x for x in arts_b if x["kind"] == "html")250    # same content, one physical blob, two tenant-scoped artifact rows251    assert html_b["sha256"] == html_a["sha256"] and html_b["artifact_id"] != html_a["artifact_id"]252    assert await db(stack, "select count(*) from blobs where sha256=$1", html_a["sha256"], one=True) == 1253    owners = await db(stack, "select tenant_id::text from artifacts where sha256=$1 order by 1", html_a["sha256"])254    assert sorted(r["tenant_id"] for r in owners) == sorted([stack.tenant_id, tid_b])255    # B's view is exactly what a first-time collection looks like: same keys, no hint that the bytes pre-existed256    assert {k for x in arts_b for k in x} == {k for x in arts_a for k in x}257    for leak in (html_a["artifact_id"], ja["job_id"], stack.tenant_id, "dedup", "already", "stored\": false"):258        assert leak not in res_b.text and leak not in rb.text and leak not in str(jb), leak259    sb = (await b.get("/v1/storage")).json()260    assert sb["artifacts"] == len(arts_b) and sb["logical_bytes"] == sum(x["bytes"] for x in arts_b)261    assert sb["physical_bytes_referenced"] == sb["logical_bytes"]262    assert (await stack.client.get("/v1/storage")).json() == storage_before  # A's accounting is untouched263    got = await b.get(f"/v1/artifacts/{html_b['artifact_id']}")264    assert got.status_code == 200 and sha256(got.content) == html_b["sha256"]265    assert_error(await b.get(f"/v1/artifacts/{html_a['artifact_id']}"), 404, "not_found")266    assert_error(await stack.client.get(f"/v1/artifacts/{html_b['artifact_id']}"), 404, "not_found")267268269@pytest.mark.xfail(strict=True, reason="design: every tenant's admin key is a fleet operator (operator-wide kill "270                                       "switch, policy deletion, worker drain and worker registry are not tenant-scoped)")271async def test_tenant_admin_cannot_operate_the_fleet_of_other_tenants(stack):272    await stack.start_worker()273    _, _, b = await make_tenant(stack)274    workers = (await b.get("/v1/workers")).json().get("items", [])275    r = await b.put("/v1/policies", json={"domain": "*", "kill_switch": True})276    try:277        blocked = await stack.client.post("/v1/scrape", json={"url": stack.url("/about"), "render": "http"})278        assert blocked.status_code == 202, "tenant B stopped tenant A's collection with a global kill switch"279        assert workers == [], "tenant B can list (and drain) workers it does not own"280    finally:281        if r.status_code == 200:282            await stack.client.delete(f"/v1/policies/{r.json()['policy_id']}")283
Files main
Menu

Theme