Download coworker/tests/test_api.py from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/tests/test_api.py
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/coworker/tests/test_api.py
-
curl -L -o test_api.py https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/tests/test_api.py
20.4 kB
| """API: auth (cookie+CSRF, bearer, rate limit), RBAC per role, gate flows, SSE, kill switch, autonomy, audit, patch watch, | |
| schedules, users, pagination, error model, security headers.""" | |
| from __future__ import annotations | |
| import json | |
| import unittest | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from coworker.adapters.report_rule import summarize | |
| from coworker.tests.fakes import PASSWORD, bearer, make_app | |
| class ApiBase(unittest.TestCase): | |
| def setUpClass(cls): | |
| cls.app, cls.c, cls.svc, cls.pod = make_app() | |
| cls.h = {r: bearer(cls.c, r) for r in ("viewer", "consultant", "qa_approver", "admin")} | |
| def drain(self): | |
| self.app.state.runs.drain() | |
| def tearDown(self): | |
| # the app is shared by the class: a run a test left waiting would make the next identical start a DUPLICATE_RUN | |
| for st in ("queued", "running", "waiting_approval", "waiting_review"): | |
| for r in self.svc.db.list_runs(st, 1000): | |
| self.app.state.runs.cancel(r["run_id"], "test") | |
| def start(self, **body): | |
| body = {"modules": ["P2P"], "playwright_mode": "stub", **body} | |
| r = self.c.post("/api/runs", json=body, headers=self.h["consultant"]) | |
| self.assertEqual(r.status_code, 202, r.text) | |
| self.drain() | |
| return r.json()["run_id"] | |
| def get_run(self, rid): | |
| return self.c.get(f"/api/runs/{rid}", headers=self.h["viewer"]).json() | |
| class TestAuth(ApiBase): | |
| def test_401_without_token_and_error_model(self): | |
| r = self.c.get("/api/runs") | |
| self.assertEqual(r.status_code, 401) | |
| self.assertEqual(set(r.json()) >= {"detail", "code", "request_id"}, True) | |
| self.assertEqual(r.json()["code"], "UNAUTHENTICATED") | |
| self.assertTrue(r.headers.get("x-request-id")) | |
| def test_cookie_login_and_csrf(self): | |
| from fastapi.testclient import TestClient | |
| c = TestClient(self.app) | |
| r = c.post("/api/auth/login", json={"username": "consultant", "password": PASSWORD}) | |
| self.assertEqual(r.status_code, 200) | |
| self.assertIn("httponly", r.headers.get("set-cookie", "").lower()) | |
| csrf = r.json()["csrf_token"] | |
| self.assertEqual(c.get("/api/auth/me").json()["role"], "consultant") | |
| body = {"modules": ["P2P"], "playwright_mode": "stub"} | |
| self.assertEqual(c.post("/api/runs", json=body).json()["code"], "CSRF") | |
| self.assertEqual(c.post("/api/runs", json=body, headers={"X-CSRF-Token": "wrong"}).status_code, 403) | |
| r = c.post("/api/runs", json=body, headers={"X-CSRF-Token": csrf}) | |
| self.assertEqual(r.status_code, 202) | |
| self.app.state.runs.cancel(r.json()["run_id"], "test") | |
| self.assertEqual(c.post("/api/auth/logout", headers={"X-CSRF-Token": csrf}).status_code, 200) | |
| self.assertEqual(c.get("/api/auth/me").status_code, 401) | |
| def test_bad_password_and_rate_limit(self): | |
| for _ in range(5): | |
| self.assertEqual(self.c.post("/api/auth/token", json={"username": "viewer", "password": "nope-nope"}).status_code, 401) | |
| r = self.c.post("/api/auth/token", json={"username": "viewer", "password": PASSWORD}) | |
| self.assertEqual(r.status_code, 429) | |
| self.assertIn("retry-after", {k.lower() for k in r.headers}) | |
| def test_oidc_is_a_stub(self): | |
| self.assertEqual(self.c.get("/api/auth/oidc/login").json()["code"], "OIDC_NOT_CONFIGURED") | |
| def test_security_headers(self): | |
| r = self.c.get("/api/health") | |
| for h in ("content-security-policy", "x-content-type-options", "x-frame-options", "referrer-policy"): | |
| self.assertIn(h, {k.lower() for k in r.headers}) | |
| self.assertEqual(r.json()["target"], "Mock app, not Oracle Fusion") | |
| def test_embedded_mode_allows_one_site_and_relaxes_cookies(self): | |
| self.svc.cfg.embed_origin = "https://huggingface.co" | |
| try: | |
| r = self.c.get("/api/health") | |
| self.assertNotIn("x-frame-options", {k.lower() for k in r.headers}) | |
| self.assertIn("frame-ancestors 'self' https://huggingface.co", r.headers["content-security-policy"]) | |
| r = self.c.post("/api/auth/login", json={"username": "qa_approver", "password": PASSWORD}) | |
| self.assertEqual(r.status_code, 200, r.text) | |
| cookies = [v.lower() for k, v in r.headers.multi_items() if k.lower() == "set-cookie"] | |
| self.assertTrue(cookies and all("samesite=none" in c and "secure" in c for c in cookies), cookies) | |
| finally: | |
| self.svc.cfg.embed_origin = "" | |
| self.c.cookies.clear() | |
| self.assertIn("x-frame-options", {k.lower() for k in self.c.get("/api/health").headers}) | |
| def test_cors_restricted(self): | |
| r = self.c.options("/api/runs", headers={"Origin": "https://evil.example", "Access-Control-Request-Method": "GET"}) | |
| self.assertNotEqual(r.headers.get("access-control-allow-origin"), "https://evil.example") | |
| r = self.c.options("/api/runs", headers={"Origin": "http://127.0.0.1:5173", "Access-Control-Request-Method": "GET"}) | |
| self.assertEqual(r.headers.get("access-control-allow-origin"), "http://127.0.0.1:5173") | |
| class TestRBAC(ApiBase): | |
| def test_role_matrix(self): | |
| cases = [ # (method, path, body, allowed roles) | |
| ("post", "/api/runs", {"modules": ["P2P"], "playwright_mode": "stub"}, {"consultant", "qa_approver", "admin"}), | |
| ("post", "/api/kill-switch", {"engaged": False, "reason": "x"}, {"admin"}), | |
| ("put", "/api/autonomy/P2P", {"level": "L0"}, {"admin"}), | |
| ("get", "/api/audit", None, {"admin"}), | |
| ("get", "/api/users", None, {"admin"}), | |
| ("post", "/api/schedules", {"kind": "interval", "every_minutes": 600, "playwright_mode": "stub"}, {"admin"}), | |
| ("get", "/api/runs", None, {"viewer", "consultant", "qa_approver", "admin"}), | |
| ] | |
| for method, path, body, allowed in cases: | |
| for role, h in self.h.items(): | |
| r = getattr(self.c, method)(path, headers=h, **({"json": body} if body is not None else {})) | |
| if role in allowed: | |
| self.assertNotEqual(r.status_code, 403, (role, path, r.text)) | |
| else: | |
| self.assertEqual(r.status_code, 403, (role, path)) | |
| self.assertEqual(r.json()["code"], "FORBIDDEN") | |
| for r in self.svc.db.list_runs("queued"): | |
| self.app.state.runs.cancel(r["run_id"], "test") | |
| def test_gate_roles(self): | |
| rid = self.start(stub_knobs={"STUB_DEFECT": "P2P-APR-001"}) | |
| self.assertEqual(self.get_run(rid)["status"], "waiting_approval") | |
| g = self.c.get(f"/api/runs/{rid}/gate", headers=self.h["viewer"]).json() | |
| body = {"approved": [p["id"] for p in g["pending"]]} | |
| for role in ("viewer", "qa_approver"): | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/gates/approve_cases", json=body, headers=self.h[role]).status_code, 403) | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/gates/approve_cases", json=body, headers=self.h["consultant"]).status_code, 200) | |
| self.drain() | |
| self.assertEqual(self.get_run(rid)["status"], "waiting_review") | |
| rv = {"review": {"P2P-APR-001": {"confirmed": "real_defect"}}} | |
| for role in ("viewer", "consultant"): | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/gates/human_review", json=rv, headers=self.h[role]).status_code, 403) | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/gates/human_review", json=rv, headers=self.h["qa_approver"]).status_code, 200) | |
| self.drain() | |
| d = self.get_run(rid) | |
| self.assertEqual(d["status"], "completed") | |
| # actor recorded = authenticated user, never free text | |
| log = self.c.get(f"/api/runs/{rid}/cases", headers=self.h["viewer"]).json()["approval_log"] | |
| self.assertEqual({a["actor"] for a in log if a["gate"] == "approve_cases"}, {"consultant"}) | |
| self.assertEqual({a["actor"] for a in log if a["gate"] == "human_review"}, {"qa_approver"}) | |
| t = self.c.get(f"/api/tickets?run_id={rid}", headers=self.h["viewer"]).json() | |
| self.assertEqual(t["total"], 1) | |
| self.assertEqual(t["items"][0]["created_by"], "qa_approver") | |
| self.assertEqual(self.c.get("/api/evidence/1", headers=self.h["viewer"]).status_code, 403) | |
| class TestRunFlows(ApiBase): | |
| def test_admin_deletes_a_runs_evidence(self): | |
| rid = self.start() | |
| self.drain() | |
| ev = self.svc.db.insert("evidence", {"run_id": rid, "case_id": "P2P-APR-001", "attempt": 0, "name": "x/trace.zip", | |
| "content_type": "application/zip", "size": 3, "sha256": "x", "blob_path": str(self.svc.cfg.fpt_home / "nope.bin"), | |
| "expires_at": "2999-01-01T00:00:00+00:00", "purged": 0, "created_at": "2026-10-17T00:00:00+00:00"}) | |
| self.assertEqual(self.c.delete(f"/api/runs/{rid}/evidence", headers=self.h["consultant"]).status_code, 403) | |
| r = self.c.delete(f"/api/runs/{rid}/evidence", headers=self.h["admin"]) | |
| self.assertEqual((r.status_code, r.json()["files"]), (200, 1), r.text) | |
| self.assertEqual(self.c.get(f"/api/runs/{rid}/evidence", headers=self.h["admin"]).json(), []) | |
| self.assertTrue(ev) | |
| def test_approve_to_completed_and_report_equals_generate_report(self): | |
| rid = self.start() | |
| self.assertEqual(self.get_run(rid)["status"], "waiting_approval") | |
| g = self.c.get(f"/api/runs/{rid}/gate", headers=self.h["viewer"]).json() | |
| self.assertEqual(g["gate"], "approve_cases") | |
| bad = self.c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": ["P2P-NOPE-999"]}, headers=self.h["consultant"]) | |
| self.assertEqual(bad.status_code, 422) | |
| self.c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": [p["id"] for p in g["pending"]]}, headers=self.h["consultant"]) | |
| self.drain() | |
| d = self.get_run(rid) | |
| self.assertEqual(d["status"], "completed") | |
| rep = self.c.get(f"/api/runs/{rid}/report", headers=self.h["viewer"]).json() | |
| st = self.app.state.runs.state(rid) | |
| tri = json.loads(Path(st["triage_path"]).read_text()) | |
| self.assertEqual(rep["decisions"]["P2P"], summarize(tri, Path(st["report_root"]), {}, False, "P2P")["decision"]) | |
| self.assertEqual(set(rep["criteria"]["P2P"]), {"C1", "C2", "C3", "C4", "C5", "C6"}) | |
| md = self.c.get(f"/api/runs/{rid}/report/P2P/md", headers=self.h["viewer"]) | |
| self.assertEqual(md.status_code, 200) | |
| self.assertIn("STUB RUN", md.text) | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/gates/approve_cases", json={}, headers=self.h["consultant"]).json()["code"], "NOT_AT_GATE") | |
| # SSE: replays every event and ends on the terminal status | |
| s = self.c.get(f"/api/runs/{rid}/stream", headers=self.h["viewer"]) | |
| self.assertEqual(s.headers["content-type"].split(";")[0], "text/event-stream") | |
| self.assertIn("event: run_event", s.text) | |
| self.assertIn('event: end\ndata: {"status": "completed"}', s.text) | |
| evs = self.c.get(f"/api/runs/{rid}/events?after=0", headers=self.h["viewer"]).json() | |
| self.assertEqual(s.text.count("event: run_event"), len(evs)) | |
| page = self.c.get("/api/runs?limit=1&offset=0", headers=self.h["viewer"]).json() | |
| self.assertEqual((page["limit"], len(page["items"])), (1, 1)) | |
| self.assertGreaterEqual(page["total"], 1) | |
| def test_reject_all_defers(self): | |
| rid = self.start() | |
| g = self.c.get(f"/api/runs/{rid}/gate", headers=self.h["viewer"]).json() | |
| ids = [p["id"] for p in g["pending"]] | |
| self.c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": [], "rejected": ids}, headers=self.h["consultant"]) | |
| self.drain() | |
| cases = self.c.get(f"/api/runs/{rid}/cases", headers=self.h["viewer"]).json() | |
| self.assertTrue(set(ids) <= {d["id"] for d in cases["deferred"] if d["reason"] == "rejected at approval gate"}) | |
| def test_cancel(self): | |
| rid = self.start() | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/cancel", json={"reason": "x"}, headers=self.h["consultant"]).json()["status"], "cancelled") | |
| self.assertEqual(self.get_run(rid)["status"], "cancelled") | |
| def test_kill_switch_refuses_runs(self): | |
| self.assertTrue(self.c.post("/api/kill-switch", json={"engaged": True, "reason": "test"}, headers=self.h["admin"]).json()["engaged"]) | |
| r = self.c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub"}, headers=self.h["consultant"]) | |
| self.assertEqual((r.status_code, r.json()["code"]), (423, "KILL_SWITCH")) | |
| self.assertFalse(self.c.post("/api/kill-switch", json={"engaged": False}, headers=self.h["admin"]).json()["engaged"]) | |
| def test_autonomy_not_earned(self): | |
| r = self.c.put("/api/autonomy/P2P", json={"level": "L1"}, headers=self.h["admin"]) | |
| self.assertEqual((r.status_code, r.json()["code"]), (409, "NOT_EARNED")) | |
| self.assertIn("metrics", r.json()) | |
| self.assertEqual(self.c.put("/api/autonomy/P2P", json={"level": "L0"}, headers=self.h["admin"]).status_code, 200) | |
| def test_audit_verify_and_egress(self): | |
| self.assertTrue(self.c.get("/api/audit/verify", headers=self.h["admin"]).json()["ok"]) | |
| eg = self.c.get("/api/egress", headers=self.h["admin"]).json() | |
| self.assertTrue(all(r["kind"].startswith("egress.") for r in eg)) | |
| a = self.c.get("/api/audit?kind=egress.*&limit=5", headers=self.h["admin"]).json() | |
| self.assertLessEqual(len(a["items"]), 5) | |
| def test_patch_watch_autostart(self): | |
| sch = self.app.state.scheduler | |
| self.c.put("/api/patch-watch", json={"enabled": True, "autostart": True, "interval_s": 30, "modules": ["P2P"]}, headers=self.h["admin"]) | |
| self.pod.release = "26C" | |
| self.assertIsNone(sch.check_patch(datetime.now(timezone.utc))["run_id"]) | |
| self.pod.release = "26D" | |
| res = sch.check_patch(datetime.now(timezone.utc)) | |
| self.assertTrue(res["changed"]) | |
| self.assertTrue(res["run_id"]) | |
| self.assertEqual(self.svc.db.get_run(res["run_id"])["trigger"], "patch_watch") | |
| self.app.state.runs.cancel(res["run_id"], "test") | |
| self.c.put("/api/patch-watch", json={"enabled": False, "autostart": False}, headers=self.h["admin"]) | |
| def test_schedules_crud_and_due(self): | |
| s = self.c.post("/api/schedules", json={"kind": "interval", "every_minutes": 5, "modules": ["P2P"], "playwright_mode": "stub"}, | |
| headers=self.h["admin"]).json() | |
| self.svc.db.update("schedules", "id", s["id"], next_run_at="2000-01-01T00:00:00+00:00") | |
| out = self.app.state.scheduler.tick(datetime.now(timezone.utc)) | |
| self.assertEqual(len(out["started"]), 1) | |
| self.app.state.runs.cancel(out["started"][0], "test") | |
| self.assertEqual(self.c.delete(f"/api/schedules/{s['id']}", headers=self.h["admin"]).status_code, 204) | |
| def test_users_admin(self): | |
| r = self.c.post("/api/users", json={"username": "newbie", "password": "short", "role": "viewer"}, headers=self.h["admin"]) | |
| self.assertEqual(r.status_code, 422) | |
| r = self.c.post("/api/users", json={"username": "newbie", "password": "long-enough-password", "role": "viewer"}, headers=self.h["admin"]) | |
| self.assertEqual(r.status_code, 201) | |
| uid = r.json()["id"] | |
| self.assertEqual(self.c.patch(f"/api/users/{uid}", json={"disabled": True}, headers=self.h["admin"]).json()["disabled"], True) | |
| me = self.c.get("/api/auth/me", headers=self.h["admin"]).json() | |
| self.assertEqual(self.c.patch(f"/api/users/{me['id']}", json={"role": "viewer"}, headers=self.h["admin"]).json()["code"], "SELF_LOCKOUT") | |
| def test_ready_and_unknown_endpoint(self): | |
| self.assertTrue(self.c.get("/api/ready").json()["ready"]) | |
| self.assertEqual(self.c.get("/api/nope", headers=self.h["viewer"]).json()["code"], "NOT_FOUND") | |
| self.assertIn("/api/runs", self.c.get("/api/openapi.json").json()["paths"]) | |
| if __name__ == "__main__": | |
| unittest.main() | |
| class TestReviewFixesApi(ApiBase): | |
| def test_d6_human_review_rejects_unknown_cases(self): | |
| rid = self.start(stub_knobs={"STUB_DEFECT": "P2P-APR-001"}) | |
| g = self.c.get(f"/api/runs/{rid}/gate", headers=self.h["viewer"]).json() | |
| self.c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": [p["id"] for p in g["pending"]]}, headers=self.h["consultant"]) | |
| self.drain() | |
| self.assertEqual(self.get_run(rid)["status"], "waiting_review") | |
| bad = self.c.post(f"/api/runs/{rid}/gates/human_review", json={"review": {"P2P-NOT-PENDING-001": {"confirmed": "not_defect"}}}, | |
| headers=self.h["qa_approver"]) | |
| self.assertEqual((bad.status_code, bad.json()["code"]), (422, "UNKNOWN_CASES")) | |
| self.assertEqual(self.get_run(rid)["status"], "waiting_review") | |
| ok = self.c.post(f"/api/runs/{rid}/gates/human_review", json={"review": {"P2P-APR-001": {"confirmed": "not_defect"}}}, | |
| headers=self.h["qa_approver"]) | |
| self.assertEqual(ok.status_code, 200) | |
| self.drain() | |
| def test_d12_no_tracebacks_in_events_or_sse(self): | |
| self.pod.environment = "production" | |
| try: | |
| rid = self.start() | |
| finally: | |
| self.pod.environment = "test" | |
| self.assertEqual(self.get_run(rid)["status"], "failed") | |
| evs = self.c.get(f"/api/runs/{rid}/events", headers=self.h["viewer"]).json() | |
| err = [e for e in evs if e["kind"] == "error"] | |
| self.assertTrue(err) | |
| self.assertIn("error_id", err[0]["summary"]) | |
| self.assertNotIn("trace", json.dumps(evs)) | |
| self.assertNotIn("Traceback", self.c.get(f"/api/runs/{rid}/stream", headers=self.h["viewer"]).text) | |
| audit = self.c.get(f"/api/audit?kind=node.error&run_id={rid}", headers=self.h["admin"]).json()["items"] | |
| self.assertIn("Traceback", audit[0]["payload"]["trace"]) # kept for admins only | |
| def test_run_note_roles_and_audit(self): | |
| rid = self.start() | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/notes", json={"text": "hello"}, headers=self.h["viewer"]).status_code, 403) | |
| r = self.c.post(f"/api/runs/{rid}/notes", json={"text": "Checked the pending cases with the client."}, headers=self.h["consultant"]) | |
| self.assertEqual(r.status_code, 201) | |
| evs = [e for e in self.c.get(f"/api/runs/{rid}/events", headers=self.h["viewer"]).json() if e["kind"] == "note"] | |
| self.assertEqual((evs[0]["summary"]["by"], evs[0]["summary"]["text"]), ("consultant", "Checked the pending cases with the client.")) | |
| a = self.c.get(f"/api/audit?kind=run.note&run_id={rid}", headers=self.h["admin"]).json()["items"] | |
| self.assertEqual(a[0]["actor"], "consultant") | |
| self.assertEqual(self.c.post(f"/api/runs/{rid}/notes", json={"text": ""}, headers=self.h["consultant"]).status_code, 422) | |
| self.app.state.runs.cancel(rid, "test") | |
| class TestEmptyApprovalRefused(unittest.TestCase): | |
| def test_an_empty_answer_is_refused_and_skipping_all_must_be_explicit(self): | |
| app, c, svc, _ = make_app() | |
| h = bearer(c, "consultant") | |
| rid = c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub"}, headers=h).json()["run_id"] | |
| app.state.runs.drain() | |
| pending = [p["id"] for p in c.get(f"/api/runs/{rid}/gate", headers=h).json()["pending"]] | |
| self.assertTrue(pending) | |
| r = c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": [], "rejected": []}, headers=h) | |
| self.assertEqual((r.status_code, r.json()["code"]), (422, "NOTHING_APPROVED")) | |
| r = c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": [], "rejected": pending[:1]}, headers=h) | |
| self.assertEqual(r.json()["code"], "NOTHING_APPROVED") | |
| self.assertEqual(c.post(f"/api/runs/{rid}/gates/approve_cases", json={"approved": [], "rejected": pending}, headers=h).status_code, 200) | |