"""Backend API: tokens, OTP, run_chat, FastAPI routes (mock LLM via conftest).""" from __future__ import annotations import os import pytest @pytest.fixture() def store(tmp_path, monkeypatch): monkeypatch.delenv("DATABASE_URL", raising=False) monkeypatch.setenv("CP_DB_PATH", str(tmp_path / "t.db")) from controlplane.app import store as s s._engine, s._initialised = None, False yield s s._engine, s._initialised = None, False def test_token_roundtrip_and_tamper(): from controlplane.api.tokens import mint_user_token, verify_user_token u = {"id": "u1", "email": "a@x.io", "name": "A"} t = mint_user_token(u, "s3cret", ttl_s=60, now=1000.0) assert t.startswith("cp1.") p = verify_user_token(t, "s3cret", now=1030.0) assert p == {"uid": "u1", "email": "a@x.io", "name": "A", "exp": 1060} assert verify_user_token(t, "s3cret", now=1061.0) is None # expired assert verify_user_token(t, "other", now=1030.0) is None # wrong secret assert verify_user_token(t[:-2] + "zz", "s3cret", now=1030.0) is None assert verify_user_token("garbage", "s3cret") is None def test_otp_request_and_check(store): from controlplane.api import otp sent = {} ok, msg = otp.request_code("Bob@Example.com", send=lambda to, code: sent.update(to=to, code=code)) assert ok and sent["to"] == "bob@example.com" and len(sent["code"]) == 6 assert otp.check_code("bob@example.com", "000000")[0] is None user, msg = otp.check_code("bob@example.com", sent["code"]) assert user["email"] == "bob@example.com" and user["provider"] == "email" assert otp.check_code("bob@example.com", sent["code"])[0] is None # single use def test_otp_rejects_bad_email_and_rate_limits(store): from controlplane.api import otp assert otp.request_code("not-an-email", send=lambda *a: None)[0] is False for _ in range(3): assert otp.request_code("c@x.io", send=lambda *a: None)[0] is True ok, msg = otp.request_code("c@x.io", send=lambda *a: None) assert ok is False and "Too many" in msg def test_run_chat_streams_and_persists(store): from controlplane.api.chat import run_chat u = store.upsert_user("d@x.io", "", "email") ev = list(run_chat(u["id"], query="How do I get a refund for my order?", thread_id=None, forced_kb=None)) kinds = [k for k, _ in ev] assert kinds[0] == "meta" and kinds[-1] == "done" and "final" in kinds tid = ev[0][1]["thread_id"] hist, state = store.load_thread(u["id"], tid) assert [m["role"] for m in hist] == ["user", "assistant"] and state["final_decision"] assert not any(k.startswith("_") for k in state) def test_run_chat_rejects_foreign_thread_and_rate_limit(store): from controlplane.api.chat import run_chat a = store.upsert_user("a@x.io", "", "email") b = store.upsert_user("b@x.io", "", "email") tid = store.create_thread(a["id"], "t") with pytest.raises(PermissionError): next(run_chat(b["id"], query="hi", thread_id=tid, forced_kb=None)) store.add_message(a["id"], tid, "user", "already asked once") with pytest.raises(RuntimeError): next(run_chat(a["id"], query="hi", thread_id=None, forced_kb=None, hourly_limit=1)) def test_run_chat_hitl_expired(store): from controlplane.api.chat import run_chat u = store.upsert_user("e@x.io", "", "email") tid = store.create_thread(u["id"], "t") with pytest.raises(LookupError): next(run_chat(u["id"], query=None, thread_id=tid, forced_kb=None, resume="x", graph_thread="gone")) # ------------------------------------------------------------------ FastAPI ---- @pytest.fixture() def client(store, monkeypatch): monkeypatch.setenv("BACKEND_SECRET", "s3cret") monkeypatch.setenv("CP_SKIP_WARMUP", "1") monkeypatch.setenv("ALLOWED_ORIGINS", "http://localhost:3000") from fastapi.testclient import TestClient from controlplane.api.server import create_app return TestClient(create_app()) def _utok(uid, email="u@x.io"): from controlplane.api.tokens import mint_user_token return {"Authorization": "Bearer " + mint_user_token({"id": uid, "email": email, "name": ""}, "s3cret")} def test_health_open_and_auth_required(client): assert client.get("/api/health").json()["ok"] is True assert client.get("/api/threads").status_code == 401 assert client.get("/api/threads", headers={"Authorization": "Bearer nope"}).status_code == 401 def test_cors_only_for_allowed_origin(client): ok = client.options("/api/threads", headers={"Origin": "http://localhost:3000", "Access-Control-Request-Method": "GET", "Access-Control-Request-Headers": "authorization"}) assert ok.headers.get("access-control-allow-origin") == "http://localhost:3000" bad = client.get("/api/health", headers={"Origin": "http://evil.example"}) assert "access-control-allow-origin" not in bad.headers def test_otp_endpoints_need_service_secret(client, store): r = client.post("/api/auth/otp/send", json={"email": "x@x.io"}) assert r.status_code == 401 r = client.post("/api/auth/upsert", json={"email": "g@x.io", "name": "G", "provider": "google"}, headers={"Authorization": "Bearer s3cret"}) assert r.status_code == 200 and r.json()["email"] == "g@x.io" r = client.post("/api/auth/otp/send", json={"email": "bad"}, headers={"Authorization": "Bearer s3cret"}) assert r.status_code == 200 and r.json()["ok"] is False def test_meta_threads_cache_for_user(client, store): a = store.upsert_user("m@x.io", "", "email") m = client.get("/api/meta", headers=_utok(a["id"])).json() assert len(m["kbs"]) == 5 and m["demo_prompts"] and m["hourly_limit"] >= 0 assert client.get("/api/threads", headers=_utok(a["id"])).json()["threads"] == [] assert client.get("/api/cache", headers=_utok(a["id"])).json()["size"] == 0 assert client.delete("/api/cache", headers=_utok(a["id"])).json()["ok"] is True def test_query_validation_and_rate_limit(client, store, monkeypatch): a = store.upsert_user("c@x.io", "", "email") assert client.post("/api/query", json={"query": ""}, headers=_utok(a["id"])).status_code == 422 assert client.post("/api/query", json={"query": "x" * 2001}, headers=_utok(a["id"])).status_code == 422 # limit semantics (0 = unlimited) are covered by test_hourly_limit_zero_means_unlimited def test_resume_without_checkpoint_is_410(client, store): a = store.upsert_user("r@x.io", "", "email") tid = store.create_thread(a["id"], "t") r = client.post("/api/resume", json={"thread_id": tid, "graph_thread": "gone", "reply": "x"}, headers=_utok(a["id"])) assert r.status_code == 410 and r.json()["detail"] == "hitl_expired" def test_query_stream_and_thread_isolation(client, store): a = store.upsert_user("a@x.io", "", "email") b = store.upsert_user("b@x.io", "", "email") r = client.post("/api/query", json={"query": "How do I get a refund for my order?"}, headers=_utok(a["id"])) assert r.status_code == 200 and r.headers["content-type"].startswith("text/event-stream") body = r.text assert "event: meta" in body and "event: final" in body and body.rstrip().endswith("data: {}") tid = client.get("/api/threads", headers=_utok(a["id"])).json()["threads"][0]["id"] assert client.get(f"/api/threads/{tid}", headers=_utok(a["id"])).json()["history"][0]["role"] == "user" assert client.get(f"/api/threads/{tid}", headers=_utok(b["id"])).status_code == 404 assert client.get("/api/threads", headers=_utok(b["id"])).json()["threads"] == [] assert client.delete(f"/api/threads/{tid}", headers=_utok(a["id"])).json()["ok"] is True assert client.get("/api/threads", headers=_utok(a["id"])).json()["threads"] == [] # ------------------------------------------------------------ review fixes ---- def test_hourly_limit_zero_means_unlimited(store): from controlplane.api.chat import rate_limited u = store.upsert_user("lim@x.io", "", "email") tid = store.create_thread(u["id"], "t") store.add_message(u["id"], tid, "user", "one question already") assert rate_limited(u["id"], 0) is False # 0 / negative = unlimited (docs + Streamlit) assert rate_limited(u["id"], -1) is False assert rate_limited(u["id"], 1) is True # 1 per hour, one already asked assert rate_limited(u["id"], 2) is False def test_rate_limit_via_http_uses_existing_messages(client, store, monkeypatch): a = store.upsert_user("lim2@x.io", "", "email") tid = store.create_thread(a["id"], "t") store.add_message(a["id"], tid, "user", "asked") monkeypatch.setenv("CP_USER_HOURLY_LIMIT", "1") from fastapi.testclient import TestClient from controlplane.api.server import create_app r = TestClient(create_app()).post("/api/query", json={"query": "hi"}, headers=_utok(a["id"])) assert r.status_code == 429 and "limit of 1 " in r.json()["detail"] def test_resume_graph_thread_must_belong_to_caller(store): from controlplane.api import chat from controlplane.api.chat import run_chat a = store.upsert_user("own1@x.io", "", "email") b = store.upsert_user("own2@x.io", "", "email") tid_b = store.create_thread(b["id"], "t") chat.remember_graph_owner("run-abc", a["id"]) with pytest.raises(PermissionError): # B presents A's paused run id next(run_chat(b["id"], query=None, thread_id=tid_b, forced_kb=None, resume="x", graph_thread="run-abc")) tid_a = store.create_thread(a["id"], "t") with pytest.raises(LookupError): # A owns it but the checkpoint is gone -> expired next(run_chat(a["id"], query=None, thread_id=tid_a, forced_kb=None, resume="x", graph_thread="run-abc")) assert chat.graph_owner("run-abc") is None # a failed/expired resume forgets the id # ------------------------------------------------------- Gradio Space entry ---- def test_space_entry_serves_api_and_status_page(store, monkeypatch): """app.py (Hugging Face Gradio-SDK Space) must expose the same API plus a status page at '/', and must not start the warm-up when it is skipped.""" import importlib import sys monkeypatch.setenv("BACKEND_SECRET", "s3cret") monkeypatch.setenv("CP_SKIP_WARMUP", "1") from fastapi.testclient import TestClient sys.modules.pop("app", None) mod = importlib.import_module("app") c = TestClient(mod.app) assert c.get("/api/health").json()["ok"] is True assert c.get("/api/health").json()["warm"]["step"] == "skipped" assert c.get("/api/threads").status_code == 401 page = c.get("/") assert page.status_code == 200 and "gradio" in page.text.lower() # the Space has no build step: models must be allowed to download at boot assert os.environ.get("CP_DETOXIFY_ALLOW_DOWNLOAD") == "1" assert "HF_HUB_OFFLINE" not in os.environ # ZeroGPU refuses a Space with "No @spaces.GPU function detected": one must be # registered and wired to the Gradio page, even though the pipeline is CPU-only assert callable(mod.gpu_probe) and mod.gpu_probe("ping").startswith("ping") assert any(getattr(d.get("fn") if isinstance(d, dict) else d, "fn", None) is mod.gpu_probe or (isinstance(d, dict) and d.get("fn") is mod.gpu_probe) for d in getattr(mod.demo, "fns", {}).values()), "gpu_probe is not a Gradio event handler" def test_space_entry_ignores_runtime_port_variable(store, monkeypatch): """ZeroGPU sets PORT=7861 (and holds that port); a Gradio Space is proxied on 7860 (GRADIO_SERVER_PORT). app.py must never bind to PORT.""" import importlib import sys monkeypatch.setenv("BACKEND_SECRET", "s3cret") monkeypatch.setenv("CP_SKIP_WARMUP", "1") monkeypatch.setenv("PORT", "7861") monkeypatch.delenv("GRADIO_SERVER_PORT", raising=False) sys.modules.pop("app", None) mod = importlib.import_module("app") assert mod.PORT == 7860 monkeypatch.setenv("GRADIO_SERVER_PORT", "7865") sys.modules.pop("app", None) assert importlib.import_module("app").PORT == 7865