GET …/hub/notify/push/{id}/image: the image recorded on the handler's user's
own push, as bytes (image/* only, at most 5 MB). A picture on the hub itself is
read through the file route it names with that route's own check; a public one
through image_proxy.fetch; a lab address is never fetched.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
475 lines
25 KiB
Python
475 lines
25 KiB
Python
"""``notify.respond`` (plugins/hubnotify.py, 2026-11-28) — a phone channel's
|
|
way back: its handler answers an ask, taps a push's button, marks pushes
|
|
dismissed and reads one back **as the person it runs for, for their own pushes
|
|
only**; the addresses their app pairs with. Plus what the android-push plugin
|
|
needed beside it: webhooks that answer their action's own JSON (or a file) and
|
|
GET.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
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",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"WEBPUSH_PATH": TMP / "webpush.json", "VAPID_KEY_PATH": TMP / "vapid.pem",
|
|
"PLUGINS_DIR": TMP / "plugins", "TOOLS_TOKEN_KEY": TMP / "tools.key",
|
|
"PROJECTS_DIR": TMP / "projects",
|
|
"INTERNAL_API_TOKEN": "tok",
|
|
"GUEST_HOSTS": "guest.example.test", "OWNER_HOSTS": "hub.example.test",
|
|
"GUEST_PUBLIC_URL": "https://guest.example.test",
|
|
"AI_AGENT_VIEW_URL": "https://admin.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from notifications.service import _create_ask, _create_notify # noqa: E402
|
|
from plugins import manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
PID = "phone"
|
|
OWNER_SID = "aaaaaaaa-1111-4111-8111-111111111111"
|
|
GUEST_SID = "bbbbbbbb-2222-4222-8222-222222222222"
|
|
|
|
# The webhook's action: says what it got, or what the body asks it to say.
|
|
HOOK = r'''
|
|
import json, os, sys
|
|
d = json.load(sys.stdin)
|
|
b = d.get("body") or {}
|
|
if b.get("say"):
|
|
print(json.dumps(b["say"]))
|
|
else:
|
|
print(json.dumps({"ok": True, "got": b, "trigger": d.get("trigger"),
|
|
"uid": json.loads(os.environ["AIA_USER_CONTEXT"])["uid"]}))
|
|
'''
|
|
# Records the clears the channel is sent.
|
|
SEND = r'''
|
|
import json, os, pathlib, sys
|
|
d = json.load(sys.stdin)
|
|
with (pathlib.Path(os.environ["AIA_PLUGIN_DATA_DIR"]) / "got.jsonl").open("a") as f:
|
|
f.write(json.dumps(d) + "\n")
|
|
print(json.dumps({"ok": True}))
|
|
'''
|
|
MANIFEST = {
|
|
"schema": 1, "id": PID, "name": "Phone",
|
|
"capabilities": ["notify.respond"],
|
|
"actions": {"hook": {"script": "handlers/hook.py"}, "send": {"script": "handlers/send.py"}},
|
|
"provides": {"notify.channel": "send"},
|
|
"webhooks": [
|
|
{"id": "app", "mode": "action", "action": "hook", "respond": "result"},
|
|
{"id": "apk", "mode": "action", "action": "hook", "respond": "result", "methods": ["GET"]},
|
|
{"id": "plain", "mode": "action", "action": "hook"},
|
|
],
|
|
}
|
|
|
|
|
|
def _src(root: pathlib.Path, mf: dict = MANIFEST, pid: str = PID) -> pathlib.Path:
|
|
(root / "handlers").mkdir(parents=True, exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps({**mf, "id": pid}))
|
|
(root / "handlers" / "hook.py").write_text(HOOK)
|
|
(root / "handlers" / "send.py").write_text(SEND)
|
|
return root
|
|
|
|
|
|
_GUESTS: list[str] = []
|
|
|
|
|
|
def _guests() -> list[str]:
|
|
if not _GUESTS:
|
|
_GUESTS.extend(DEPS.users.create(f"{n.lower()}@example.test", n)["id"] for n in ("Cel", "Dom"))
|
|
return _GUESTS
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.tc = TestClient(main.app)
|
|
cls.guest, cls.other = _guests()
|
|
DEPS.meta_store.update(GUEST_SID, {"owner": cls.guest})
|
|
DEPS.meta_store.update(OWNER_SID, {"title": "mine"})
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.store = PluginStore(pathlib.Path(self.tmp.name) / "data")
|
|
src = _src(pathlib.Path(self.tmp.name) / "src")
|
|
for uid in (OWNER_UID, self.guest, self.other):
|
|
self.store.install(uid, str(src), is_owner=True, approve=True)
|
|
p = patch.object(DEPS, "plugin_store", self.store)
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
self.addCleanup(self.tmp.cleanup)
|
|
|
|
def call(self, method, path, uid=OWNER_UID, pid=PID, token=None, **kw):
|
|
tok = token or access.mint_handler(uid, pid, ttl=600)
|
|
return self.tc.request(method, f"/proxy/tools/plugins/{pid}/hub/notify/{path}",
|
|
headers={"Authorization": f"Bearer {tok}"}, **kw)
|
|
|
|
def clears(self, uid=OWNER_UID):
|
|
p = self.store.user_data_dir(uid, PID) / "got.jsonl"
|
|
deadline = time.time() + 2
|
|
while time.time() < deadline and not p.exists():
|
|
time.sleep(0.05)
|
|
time.sleep(0.1)
|
|
rows = [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
|
|
return [r["push"]["tags"] for r in rows if r["event"] == "clear"]
|
|
|
|
def ask(self, sid=""):
|
|
return _create_ask(DEPS, {"question": "Deploy?", "options": ["Yes", "No"],
|
|
"sessionId": sid})["id"]
|
|
|
|
|
|
class TestManifest(unittest.TestCase):
|
|
def test_a_capability_a_guest_may_approve(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = manifest.validate_manifest(_src(pathlib.Path(td)))
|
|
self.assertIn("notify.respond", mf["capabilities"])
|
|
self.assertFalse(manifest.requires_operator(mf))
|
|
labels = [i["label"] for i in manifest.capability_summary(mf)]
|
|
self.assertTrue(any("Answers your questions" in x for x in labels), labels)
|
|
|
|
def test_respond_and_methods_are_written_only_when_set(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = manifest.validate_manifest(_src(pathlib.Path(td)))
|
|
app, apk, plain = mf["webhooks"]
|
|
self.assertEqual((app["respond"], app.get("methods")), ("result", None))
|
|
self.assertEqual(apk["methods"], ["GET"])
|
|
self.assertNotIn("respond", plain)
|
|
self.assertNotIn("methods", plain)
|
|
|
|
def test_bad_respond_or_methods_are_refused(self):
|
|
for patch_ in ({"respond": "raw"}, {"methods": ["PUT"]}):
|
|
bad = {**MANIFEST, "webhooks": [{"id": "x", "mode": "action", "action": "hook", **patch_}]}
|
|
with tempfile.TemporaryDirectory() as td, self.assertRaises(manifest.ManifestError):
|
|
manifest.validate_manifest(_src(pathlib.Path(td), bad))
|
|
notify = {**MANIFEST, "webhooks": [{"id": "x", "mode": "notify", "respond": "result"}]}
|
|
with tempfile.TemporaryDirectory() as td, self.assertRaises(manifest.ManifestError):
|
|
manifest.validate_manifest(_src(pathlib.Path(td), notify))
|
|
|
|
def test_an_older_webhook_keeps_its_fingerprint(self):
|
|
plain = {**MANIFEST, "webhooks": [{"id": "plain", "mode": "action", "action": "hook"}]}
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = manifest.validate_manifest(_src(pathlib.Path(td), plain))
|
|
wider = manifest.validate_manifest(_src(pathlib.Path(td) / "w", {
|
|
**MANIFEST, "webhooks": [{"id": "plain", "mode": "action", "action": "hook",
|
|
"respond": "result"}]}))
|
|
self.assertEqual(mf["webhooks"][0], {
|
|
"id": "plain", "mode": "action", "titleTemplate": "Phone: {{title}}",
|
|
"promptTemplate": "{{body}}", "action": "hook", "description": "",
|
|
"internalOnly": False})
|
|
self.assertNotEqual(manifest.capability_fingerprint(mf), manifest.capability_fingerprint(wider))
|
|
|
|
|
|
class TestGate(Base):
|
|
def test_handler_token_and_capability_are_required(self):
|
|
run = access.mint(self.guest) # a guest's run token
|
|
self.assertEqual(self.call("GET", "pairing", token=run).status_code, 403)
|
|
self.assertEqual(self.call("GET", "pairing", token="nope").status_code, 401)
|
|
bare = _src(pathlib.Path(self.tmp.name) / "bare", {**MANIFEST, "capabilities": []}, "bare")
|
|
self.store.install(OWNER_UID, str(bare), is_owner=True, approve=True)
|
|
r = self.call("GET", "pairing", pid="bare")
|
|
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "capability"))
|
|
|
|
def test_never_on_a_public_host(self):
|
|
tok = access.mint_handler(OWNER_UID, PID, ttl=600)
|
|
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/notify/pairing",
|
|
headers={"Authorization": f"Bearer {tok}", "Host": "guest.example.test"})
|
|
self.assertEqual(r.status_code, 401)
|
|
|
|
|
|
class TestPairing(Base):
|
|
def test_the_owner_gets_the_public_address_then_the_tailnet(self):
|
|
d = self.call("GET", "pairing").json()
|
|
tok = self.store.get_raw(OWNER_UID, PID)["webhookTokens"]
|
|
self.assertTrue(d["isOwner"])
|
|
pub, tail = d["addresses"]
|
|
# The app opens the owner's own host; its webhook goes through the
|
|
# guest host, the only public one serving /proxy/tools/.
|
|
self.assertEqual((pub["id"], pub["hub"]), ("public", "https://hub.example.test"))
|
|
self.assertEqual(pub["hooks"]["app"],
|
|
f"https://guest.example.test/proxy/tools/plugins/{PID}/webhook/app?token={tok['app']}")
|
|
self.assertEqual((tail["id"], tail["hub"]), ("tailnet", "https://admin.example.test"))
|
|
self.assertTrue(tail["hooks"]["apk"].startswith(
|
|
f"https://admin.example.test/proxy/tools/plugins/{PID}/webhook/apk?token={tok['apk']}"))
|
|
self.assertEqual(d["origins"], ["https://admin.example.test", "https://guest.example.test",
|
|
"https://hub.example.test"])
|
|
|
|
def test_a_guest_gets_the_guest_host_and_their_own_token(self):
|
|
d = self.call("GET", "pairing", uid=self.guest).json()
|
|
tok = self.store.get_raw(self.guest, PID)["webhookTokens"]["app"]
|
|
self.assertEqual((d["user"], d["uid"], d["isOwner"]), ("Cel", self.guest, False))
|
|
[a] = d["addresses"]
|
|
self.assertEqual(a["hub"], "https://guest.example.test")
|
|
self.assertIn(f"token={tok}", a["hooks"]["app"])
|
|
self.assertNotEqual(tok, self.store.get_raw(OWNER_UID, PID)["webhookTokens"]["app"])
|
|
|
|
|
|
class TestAnswer(Base):
|
|
def test_the_owner_answers_their_ask_and_the_first_answer_wins(self):
|
|
aid = self.ask()
|
|
r = self.call("POST", "answer", json={"id": aid, "index": 1})
|
|
self.assertEqual((r.status_code, r.json()), (200, {"ok": True, "id": aid, "index": 1, "label": "No"}))
|
|
self.assertEqual(DEPS.notify_store.get(aid)["answer"], "No")
|
|
again = self.call("POST", "answer", json={"id": aid, "index": 0})
|
|
self.assertEqual((again.status_code, again.json()["error"]["kind"]), (409, "answered"))
|
|
self.assertEqual(DEPS.notify_store.get(aid)["answer"], "No")
|
|
# …and the hub took it off the owner's channels, as it always does.
|
|
self.assertIn([aid], self.clears())
|
|
|
|
def test_a_guest_cannot_touch_the_owners_ask(self):
|
|
aid = self.ask() # no session: the owner's
|
|
r = self.call("POST", "answer", uid=self.guest, json={"id": aid, "index": 0})
|
|
self.assertEqual(r.status_code, 404)
|
|
self.assertEqual(self.call("GET", f"push/{aid}", uid=self.guest).status_code, 404)
|
|
self.assertEqual(DEPS.notify_store.get(aid)["status"], "pending")
|
|
|
|
def test_a_guest_answers_their_own_and_nobody_elses(self):
|
|
aid = self.ask(GUEST_SID)
|
|
self.assertEqual(self.call("POST", "answer", uid=self.other,
|
|
json={"id": aid, "index": 0}).status_code, 404)
|
|
# The owner doesn't hear a guest's conversation he doesn't follow: his
|
|
# phone never got this ask, so his channel can't answer it.
|
|
self.assertEqual(self.call("POST", "answer", json={"id": aid, "index": 0}).status_code, 404)
|
|
r = self.call("POST", "answer", uid=self.guest, json={"id": aid, "index": 0})
|
|
self.assertEqual((r.status_code, r.json()["label"]), (200, "Yes"))
|
|
|
|
def test_bad_input(self):
|
|
aid = self.ask()
|
|
self.assertEqual(self.call("POST", "answer", json={"id": aid}).status_code, 400)
|
|
self.assertEqual(self.call("POST", "answer", json={"id": aid, "index": 7}).status_code, 400)
|
|
self.assertEqual(self.call("POST", "answer", json={"id": "ask_000000000000", "index": 0}).status_code, 404)
|
|
nid = _create_notify(DEPS, {"title": "t", "message": "m"})["id"]
|
|
self.assertEqual(self.call("POST", "answer", json={"id": nid, "index": 0}).status_code, 404)
|
|
|
|
def test_an_expired_ask_says_so(self):
|
|
aid = self.ask()
|
|
DEPS.notify_store._update(aid, {"expiresAt": "2020-01-01T00:00:00Z"})
|
|
r = self.call("POST", "answer", json={"id": aid, "index": 0})
|
|
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (409, "expired"))
|
|
|
|
|
|
class TestPushAndAction(Base):
|
|
def push(self, **kw):
|
|
nid = "ntf_" + os.urandom(6).hex()
|
|
d = {"id": nid, "title": "PR ready", "message": "long " * 300, "type": "git",
|
|
"actions": [{"action": f"{nid}__0", "title": "Merge"},
|
|
{"action": f"{nid}__1", "title": "Later"}], **kw}
|
|
return _create_notify(DEPS, d)["id"]
|
|
|
|
def test_get_reads_the_whole_push_back(self):
|
|
nid = self.push()
|
|
d = self.call("GET", f"push/{nid}").json()
|
|
self.assertTrue(d["ok"])
|
|
p = d["push"]
|
|
self.assertEqual((p["id"], p["kind"], p["title"], p["type"]), (nid, "notify", "PR ready", "git"))
|
|
self.assertEqual(p["body"], "long " * 300)
|
|
self.assertEqual([a["title"] for a in p["actions"]], ["Merge", "Later"])
|
|
self.assertNotIn("delivered", p)
|
|
aid = self.ask()
|
|
a = self.call("GET", f"push/{aid}").json()["push"]
|
|
self.assertEqual((a["kind"], a["body"], a["options"], a["status"]),
|
|
("ask", "Deploy?", ["Yes", "No"], "pending"))
|
|
|
|
def test_a_guest_reads_their_push_on_their_host(self):
|
|
nid = _create_notify(DEPS, {"title": "t", "message": "m", "sessionId": GUEST_SID,
|
|
"url": "https://admin.example.test/conversation/x"})["id"]
|
|
p = self.call("GET", f"push/{nid}", uid=self.guest).json()["push"]
|
|
self.assertEqual(p["url"], "https://guest.example.test/conversation/x")
|
|
self.assertEqual(self.call("GET", f"push/{nid}", uid=self.other).status_code, 404)
|
|
|
|
def test_a_button_by_its_id_first_tap_wins(self):
|
|
nid = self.push()
|
|
with patch("plugins.scheduler.dispatch_event") as ev:
|
|
r = self.call("POST", "action", json={"id": nid, "action": f"{nid}__1"})
|
|
self.assertEqual(r.json(), {"ok": True, "id": nid, "index": 1, "title": "Later",
|
|
"already": False})
|
|
again = self.call("POST", "action", json={"id": nid, "index": 0}).json()
|
|
self.assertEqual((again["index"], again["title"], again["already"]), (1, "Later", True))
|
|
ev.assert_called_once()
|
|
self.assertEqual(ev.call_args.args[1:], ("notify.action", {"notifyId": nid, "index": 1,
|
|
"title": "Later"}))
|
|
|
|
def test_a_button_that_is_not_theirs_or_not_there(self):
|
|
nid = self.push()
|
|
self.assertEqual(self.call("POST", "action", uid=self.guest,
|
|
json={"id": nid, "index": 0}).status_code, 404)
|
|
self.assertEqual(self.call("POST", "action", json={"id": nid, "action": "nope"}).status_code, 400)
|
|
self.assertEqual(self.call("POST", "action", json={"id": nid, "index": 5}).status_code, 400)
|
|
self.assertEqual(DEPS.notify_store.get(nid)["status"], "sent")
|
|
|
|
|
|
class TestPushImage(Base):
|
|
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 64
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.dir = pathlib.Path(self.tmp.name) / "files"
|
|
self.dir.mkdir()
|
|
(self.dir / "shot.png").write_bytes(self.PNG)
|
|
(self.dir / "notes.txt").write_text("secret")
|
|
|
|
# The file route's own check: the owner reads anything here, a guest
|
|
# only what is "theirs".
|
|
def resolve(caller, path):
|
|
from types import SimpleNamespace
|
|
if not caller.is_owner and not path.startswith("mine/"):
|
|
return None
|
|
return SimpleNamespace(abs=self.dir / path.removeprefix("mine/"))
|
|
p = patch("files.browse.resolve", resolve)
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
|
|
def push(self, image, sid=""):
|
|
return _create_notify(DEPS, {"title": "t", "message": "m", "image": image,
|
|
"sessionId": sid})["id"]
|
|
|
|
def test_a_picture_on_the_hub_is_served_as_bytes(self):
|
|
for image in ("https://admin.example.test/api/host-file/raw?path=shot.png",
|
|
"/api/host-file/raw?path=shot.png",
|
|
"https://hub.example.test/api/host-file/raw?path=shot.png"):
|
|
r = self.call("GET", f"push/{self.push(image)}/image")
|
|
self.assertEqual((r.status_code, r.content, r.headers["content-type"]),
|
|
(200, self.PNG, "image/png"), image)
|
|
|
|
def test_only_the_push_owner_and_only_what_they_may_read(self):
|
|
nid = self.push("/api/host-file/raw?path=shot.png")
|
|
self.assertEqual(self.call("GET", f"push/{nid}/image", uid=self.guest).status_code, 404)
|
|
# A guest's own push naming a file the route refuses them: nothing.
|
|
gid = self.push("/api/host-file/raw?path=shot.png", GUEST_SID)
|
|
self.assertEqual(self.call("GET", f"push/{gid}/image", uid=self.guest).status_code, 404)
|
|
ok = self.push("/api/host-file/raw?path=mine/shot.png", GUEST_SID)
|
|
self.assertEqual(self.call("GET", f"push/{ok}/image", uid=self.guest).content, self.PNG)
|
|
self.assertEqual(self.call("GET", f"push/{ok}/image", uid=self.other).status_code, 404)
|
|
|
|
def test_not_an_open_door(self):
|
|
for image in ("/api/host-file/raw?path=notes.txt", # not an image
|
|
"/api/host-file/raw?path=nope.png", # no such file
|
|
"/api/host-file/raw", # no path
|
|
"/api/users", "/api/notify-log", # not a file route
|
|
"http://127.0.0.1:9/x.png", "http://10.0.0.1/x.png", # the lab
|
|
"file:///etc/passwd", "//evil.example/x.png", ""):
|
|
nid = self.push(image)
|
|
self.assertEqual(self.call("GET", f"push/{nid}/image").status_code, 404, image)
|
|
self.assertEqual(self.call("GET", "push/ntf_000000000000/image").status_code, 404)
|
|
|
|
def test_too_big_is_refused_and_the_owner_only_routes(self):
|
|
with patch("notifications.image_proxy.MAX_BYTES", 10):
|
|
nid = self.push("/api/host-file/raw?path=shot.png")
|
|
self.assertEqual(self.call("GET", f"push/{nid}/image").status_code, 404)
|
|
with patch("files.assets.screenshot_asset") as shot:
|
|
gid = self.push("/api/screenshot?path=x.png", GUEST_SID)
|
|
self.assertEqual(self.call("GET", f"push/{gid}/image", uid=self.guest).status_code, 404)
|
|
shot.assert_not_called()
|
|
|
|
def test_a_public_picture_goes_through_the_image_proxy(self):
|
|
nid = self.push("https://cdn.example.test/a.png")
|
|
with patch("notifications.image_proxy.fetch", return_value=(self.PNG, "image/png")) as f:
|
|
r = self.call("GET", f"push/{nid}/image")
|
|
self.assertEqual((r.status_code, r.content), (200, self.PNG))
|
|
f.assert_called_once_with("https://cdn.example.test/a.png")
|
|
|
|
|
|
class TestDismissed(Base):
|
|
def test_the_owners_swipe_is_dismissed_in_the_app_and_cleared_elsewhere(self):
|
|
nid = _create_notify(DEPS, {"title": "t", "message": "m"})["id"]
|
|
twin = _src(pathlib.Path(self.tmp.name) / "twin", {**MANIFEST, "webhooks": []}, "twin")
|
|
self.store.install(OWNER_UID, str(twin), is_owner=True, approve=True)
|
|
events = []
|
|
with patch.object(DEPS.hub, "publish", events.append):
|
|
r = self.call("POST", "dismissed", json={"tags": [nid, "ntf_ffffffffffff"]})
|
|
self.assertEqual(r.json(), {"ok": True, "dismissed": 1})
|
|
self.assertEqual(DEPS.notif_read_store.state_of(f"log#{nid}"), "dismissed")
|
|
st = next(e for e in events if e["type"] == "notif-state")
|
|
self.assertEqual((st["ids"], st["state"], st["by"]), ([f"log#{nid}"], "dismissed", f"plugin:{PID}"))
|
|
# The other phone channel (Home Assistant, in parallel) is told; the
|
|
# one it was swiped on is not.
|
|
p = self.store.user_data_dir(OWNER_UID, "twin") / "got.jsonl"
|
|
deadline = time.time() + 3
|
|
while time.time() < deadline and not p.exists():
|
|
time.sleep(0.05)
|
|
self.assertEqual([json.loads(x)["push"]["tags"] for x in p.read_text().splitlines()], [[nid]])
|
|
self.assertEqual(self.clears(), [])
|
|
|
|
def test_a_guest_cannot_dismiss_the_owners_push(self):
|
|
nid = _create_notify(DEPS, {"title": "t", "message": "m"})["id"]
|
|
r = self.call("POST", "dismissed", uid=self.guest, json={"tags": [nid]})
|
|
self.assertEqual(r.json(), {"ok": True, "dismissed": 0})
|
|
self.assertEqual(DEPS.notif_read_store.state_of(f"log#{nid}"), "unread")
|
|
|
|
def test_a_guests_own_swipe_counts_and_writes_no_ledger(self):
|
|
nid = _create_notify(DEPS, {"title": "t", "message": "m", "sessionId": GUEST_SID})["id"]
|
|
r = self.call("POST", "dismissed", uid=self.guest, json={"tags": [nid]})
|
|
self.assertEqual(r.json(), {"ok": True, "dismissed": 1})
|
|
self.assertEqual(DEPS.notif_read_store.state_of(f"log#{nid}"), "unread")
|
|
self.assertEqual(self.call("POST", "dismissed", json={"tags": "x"}).status_code, 400)
|
|
|
|
|
|
class TestWebhook(Base):
|
|
def hook(self, hid, method="POST", uid=OWNER_UID, query="", **kw):
|
|
tok = self.store.get_raw(uid, PID)["webhookTokens"][hid]
|
|
return self.tc.request(
|
|
method, f"/proxy/tools/plugins/{PID}/webhook/{hid}?token={tok}{query}", **kw)
|
|
|
|
def test_respond_result_is_the_actions_own_json(self):
|
|
r = self.hook("app", json={"op": "ping"})
|
|
self.assertEqual(r.json(), {"ok": True, "got": {"op": "ping"}, "trigger": "webhook",
|
|
"uid": OWNER_UID})
|
|
r = self.hook("app", json={"say": {"ok": False, "error": "answered"}})
|
|
self.assertEqual((r.status_code, r.json()), (200, {"ok": False, "error": "answered"}))
|
|
r = self.hook("app", json={"say": {"_error": {"status": 404, "kind": "gone", "message": "no"}}})
|
|
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (404, "gone"))
|
|
|
|
def test_the_envelope_stays_the_default(self):
|
|
r = self.hook("plain", json={"a": 1}).json()
|
|
self.assertEqual((r["ok"], r["mode"], r["result"]["got"]), (True, "action", {"a": 1}))
|
|
|
|
def test_it_runs_as_whoever_the_token_belongs_to(self):
|
|
self.assertEqual(self.hook("app", uid=self.guest, json={}).json()["uid"], self.guest)
|
|
r = self.tc.post(f"/proxy/tools/plugins/{PID}/webhook/app?token=wrong", json={})
|
|
self.assertEqual(r.status_code, 401)
|
|
|
|
def test_methods(self):
|
|
self.assertEqual(self.hook("app", "GET").status_code, 405)
|
|
self.assertEqual(self.hook("apk", "POST", json={}).status_code, 405)
|
|
r = self.hook("apk", "GET", query="&v=12")
|
|
self.assertEqual(r.json()["got"], {"v": "12"}) # the query, minus the token
|
|
|
|
def test_a_file_from_the_shared_dir_only(self):
|
|
shared = self.store.shared_data_dir(PID)
|
|
(shared / "apk").mkdir()
|
|
(shared / "apk" / "app.apk").write_bytes(b"PK\x03\x04apk")
|
|
say = json.dumps({"_file": {"path": "apk/app.apk", "filename": "ai agent 1.2.apk",
|
|
"contentType": "application/vnd.android.package-archive"}})
|
|
r = self.hook("app", json={"say": json.loads(say)})
|
|
self.assertEqual((r.status_code, r.content), (200, b"PK\x03\x04apk"))
|
|
self.assertEqual(r.headers["content-type"], "application/vnd.android.package-archive")
|
|
self.assertIn('filename="ai_agent_1.2.apk"', r.headers["content-disposition"])
|
|
for path in ("../../installed.json", "/etc/passwd", "apk/nope.apk", ""):
|
|
r = self.hook("app", json={"say": {"_file": {"path": path}}})
|
|
self.assertEqual(r.status_code, 404, path)
|
|
(self.store.user_data_dir(self.guest, PID) / "mine.txt").write_text("hi")
|
|
r = self.hook("app", uid=self.guest, json={"say": {"_file": {"path": "mine.txt", "in": "data"}}})
|
|
self.assertEqual(r.content, b"hi")
|
|
r = self.hook("app", json={"say": {"_file": {"path": "mine.txt", "in": "data"}}})
|
|
self.assertEqual(r.status_code, 404) # the owner's dir has none
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|