305 lines
14 KiB
Python
305 lines
14 KiB
Python
"""The ask-form proxy: admin calls pass through under the hub's bearer, the
|
|
events webhook queues for the hub from loopback only."""
|
|
|
|
import json
|
|
import threading
|
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
|
|
import pytest
|
|
from fastapi import FastAPI, HTTPException
|
|
from fastapi.testclient import TestClient
|
|
|
|
import askform
|
|
|
|
HUB = "hub-t0ken"
|
|
ADMIN = "adm1n"
|
|
|
|
|
|
class FakeAdmin(BaseHTTPRequestHandler):
|
|
"""A slice of `ask-form serve`'s admin API."""
|
|
forms = {"project-setup_k3f9q2": {"id": "project-setup_k3f9q2", "title": "Project setup",
|
|
"status": "pending", "meta": {"session": "s1"}}}
|
|
calls: list = []
|
|
health = {"ok": True, "version": "v0.5.0", "forms": 1}
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _send(self, code, obj):
|
|
data = json.dumps(obj).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def do_GET(self):
|
|
FakeAdmin.calls.append(("GET", self.path, self.headers.get("Authorization")))
|
|
if self.headers.get("Authorization") != f"Bearer {ADMIN}":
|
|
return self._send(401, {"error": "bad admin token"})
|
|
if self.path == "/v1/health":
|
|
return self._send(200, FakeAdmin.health)
|
|
if self.path.startswith("/v1/forms?") or self.path == "/v1/forms":
|
|
want = self.path.partition("status=")[2].split("&")[0]
|
|
forms = [f for f in self.forms.values() if not want or f["status"] == want]
|
|
return self._send(200, {"forms": forms, "count": len(forms)})
|
|
fid = self.path.split("/")[3].split("?")[0]
|
|
f = self.forms.get(fid)
|
|
if not f:
|
|
return self._send(404, {"error": f"unknown form {fid}"})
|
|
out = dict(f)
|
|
if "fields=1" in self.path:
|
|
out["fields"] = [{"key": "stack", "label": "Stack", "type": "radio"}]
|
|
self._send(200, out)
|
|
|
|
def do_POST(self):
|
|
FakeAdmin.calls.append(("POST", self.path, self.headers.get("Authorization")))
|
|
if self.headers.get("Authorization") != f"Bearer {ADMIN}":
|
|
return self._send(401, {"error": "bad admin token"})
|
|
if self.path == "/v1/forms":
|
|
length = int(self.headers.get("Content-Length") or "0")
|
|
body = json.loads(self.rfile.read(length).decode() or "{}") if length else {}
|
|
if not body.get("title"):
|
|
return self._send(400, {"error": "title required"})
|
|
fid = "created-form_abc123"
|
|
rec = {
|
|
"id": fid,
|
|
"title": body["title"],
|
|
"description": body.get("description") or "",
|
|
"status": "pending",
|
|
"url": f"http://127.0.0.1:7462/f/{fid}?token=tok1",
|
|
"publicUrl": f"https://ask-form.xyz/f/{fid}?token=tok1",
|
|
"meta": body.get("meta") or {},
|
|
"fields": body.get("fields") or [],
|
|
}
|
|
self.forms[fid] = rec
|
|
return self._send(201, rec)
|
|
fid = self.path.split("/")[3]
|
|
f = self.forms.get(fid)
|
|
if not f:
|
|
return self._send(404, {"error": f"unknown form {fid}"})
|
|
if f["status"] != "pending":
|
|
return self._send(409, {**f, "warning": "already " + f["status"]})
|
|
f["status"] = "revoked"
|
|
self._send(200, f)
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def admin():
|
|
srv = HTTPServer(("127.0.0.1", 0), FakeAdmin)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
yield f"http://127.0.0.1:{srv.server_port}"
|
|
srv.shutdown()
|
|
|
|
|
|
def _hub_auth(h):
|
|
if h != f"Bearer {HUB}":
|
|
raise HTTPException(401, "unauthorized")
|
|
|
|
|
|
@pytest.fixture()
|
|
def client(admin, monkeypatch):
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_URL", admin)
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_TOKEN", ADMIN)
|
|
queued = []
|
|
app = FastAPI()
|
|
app.include_router(askform.make_router(_hub_auth, lambda ev: queued.append(ev) or {"id": "afe_x", "status": "queued"}))
|
|
# Loopback client: the events webhook takes only those.
|
|
c = TestClient(app, headers={"Authorization": f"Bearer {HUB}"}, client=("127.0.0.1", 40000))
|
|
c.queued = queued
|
|
return c
|
|
|
|
|
|
def test_token_resolution(tmp_path, monkeypatch):
|
|
monkeypatch.delenv("ASK_FORM_ADMIN_TOKEN", raising=False)
|
|
monkeypatch.setenv("ASK_FORM_CONFIG", str(tmp_path))
|
|
assert not askform.installed()
|
|
(tmp_path / "admin-token").write_text("abc\n")
|
|
assert askform.admin_token() == "abc"
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_TOKEN", "fromenv")
|
|
assert askform.admin_token() == "fromenv"
|
|
|
|
|
|
def test_health_and_list(client):
|
|
assert client.get("/ask-form/health").json()["version"] == "v0.5.0"
|
|
r = client.get("/ask-form/forms?status=pending")
|
|
assert r.status_code == 200 and r.json()["count"] == 1
|
|
assert ("GET", "/v1/forms?status=pending", f"Bearer {ADMIN}") in FakeAdmin.calls
|
|
|
|
|
|
def test_create_form(client):
|
|
r = client.post("/ask-form/forms", json={
|
|
"title": "Approve deploy",
|
|
"fields": [{"key": "decision", "label": "Decision", "type": "radio", "options": ["Approve", "Deny"]}],
|
|
"meta": {"session": "s2", "ownerOnly": True},
|
|
})
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert body["id"] == "created-form_abc123"
|
|
assert body["publicUrl"].startswith("https://ask-form.xyz/f/created-form_abc123")
|
|
assert ("POST", "/v1/forms", f"Bearer {ADMIN}") in FakeAdmin.calls
|
|
assert client.post("/ask-form/forms", json={}).status_code == 400
|
|
FakeAdmin.forms.pop("created-form_abc123", None)
|
|
|
|
|
|
def test_get_with_fields_and_bad_ids(client):
|
|
r = client.get("/ask-form/forms/project-setup_k3f9q2?fields=1")
|
|
assert r.json()["fields"][0]["key"] == "stack"
|
|
assert client.get("/ask-form/forms/nope").status_code == 400 # not an id shape
|
|
assert client.get("/ask-form/forms/missing_aaaaaa").status_code == 404
|
|
|
|
|
|
def test_revoke_passes_409_as_state(client):
|
|
assert client.post("/ask-form/forms/project-setup_k3f9q2/revoke").json()["status"] == "revoked"
|
|
r = client.post("/ask-form/forms/project-setup_k3f9q2/revoke") # again: already revoked
|
|
assert r.status_code == 200 and r.json()["warning"] == "already revoked"
|
|
|
|
|
|
def test_hub_bearer_required(client):
|
|
assert client.get("/ask-form/forms", headers={"Authorization": "Bearer nope"}).status_code == 401
|
|
|
|
|
|
def test_not_installed_is_503(admin, monkeypatch, tmp_path):
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_URL", admin)
|
|
monkeypatch.delenv("ASK_FORM_ADMIN_TOKEN", raising=False)
|
|
monkeypatch.setenv("ASK_FORM_CONFIG", str(tmp_path))
|
|
app = FastAPI()
|
|
app.include_router(askform.make_router(_hub_auth))
|
|
c = TestClient(app, headers={"Authorization": f"Bearer {HUB}"})
|
|
r = c.get("/ask-form/forms")
|
|
assert r.status_code == 503 and r.json()["detail"]["kind"] == "askform_missing"
|
|
assert c.get("/ask-form/health").json() == {"installed": False, "ok": False}
|
|
|
|
|
|
def test_server_down_is_503(monkeypatch):
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_URL", "http://127.0.0.1:1")
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_TOKEN", ADMIN)
|
|
app = FastAPI()
|
|
app.include_router(askform.make_router(_hub_auth))
|
|
c = TestClient(app, headers={"Authorization": f"Bearer {HUB}"})
|
|
assert c.get("/ask-form/forms").json()["detail"]["kind"] == "askform_down"
|
|
|
|
|
|
def test_events_webhook(client):
|
|
ev = {"event": "created", "form": {"id": "project-setup_k3f9q2", "title": "Project setup",
|
|
"status": "pending", "url": "https://ask-form.xyz/f/project-setup_k3f9q2?token=t"}}
|
|
r = client.post("/ask-form/events", json=ev, headers={"Authorization": ""})
|
|
assert r.status_code == 200 and client.queued == [ev]
|
|
assert client.post("/ask-form/events", json={"event": "nope", "form": {"id": "x_aaaaaa"}}).status_code == 400
|
|
assert client.post("/ask-form/events", json={"event": "created", "form": {"id": "bad id"}}).status_code == 400
|
|
|
|
|
|
def test_events_refused_off_this_machine(admin, monkeypatch):
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_URL", admin)
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_TOKEN", ADMIN)
|
|
monkeypatch.setenv("SIDECAR_BIND", "100.64.0.7")
|
|
app = FastAPI()
|
|
app.include_router(askform.make_router(_hub_auth, lambda ev: {"id": "afe_x"}))
|
|
ev = {"event": "created", "form": {"id": "x_aaaaaa"}}
|
|
assert TestClient(app, client=("100.64.0.9", 40000)).post("/ask-form/events", json=ev).status_code == 403
|
|
# A worker's serve reaches its sidecar on the Tailscale address it binds.
|
|
assert TestClient(app, client=("100.64.0.7", 40000)).post("/ask-form/events", json=ev).status_code == 200
|
|
|
|
|
|
# ── wiring a guest's ask-form to this sidecar ────────────────────────────────
|
|
@pytest.fixture()
|
|
def wired(admin, monkeypatch, tmp_path):
|
|
"""An installed ask-form (admin token + config dir) whose admin API is the fake."""
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_URL", admin)
|
|
monkeypatch.setenv("ASK_FORM_ADMIN_TOKEN", ADMIN)
|
|
monkeypatch.setenv("ASK_FORM_CONFIG", str(tmp_path))
|
|
monkeypatch.setenv("SIDECAR_PORT", "8790")
|
|
monkeypatch.setitem(FakeAdmin.forms["project-setup_k3f9q2"], "status", "submitted")
|
|
return tmp_path
|
|
|
|
|
|
def test_wire_events_writes_serve_env_once_and_restarts(wired):
|
|
restarts = []
|
|
env = wired / "serve.env"
|
|
env.write_text("ASK_FORM_RELAY=https://ask-form.xyz\nASK_FORM_LANG=fr\n")
|
|
assert askform.wire_events(lambda: restarts.append(1) or True) == "wired"
|
|
text = env.read_text()
|
|
assert "ASK_FORM_RELAY=https://ask-form.xyz" in text and "ASK_FORM_LANG=fr" in text
|
|
assert text.count("ASK_FORM_EVENTS_URL=http://127.0.0.1:8790/ask-form/events") == 1
|
|
assert env.stat().st_mode & 0o777 == 0o600
|
|
# Wired and restarted since: nothing more to do, no second restart.
|
|
assert askform.wire_events(lambda: restarts.append(1) or True) == "already"
|
|
assert restarts == [1]
|
|
|
|
|
|
def test_wire_events_leaves_an_owners_own_events_url(wired):
|
|
(wired / "serve.env").write_text("ASK_FORM_EVENTS_URL='https://hooks.example/x'\n")
|
|
assert askform.wire_events(lambda: pytest.fail("no restart")) == "own"
|
|
assert "hooks.example" in (wired / "serve.env").read_text()
|
|
|
|
|
|
def test_wire_events_waits_for_an_open_form_before_restarting(wired, monkeypatch):
|
|
monkeypatch.setitem(FakeAdmin.forms["project-setup_k3f9q2"], "status", "pending")
|
|
restarts = []
|
|
assert askform.wire_events(lambda: restarts.append(1) or True) == "busy"
|
|
assert restarts == []
|
|
assert "ASK_FORM_EVENTS_URL=" in (wired / "serve.env").read_text()
|
|
# The form is answered: the next pass restarts it, once.
|
|
FakeAdmin.forms["project-setup_k3f9q2"]["status"] = "submitted"
|
|
assert askform.wire_events(lambda: restarts.append(1) or True) == "wired"
|
|
assert askform.wire_events(lambda: restarts.append(1) or True) == "already"
|
|
assert restarts == [1]
|
|
|
|
|
|
def test_wire_events_without_ask_form_is_a_no_op(monkeypatch, tmp_path):
|
|
monkeypatch.delenv("ASK_FORM_ADMIN_TOKEN", raising=False)
|
|
monkeypatch.setenv("ASK_FORM_CONFIG", str(tmp_path))
|
|
assert askform.wire_events() == "off"
|
|
assert not (tmp_path / "serve.env").exists()
|
|
|
|
|
|
# ── letting the hub frame this machine's forms ───────────────────────────────
|
|
HUBS = ["https://ai-agent.lab.example", "https://claude.lab.example"]
|
|
|
|
|
|
def test_wire_embed_adds_the_hub_keeps_the_owners_and_restarts(wired, monkeypatch):
|
|
monkeypatch.setattr(FakeAdmin, "health", {"ok": True, "version": "v0.16.0"})
|
|
env = wired / "serve.env"
|
|
env.write_text("ASK_FORM_RELAY=https://ask-form.xyz\nASK_FORM_EMBED_ORIGINS=https://mine.example\n")
|
|
restarts = []
|
|
assert askform.wire_embed(HUBS, lambda: restarts.append(1) or True) == "wired"
|
|
text = env.read_text()
|
|
assert "ASK_FORM_RELAY=https://ask-form.xyz" in text
|
|
assert text.count("ASK_FORM_EMBED_ORIGINS=") == 1
|
|
assert askform._env_embed(text) == ["https://mine.example", *HUBS]
|
|
assert env.stat().st_mode & 0o777 == 0o600
|
|
assert restarts == [1]
|
|
# serve now reports them: nothing more to do.
|
|
monkeypatch.setattr(FakeAdmin, "health", {"ok": True, "version": "v0.16.0",
|
|
"embedOrigins": ["https://mine.example", *HUBS]})
|
|
assert askform.wire_embed(HUBS, lambda: pytest.fail("no restart")) == "already"
|
|
|
|
|
|
def test_wire_embed_waits_for_open_forms(wired, monkeypatch):
|
|
monkeypatch.setattr(FakeAdmin, "health", {"ok": True, "version": "v0.16.1"})
|
|
monkeypatch.setitem(FakeAdmin.forms["project-setup_k3f9q2"], "status", "pending")
|
|
assert askform.wire_embed(HUBS, lambda: pytest.fail("no restart")) == "busy"
|
|
assert askform._env_embed((wired / "serve.env").read_text()) == HUBS
|
|
FakeAdmin.forms["project-setup_k3f9q2"]["status"] = "submitted"
|
|
restarts = []
|
|
assert askform.wire_embed(HUBS, lambda: restarts.append(1) or True) == "wired"
|
|
assert askform._env_embed((wired / "serve.env").read_text()) == HUBS # not doubled
|
|
assert restarts == [1]
|
|
|
|
|
|
def test_wire_embed_leaves_an_old_serve_alone(wired):
|
|
# FakeAdmin's default health is v0.5.0: it would ignore the variable.
|
|
assert askform.wire_embed(HUBS, lambda: pytest.fail("no restart")) == "old"
|
|
assert not (wired / "serve.env").exists()
|
|
|
|
|
|
def test_embed_route(client, monkeypatch, tmp_path):
|
|
monkeypatch.setenv("ASK_FORM_CONFIG", str(tmp_path))
|
|
monkeypatch.setattr(FakeAdmin, "health", {"ok": True, "version": "v0.16.0", "embedOrigins": HUBS})
|
|
assert client.post("/ask-form/embed", json={"origins": HUBS}).json() == {"state": "already"}
|
|
for bad in ({}, {"origins": []}, {"origins": ["https://*.x"]}, {"origins": ["http://evil.example"]},
|
|
{"origins": ["https://x.example/path"]}, {"origins": ["https://x.example'; x"]}):
|
|
assert client.post("/ask-form/embed", json=bad).status_code == 400, bad
|
|
r = client.post("/ask-form/embed", json={"origins": HUBS}, headers={"Authorization": "Bearer nope"})
|
|
assert r.status_code == 401
|