Files
gabrielvidal b000f4f8e0 fix(guests): push endpoints are push services, a ceiling on wrong sign-in codes, a Bash switch for No-project chats
Any https endpoint was accepted and a 307 from it re-POSTed to the hub's own
loopback as the owner. Sign-in codes: 10 wrong per address a day, 20 per IP in
10 min, 4 mails per address an hour, sent off the request thread. `scratchBash`
per guest (on by default) sets scope.noBash when off. Caps on guest ui-state
and drafts; the host-file secret filter follows links; enroll and terminal
claims re-checked.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

157 lines
8.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Composer drafts on the server (drafts/): per user, last write wins, the SSE
event names its user, a guest only ever reaches their own.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import json
import os
import pathlib
import tempfile
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"DRAFTS_PATH": TMP / "drafts.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
(TMP / "projects").mkdir(parents=True, exist_ok=True)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from core.routes import _guest_filter # noqa: E402
from drafts.store import DraftStore, MAX_KEYS # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
LIVE = json.dumps({"text": "started on the phone", "tags": ["project:homelab"]})
class Store(unittest.TestCase):
def test_round_trip_and_reload(self):
p = TMP / "s1.json"
s = DraftStore(str(p))
r = s.put("owner", "draft:spawn:personal", LIVE, "tabA", now_ms=1000)
self.assertEqual((r["updatedAt"], r["device"]), (1000, "tabA"))
# never back in time: a write in the same ms still moves forward
self.assertEqual(s.put("owner", "draft:spawn:personal", LIVE, "tabB", now_ms=900)["updatedAt"], 1001)
self.assertEqual(DraftStore(str(p)).get("owner", "draft:spawn:personal")["device"], "tabB")
self.assertTrue(s.delete("owner", "draft:spawn:personal"))
self.assertFalse(s.delete("owner", "draft:spawn:personal"))
self.assertEqual(DraftStore(str(p)).list("owner"), [])
def test_refuses_bad_input(self):
s = DraftStore(str(TMP / "s2.json"))
for key in ("spawn:x", "draft:", "draft:a/b", "../x", "draft:" + "x" * 200):
with self.assertRaises(ValueError, msg=key):
s.put("owner", key, LIVE)
with self.assertRaises(ValueError):
s.put("owner", "draft:k", "not json")
with self.assertRaises(ValueError):
s.put("owner", "draft:k", json.dumps("x" * (600 * 1024)))
# an odd device name is dropped, not stored
self.assertEqual(s.put("owner", "draft:k", LIVE, "a b<c>")["device"], "")
def test_users_apart_and_capped(self):
s = DraftStore(str(TMP / "s3.json"))
s.put("owner", "draft:k", LIVE)
s.put("dom", "draft:k", json.dumps({"text": "dom's"}))
self.assertEqual(json.loads(s.get("dom", "draft:k")["value"])["text"], "dom's")
self.assertEqual(json.loads(s.get("owner", "draft:k")["value"])["text"], "started on the phone")
for i in range(MAX_KEYS + 5):
s.put("claire", f"draft:resume:{i}", LIVE, now_ms=10_000 + i)
keys = [d["key"] for d in s.list("claire")]
self.assertEqual(len(keys), MAX_KEYS)
self.assertNotIn("draft:resume:0", keys) # the stalest went
self.assertEqual(keys[0], f"draft:resume:{MAX_KEYS + 4}") # newest first
def test_a_users_drafts_have_a_total_size(self):
"""400 keys × 512 KB of one user must not be what the file holds:
past MAX_TOTAL the stalest go, never the one being written."""
from drafts import store as ds
s = DraftStore(str(TMP / "s4.json"))
self.addCleanup(setattr, ds, "MAX_TOTAL", ds.MAX_TOTAL)
ds.MAX_TOTAL = 2 * 1024 * 1024 # the real one makes a slow test
big = json.dumps("x" * (500 * 1024))
n = ds.MAX_TOTAL // len(big) + 3
for i in range(n):
s.put("dom", f"draft:resume:{i}", big, now_ms=10_000 + i)
keys = [d["key"] for d in s.list("dom")]
self.assertLess(len(keys), n)
self.assertLessEqual(sum(len(d["value"]) for d in s.list("dom")), ds.MAX_TOTAL)
self.assertEqual(keys[0], f"draft:resume:{n - 1}") # the newest stays
self.assertNotIn("draft:resume:0", keys) # the stalest went
s.put("claire", "draft:k", LIVE) # another user's are untouched
self.assertEqual(len(s.list("claire")), 1)
class Routes(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={})
for uid in ("owner", self.dom["id"]):
for d in DEPS.draft_store.list(uid):
DEPS.draft_store.delete(uid, d["key"])
self.events = []
orig = DEPS.hub.publish
DEPS.hub.publish = lambda ev: self.events.append(ev)
self.addCleanup(setattr, DEPS.hub, "publish", orig)
def guest(self):
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
return c
def test_owner_put_get_list_delete(self):
c = TestClient(main.app)
r = c.put("/api/drafts/draft:spawn:personal", json={"value": LIVE, "device": "tab1"}, headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.events[-1]["type"], "drafts")
self.assertEqual((self.events[-1]["user"], self.events[-1]["key"], self.events[-1]["device"]),
("owner", "draft:spawn:personal", "tab1"))
self.assertEqual(c.get("/api/drafts/draft:spawn:personal", headers=OWNER_H).json()["value"], LIVE)
self.assertEqual([d["key"] for d in c.get("/api/drafts", headers=OWNER_H).json()["drafts"]],
["draft:spawn:personal"])
self.assertEqual(c.delete("/api/drafts/draft:spawn:personal?device=tab1", headers=OWNER_H).status_code, 200)
self.assertTrue(self.events[-1]["deleted"])
self.assertEqual(c.get("/api/drafts/draft:spawn:personal", headers=OWNER_H).status_code, 404)
self.assertEqual(c.put("/api/drafts/nope", json={"value": LIVE}, headers=OWNER_H).status_code, 400)
self.assertEqual(c.put("/api/drafts/draft:k", json={"value": "{"}, headers=OWNER_H).status_code, 400)
def test_guest_has_their_own(self):
g = self.guest()
self.assertEqual(g.put("/api/drafts/draft:spawn:guests", json={"value": LIVE}).status_code, 200)
self.assertEqual(self.events[-1]["user"], self.dom["id"])
self.assertEqual(len(g.get("/api/drafts").json()["drafts"]), 1)
# the owner's list doesn't have it, and the guest never sees the owner's
c = TestClient(main.app)
self.assertEqual(c.get("/api/drafts", headers=OWNER_H).json()["drafts"], [])
c.put("/api/drafts/draft:spawn:personal", json={"value": LIVE}, headers=OWNER_H)
self.assertEqual([d["key"] for d in g.get("/api/drafts").json()["drafts"]], ["draft:spawn:guests"])
self.assertEqual(g.get("/api/drafts/draft:spawn:personal").status_code, 404)
def test_guest_stream_carries_only_theirs(self):
caller = type("C", (), {"id": self.dom["id"], "is_owner": False})()
flt = _guest_filter(DEPS, caller)
mine = {"type": "drafts", "user": self.dom["id"], "key": "draft:k"}
self.assertEqual(flt(mine), mine)
self.assertIsNone(flt({"type": "drafts", "user": "owner", "key": "draft:k"}))
self.assertIsNone(flt({"type": "drafts", "user": "claire", "key": "draft:k"}))
if __name__ == "__main__":
unittest.main()