A plugin declaring provides: {"notify.channel": "<action>"} gets every
push, ask and clear of the person who installed it (notifications/channels.py),
the payload the HA webhook always got. Tried once, no retry; with no channel
a push is still in the app (an in_app record, ok) and on the browsers, which
stay core. Guests' own channel installs get their wording and guest link.
Removed: the webhook list (Settings → Webhooks, /api/webhooks*, forward(),
the seeded HA webhook) and integrations/home-assistant, now in the
home-assistant-push plugin (ai-agent-plugins). The old webhook's URL and PWA
package are carried over once into the plugin's data. /settings/webhooks
redirects to the plugin. Forms ha-push-as-a-plugin_yjj2n0,
browser-push-as-a-plugin_7id9we.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
483 lines
24 KiB
Python
483 lines
24 KiB
Python
"""Web Push for guests (users/webpush.py): subscribing from a browser, the
|
|
``webpush`` channel in the guest fan-out (a push, an ask with its options, a
|
|
form), dead devices dropped, and the payload a browser can actually decrypt.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import base64
|
|
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",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"WEBPUSH_PATH": TMP / "webpush.json",
|
|
"VAPID_KEY_PATH": TMP / "vapid.pem",
|
|
# the tests' stand-in for a browser vendor's push service
|
|
"WEBPUSH_EXTRA_HOSTS": "push.example.test",
|
|
"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" / "film").mkdir(parents=True)
|
|
|
|
from cryptography.hazmat.primitives.asymmetric import ec # noqa: E402
|
|
from cryptography.hazmat.primitives.serialization import ( # noqa: E402
|
|
Encoding, PublicFormat)
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from notifications.service import _create_ask, _create_notify # noqa: E402
|
|
from users import webpush # noqa: E402
|
|
from users.caller import SESSION_COOKIE # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
|
|
|
|
def _b64(raw: bytes) -> str:
|
|
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
|
|
|
|
|
def _browser(n: int = 1):
|
|
"""A fake browser's subscription and the private key it decrypts with."""
|
|
key = ec.generate_private_key(ec.SECP256R1())
|
|
auth = os.urandom(16)
|
|
sub = {"endpoint": f"https://push.example.test/sub/{n}",
|
|
"keys": {"p256dh": _b64(key.public_key().public_bytes(
|
|
Encoding.X962, PublicFormat.UncompressedPoint)), "auth": _b64(auth)}}
|
|
return sub, key, auth
|
|
|
|
|
|
class WebPush(unittest.TestCase):
|
|
def setUp(self):
|
|
for u in DEPS.users.all():
|
|
DEPS.push.forget_user(u["id"])
|
|
DEPS.users.delete(u["id"])
|
|
DEPS.push.forget_user("owner")
|
|
self.dom = DEPS.users.create("dom@example.com", "Dom",
|
|
projects={"film": "chat"})
|
|
self.c = TestClient(main.app, base_url="https://claude.example.test")
|
|
self.c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
|
|
self.sent: list[tuple[dict, dict]] = []
|
|
self._orig_post = webpush._post
|
|
webpush._post = lambda sub, data, urgency: self.sent.append(
|
|
(sub, {**json.loads(data), "_urgency": urgency}))
|
|
# Delivery runs off the request thread; run it inline here.
|
|
self._orig_async = webpush.send_async
|
|
webpush.send_async = webpush.send
|
|
|
|
def tearDown(self):
|
|
webpush._post = self._orig_post
|
|
webpush.send_async = self._orig_async
|
|
|
|
def subscribe(self, n=1):
|
|
sub, key, auth = _browser(n)
|
|
r = self.c.post("/api/me/push", json={"subscription": sub, "label": f"Phone {n}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
return r.json(), sub, key, auth
|
|
|
|
def guest_conversation(self):
|
|
DEPS.meta_store.update("s-dom", {"owner": self.dom["id"]})
|
|
return "s-dom"
|
|
|
|
def push_service(self, status, headers=None, body=b""):
|
|
"""Stand in for the network under the real sender: every request the
|
|
hub would make lands in ``.calls`` and gets this answer."""
|
|
import requests
|
|
|
|
class Service(requests.adapters.BaseAdapter):
|
|
calls: list = []
|
|
|
|
def send(self, request, **_):
|
|
self.calls.append(request)
|
|
r = requests.Response()
|
|
r.status_code, r._content, r.url = status, body, request.url
|
|
r.reason, r.request = "x", request
|
|
r.headers.update(headers or {})
|
|
return r
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
webpush._session = None
|
|
self.addCleanup(setattr, webpush, "_session", None)
|
|
service = Service()
|
|
session = webpush._no_redirect_session()
|
|
session.mount("https://", service)
|
|
session.mount("http://", service)
|
|
return service
|
|
|
|
def test_subscribing_turns_the_channel_on(self):
|
|
self.assertEqual(DEPS.users.get("dom")["notify"]["channels"], ["in_app"])
|
|
out, *_ = self.subscribe()
|
|
self.assertTrue(out["publicKey"])
|
|
self.assertEqual([d["label"] for d in out["devices"]], ["Phone 1"])
|
|
self.assertIn("webpush", DEPS.users.get("dom")["notify"]["channels"])
|
|
# The same browser again is the same device, not a second one.
|
|
self.subscribe()
|
|
self.assertEqual(DEPS.push.count("dom"), 1)
|
|
# The owner's page lists it.
|
|
users = TestClient(main.app).get("/api/users", headers=OWNER_H).json()["users"]
|
|
self.assertEqual(len(users[0]["pushDevices"]), 1)
|
|
|
|
def test_remove_device_is_per_user(self):
|
|
out, *_ = self.subscribe()
|
|
dev = out["devices"][0]["id"]
|
|
claire = DEPS.users.create("claire@example.com", "Claire")
|
|
c2 = TestClient(main.app, base_url="https://claude.example.test")
|
|
c2.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(claire["id"]))
|
|
self.assertEqual(c2.delete(f"/api/me/push/{dev}").status_code, 404)
|
|
self.assertEqual(self.c.delete(f"/api/me/push/{dev}").json()["devices"], [])
|
|
|
|
def test_rejects_junk_and_impersonation(self):
|
|
r = self.c.post("/api/me/push", json={"subscription": {"endpoint": "http://x"}})
|
|
self.assertEqual(r.status_code, 400)
|
|
imp = TestClient(main.app)
|
|
imp.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(
|
|
self.dom["id"], impersonator="owner"))
|
|
r = imp.post("/api/me/push", json={"subscription": _browser()[0]},
|
|
headers={"Origin": "http://testserver"})
|
|
self.assertEqual(r.status_code, 400)
|
|
self.assertEqual(DEPS.push.count("dom"), 0)
|
|
|
|
def test_push_ask_and_form_reach_the_device(self):
|
|
self.subscribe()
|
|
sid = self.guest_conversation()
|
|
_create_notify(DEPS, {"title": "✅ Done", "message": "built it", "type": "deploy",
|
|
"url": "https://ai.example.test/c/x", "sessionId": sid})
|
|
ask = _create_ask(DEPS, {"question": "Ship it?", "options": ["Yes", "No"],
|
|
"sessionId": sid})
|
|
_create_notify(DEPS, {"title": "📋 Brief", "message": "Tap", "type": "ai",
|
|
"sessionId": sid, "pushKind": "form"})
|
|
kinds = [(p["kind"], p["_urgency"]) for _, p in self.sent]
|
|
self.assertEqual(kinds, [("notify", "normal"), ("ask", "high"), ("form", "high")])
|
|
push, ask_push = self.sent[0][1], self.sent[1][1]
|
|
self.assertEqual((push["title"], push["body"], push["type"]),
|
|
("✅ Done", "built it", "deploy"))
|
|
self.assertEqual(ask_push["id"], ask["id"])
|
|
self.assertEqual(ask_push["options"], ["Yes", "No"])
|
|
self.assertIn("webpush", [d["target"] for d in ask["delivered"]])
|
|
|
|
def test_each_kind_has_its_look(self):
|
|
from users.push_style import IMPORTANCE, style_of
|
|
self.subscribe()
|
|
sid = self.guest_conversation()
|
|
_create_notify(DEPS, {"title": "c", "type": "commit", "sessionId": sid})
|
|
_create_notify(DEPS, {"title": "?", "type": "nope", "sessionId": sid})
|
|
_create_ask(DEPS, {"question": "q", "options": ["a", "b"], "sessionId": sid})
|
|
looks = [(p["icon"], p["badge"]) for _, p in self.sent]
|
|
self.assertEqual(looks, [("/push/git.png", "/push/git-badge.png"),
|
|
("/push/default.png", "/push/default-badge.png"),
|
|
("/push/ask.png", "/push/ask-badge.png")])
|
|
self.assertTrue(all(p["timestamp"] > 0 for _, p in self.sent))
|
|
# Every style has its two PNGs.
|
|
pub = pathlib.Path(__file__).resolve().parent.parent / "frontend" / "public" / "push"
|
|
for style in IMPORTANCE:
|
|
self.assertTrue((pub / f"{style}.png").is_file(), style)
|
|
self.assertTrue((pub / f"{style}-badge.png").is_file(), style)
|
|
self.assertEqual(style_of("notify", "Warning"), "warn")
|
|
|
|
def test_levels_silence_or_drop_a_group(self):
|
|
self.subscribe()
|
|
sid = self.guest_conversation()
|
|
view = self.c.get("/api/me/push").json()["prefs"]
|
|
self.assertEqual({p["id"]: p["level"] for p in view}["code"], "silent")
|
|
r = self.c.put("/api/me/push/prefs",
|
|
json={"levels": {"deploy": "off", "code": "buzz", "x": "off",
|
|
"ai": "loud"}})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(DEPS.push.levels("dom"), {"deploy": "off", "code": "buzz"})
|
|
_create_notify(DEPS, {"title": "d", "type": "deploy", "sessionId": sid})
|
|
_create_notify(DEPS, {"title": "c", "type": "code", "sessionId": sid})
|
|
_create_notify(DEPS, {"title": "s", "type": "service", "sessionId": sid})
|
|
self.assertEqual([(p["title"], p.get("silent", False)) for _, p in self.sent],
|
|
[("c", False), ("s", True)])
|
|
|
|
def test_answered_question_is_cleared_everywhere(self):
|
|
self.subscribe()
|
|
sid = self.guest_conversation()
|
|
ask = _create_ask(DEPS, {"question": "q", "options": ["a", "b"], "sessionId": sid})
|
|
r = self.c.post(f"/api/ask/{ask['id']}/answer", json={"index": 1})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.sent[-1][1], {"kind": "clear", "tag": ask["id"],
|
|
"_urgency": "low"})
|
|
# Nobody who has questions off gets a clear.
|
|
self.sent.clear()
|
|
DEPS.push.set_levels("dom", {"questions": "off"})
|
|
from users import deliver
|
|
deliver.clear(DEPS, sid, "frm_x", "form")
|
|
self.assertEqual(self.sent, [])
|
|
|
|
def test_image_and_tag_ride_along(self):
|
|
self.subscribe()
|
|
_create_notify(DEPS, {"title": "x", "type": "deploy", "tag": "site",
|
|
"image": "https://site.example/og.png",
|
|
"sessionId": self.guest_conversation()})
|
|
p = self.sent[0][1]
|
|
self.assertEqual((p["image"], p["tag"]), (f"/api/notify/{p['id']}/image", "site"))
|
|
|
|
def test_image_is_served_from_the_app(self):
|
|
from notifications import image_proxy
|
|
sid = self.guest_conversation()
|
|
def push(image):
|
|
return _create_notify(DEPS, {"title": "x", "image": image, "sessionId": sid})["id"]
|
|
pub, lab, own = (push("https://site.example/og.png"),
|
|
push("https://grafana.lab.example/r.png"),
|
|
push("/api/artefact?path=a.png"))
|
|
orig = (image_proxy.is_public, image_proxy.fetch)
|
|
image_proxy.is_public = lambda url: "lab" not in url
|
|
image_proxy.fetch = lambda url: (b"PNG", "image/png")
|
|
try:
|
|
r = self.c.get(f"/api/notify/{pub}/image")
|
|
self.assertEqual((r.status_code, r.content, r.headers["content-type"]),
|
|
(200, b"PNG", "image/png"))
|
|
self.assertEqual(self.c.get(f"/api/notify/{lab}/image").status_code, 404)
|
|
owner = TestClient(main.app).get(f"/api/notify/{lab}/image", headers=OWNER_H,
|
|
follow_redirects=False)
|
|
self.assertEqual(owner.headers["location"], "https://grafana.lab.example/r.png")
|
|
r = self.c.get(f"/api/notify/{own}/image", follow_redirects=False)
|
|
self.assertEqual(r.headers["location"], "/api/artefact?path=a.png")
|
|
# Someone else's push: not theirs to see.
|
|
other = _create_notify(DEPS, {"title": "o", "image": "https://site.example/x.png",
|
|
"sessionId": ""})["id"]
|
|
self.assertEqual(self.c.get(f"/api/notify/{other}/image").status_code, 404)
|
|
finally:
|
|
image_proxy.is_public, image_proxy.fetch = orig
|
|
|
|
def test_private_hosts_are_never_public(self):
|
|
from notifications.image_proxy import is_public, own_path
|
|
self.assertFalse(is_public("http://127.0.0.1/x.png"))
|
|
self.assertFalse(is_public("http://100.104.50.115/x.png"))
|
|
self.assertFalse(is_public("file:///etc/passwd"))
|
|
self.assertEqual(own_path("https://hub.example/api/x", ("https://hub.example",)), "/api/x")
|
|
self.assertIsNone(own_path("//evil.example/x", ()))
|
|
|
|
# ── clearing (phone + devices) ─────────────────────────────────────────
|
|
def _phone(self):
|
|
import notifications.service as svc
|
|
calls = []
|
|
orig = svc.clear_phone
|
|
svc.clear_phone = lambda deps, tags: calls.append(list(tags))
|
|
self.addCleanup(setattr, svc, "clear_phone", orig)
|
|
return calls
|
|
|
|
def owner_device(self):
|
|
TestClient(main.app).post("/api/me/push", headers=OWNER_H,
|
|
json={"subscription": _browser(7)[0]})
|
|
|
|
def test_answered_ask_clears_the_phone_when_the_owner_hears_it(self):
|
|
phone = self._phone()
|
|
ask = _create_ask(DEPS, {"question": "q", "options": ["a", "b"], "sessionId": ""})
|
|
TestClient(main.app).post(f"/api/ask/{ask['id']}/answer", headers=OWNER_H,
|
|
json={"index": 0})
|
|
self.assertEqual(phone, [[ask["id"]]])
|
|
# A guest's conversation the owner doesn't follow: not on his phone.
|
|
g = _create_ask(DEPS, {"question": "q", "options": ["a", "b"],
|
|
"sessionId": self.guest_conversation()})
|
|
self.c.post(f"/api/ask/{g['id']}/answer", json={"index": 0})
|
|
self.assertEqual(phone, [[ask["id"]]])
|
|
|
|
def test_form_push_is_tagged_and_cleared_by_its_id(self):
|
|
phone = self._phone()
|
|
n = _create_notify(DEPS, {"title": "📋 f", "sessionId": "", "pushKind": "form",
|
|
"tag": "frm_abc"})
|
|
self.assertEqual(DEPS.notify_store.get(n["id"])["tag"], "frm_abc")
|
|
from users import deliver
|
|
deliver.clear(DEPS, "", "frm_abc", "form")
|
|
self.assertEqual(phone, [["frm_abc"]])
|
|
|
|
def test_read_in_the_app_clears_the_readers_devices(self):
|
|
phone = self._phone()
|
|
self.owner_device()
|
|
self.subscribe()
|
|
n = _create_notify(DEPS, {"title": "x", "type": "deploy", "sessionId": ""})
|
|
self.sent.clear()
|
|
TestClient(main.app).post("/api/notifications/seen", headers=OWNER_H,
|
|
json={"ids": [f"log#{n['id']}"]})
|
|
self.assertEqual(phone, [[n["id"]]])
|
|
self.assertEqual([(s["endpoint"][-1], p) for s, p in self.sent],
|
|
[("7", {"kind": "clear", "tag": n["id"], "_urgency": "low"})])
|
|
# A guest reading theirs: their devices only, the ledger untouched.
|
|
g = _create_notify(DEPS, {"title": "y", "sessionId": self.guest_conversation()})
|
|
self.sent.clear()
|
|
self.c.post("/api/notifications/seen", json={"ids": [f"log#{g['id']}"]})
|
|
self.assertEqual([s["endpoint"][-1] for s, _ in self.sent], ["1"])
|
|
self.assertEqual(phone, [[n["id"]]])
|
|
# `all` (an old blob's catch-up) clears nothing.
|
|
self.sent.clear()
|
|
TestClient(main.app).post("/api/notifications/seen", headers=OWNER_H,
|
|
json={"all": True})
|
|
self.assertEqual(self.sent, [])
|
|
|
|
def test_swiped_on_the_phone_is_read_in_the_app(self):
|
|
phone = self._phone()
|
|
self.owner_device()
|
|
n = _create_notify(DEPS, {"title": "x", "sessionId": ""})
|
|
self.sent.clear()
|
|
seen = []
|
|
orig = DEPS.hub.publish
|
|
DEPS.hub.publish = lambda ev: seen.append(ev) or orig(ev)
|
|
self.addCleanup(setattr, DEPS.hub, "publish", orig)
|
|
r = TestClient(main.app).post("/api/notifications/dismissed", headers=OWNER_H,
|
|
json={"tag": n["id"]})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertTrue(DEPS.notif_read_store.is_seen(f"log#{n['id']}"))
|
|
self.assertIn({"type": "notif-seen", "ids": [f"log#{n['id']}"]}, seen)
|
|
self.assertEqual([p["kind"] for _, p in self.sent], ["clear"])
|
|
self.assertEqual(phone, []) # it's already gone from the phone
|
|
self.assertEqual(self.c.post("/api/notifications/dismissed",
|
|
json={"tag": n["id"]}).status_code, 403)
|
|
|
|
def test_expired_ask_is_swept_off(self):
|
|
from notifications.service import sweep_expired_asks
|
|
phone = self._phone()
|
|
ask = _create_ask(DEPS, {"question": "q", "options": ["a", "b"], "sessionId": "",
|
|
"timeoutSecs": 1})
|
|
DEPS.notify_store._update(ask["id"], {"expiresAt": "2000-01-01T00:00:00Z"})
|
|
self.assertGreaterEqual(sweep_expired_asks(DEPS), 1)
|
|
self.assertEqual(DEPS.notify_store.get(ask["id"])["status"], "expired")
|
|
self.assertIn([ask["id"]], phone)
|
|
|
|
def test_unticked_channel_or_owner_conversation_sends_nothing(self):
|
|
self.subscribe()
|
|
DEPS.users.update("dom", {"notify": {"channels": ["in_app"]}})
|
|
_create_notify(DEPS, {"title": "x", "sessionId": self.guest_conversation()})
|
|
_create_notify(DEPS, {"title": "owner's", "sessionId": ""})
|
|
self.assertEqual(self.sent, [])
|
|
|
|
def test_gone_device_is_dropped(self):
|
|
self.subscribe(1)
|
|
self.subscribe(2)
|
|
|
|
class Gone(Exception):
|
|
response = type("R", (), {"status_code": 410})()
|
|
|
|
def post(sub, data, urgency):
|
|
if sub["endpoint"].endswith("/1"):
|
|
raise Gone("410 Gone")
|
|
webpush._post = post
|
|
r = self.c.post("/api/me/push/test")
|
|
res = r.json()["results"]
|
|
self.assertEqual(sorted(x["ok"] for x in res), [False, True])
|
|
self.assertEqual(DEPS.push.count("dom"), 1)
|
|
self.assertTrue(r.json()["devices"][0]["lastOkAt"])
|
|
|
|
def test_endpoint_must_be_a_browser_push_service(self):
|
|
"""The endpoint is the caller's word, and the hub POSTs to it from
|
|
inside its own network: only a browser vendor's push service."""
|
|
keys = _browser()[0]["keys"]
|
|
for bad in ("https://evil.example/x",
|
|
"https://127.0.0.1:8080/api/cron/x/run",
|
|
"https://ai-agent:8080/api/spawn",
|
|
"https://fcm.googleapis.com.evil.example/x",
|
|
"https://evil.example/fcm.googleapis.com",
|
|
"https://fcm.googleapis.com@evil.example/x",
|
|
"https://evil.example\\@fcm.googleapis.com/x",
|
|
"https://fcm.googleapis.com:8443/x",
|
|
"http://fcm.googleapis.com/x"):
|
|
r = self.c.post("/api/me/push", json={"subscription": {"endpoint": bad,
|
|
"keys": keys}})
|
|
self.assertEqual(r.status_code, 400, bad)
|
|
self.assertEqual(DEPS.push.count("dom"), 0)
|
|
for good in ("https://fcm.googleapis.com/fcm/send/abc:def",
|
|
"https://updates.push.services.mozilla.com/wpush/v2/gAAA",
|
|
"https://web.push.apple.com/QabC",
|
|
"https://wns2-par02p.notify.windows.com/w/?token=x"):
|
|
r = self.c.post("/api/me/push", json={"subscription": {"endpoint": good,
|
|
"keys": keys}})
|
|
self.assertEqual(r.status_code, 200, good)
|
|
self.assertEqual(DEPS.push.count("dom"), 4)
|
|
|
|
def test_a_redirect_is_never_followed_and_only_the_status_comes_back(self):
|
|
"""A 307 from the "push service" would re-POST from inside the hub
|
|
— to its own loopback, where it is the owner."""
|
|
webpush._post = self._orig_post
|
|
out, *_ = self.subscribe()
|
|
service = self.push_service(
|
|
307, {"Location": "http://127.0.0.1:8080/api/cron/week-burn/run"},
|
|
b"internal words nobody outside should read")
|
|
r = self.c.post("/api/me/push/test")
|
|
self.assertEqual(len(service.calls), 1) # the redirect went nowhere
|
|
res, = r.json()["results"]
|
|
self.assertEqual((res["ok"], res["status"]), (False, 307))
|
|
self.assertEqual(res["error"], "push service answered 307")
|
|
self.assertNotIn("internal words", r.text)
|
|
self.assertNotIn("127.0.0.1", r.text)
|
|
self.assertEqual(r.json()["devices"][0]["lastError"], "push service answered 307")
|
|
|
|
def test_a_stored_endpoint_off_the_list_is_dropped_unsent(self):
|
|
_, sub, *_ = self.subscribe()
|
|
with DEPS.push._lock: # as recorded before endpoints were checked
|
|
rec = next(iter(DEPS.push._data["subs"].values()))
|
|
rec["endpoint"] = "https://evil.example/x"
|
|
r = self.c.post("/api/me/push/test")
|
|
self.assertEqual(self.sent, [])
|
|
self.assertTrue(r.json()["results"][0]["dropped"])
|
|
self.assertEqual(DEPS.push.count("dom"), 0)
|
|
|
|
def test_owner_devices_ride_beside_the_channels(self):
|
|
owner = TestClient(main.app)
|
|
r = owner.post("/api/me/push", headers=OWNER_H,
|
|
json={"subscription": _browser(9)[0], "label": "Laptop"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
_create_notify(DEPS, {"title": "owner's", "sessionId": ""})
|
|
_create_notify(DEPS, {"title": "dom's", "sessionId": self.guest_conversation()})
|
|
self.assertEqual([p["title"] for _, p in self.sent], ["owner's"])
|
|
self.assertEqual(self.sent[0][0]["endpoint"], "https://push.example.test/sub/9")
|
|
# Never the guest list, and gone again on remove.
|
|
users = owner.get("/api/users", headers=OWNER_H).json()["users"]
|
|
self.assertEqual(users[0]["pushDevices"], [])
|
|
dev = r.json()["devices"][0]["id"]
|
|
self.assertEqual(owner.delete(f"/api/me/push/{dev}", headers=OWNER_H)
|
|
.json()["devices"], [])
|
|
|
|
def test_stored_email_channel_is_dropped(self):
|
|
from users.store import UsersStore
|
|
DEPS.users.update("dom", {"notify": {"channels": ["in_app", "webpush"]}})
|
|
raw = json.loads(pathlib.Path(os.environ["USERS_PATH"]).read_text())
|
|
raw["users"]["dom"]["notify"]["channels"] = ["in_app", "email"]
|
|
path = TMP / "old-users.json"
|
|
path.write_text(json.dumps(raw))
|
|
self.assertEqual(UsersStore(str(path)).get("dom")["notify"]["channels"], ["in_app"])
|
|
|
|
def test_owner_can_test_a_guests_push(self):
|
|
self.subscribe()
|
|
r = TestClient(main.app).post("/api/users/dom/push-test", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.sent[0][1]["kind"], "test")
|
|
|
|
def test_payload_decrypts_in_the_browser(self):
|
|
"""The real encryption path (pywebpush) with the HTTP call stubbed:
|
|
what the push service gets is a browser-decryptable aes128gcm body
|
|
signed by our VAPID key."""
|
|
import http_ece
|
|
webpush._post = self._orig_post
|
|
_, sub, key, auth = self.subscribe()
|
|
service = self.push_service(201)
|
|
r = self.c.post("/api/me/push/test")
|
|
req, = service.calls
|
|
posted = {"url": req.url, "data": req.body, "headers": req.headers}
|
|
self.assertEqual([x["ok"] for x in r.json()["results"]], [True])
|
|
self.assertEqual(posted["url"], sub["endpoint"])
|
|
self.assertIn("vapid t=", posted["headers"]["Authorization"])
|
|
self.assertIn(webpush.public_key(), posted["headers"]["Authorization"])
|
|
plain = http_ece.decrypt(posted["data"], private_key=key,
|
|
auth_secret=auth, version="aes128gcm")
|
|
self.assertEqual(json.loads(plain)["kind"], "test")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|