signal-bot/tests/test_transport_rest.py
Krzysztof kuhy Rudnicki aefffb2fd9
Some checks are pending
CI / check (push) Waiting to run
feat: add a photo to the album from the chat, tagged, stripped and verified
Send a photo captioned "!add_photo alfa wakacje" in one of the album's own
groups and it lands in the pack tagged with both, retrievable through !alfa
and the new !losowe immediately -- no restart, and no tagger session on the PC.
A label matching nobody becomes a custom tag, and !losowe is the only door to
one, which is what keeps a live swap a *data* swap: it can never register a
trigger or widen a command's groups.

No typed label travels. Labels become pseudonym keys in a new registry
arg_resolver, at the dispatcher, before the line that logs the command name --
so no handler, journal entry, command_uses row or reply body ever holds a word
somebody typed. The reply is counts and pseudonyms: "dodano · p1: 4 · t1: 1".

Stripping is exiftool with a *positive* check on the output, never an exit
code. ffmpeg was tried first and fails silently on photos: given a JPEG with a
real APP1 Exif segment it returned a byte-identical file, GPS intact, exit 0.
The surviving-tag allowlist is per tag *name* rather than per group, because
measurement showed a group-level "must be empty" rule rejects every format
except JPEG -- a valid PNG always reports its IHDR, an MP4 some fifty QuickTime
tags that are the container itself. Codec configuration (CompressorName,
VendorID, the HEVC parameter set) is on the list by decision: CompressorName
lives in the avc1 sample description and exiftool cannot write it at all, so
the alternative was refusing every video and every iPhone HEIC. Location and
identity tags are still refused, and the e2e run re-reads the stored files to
prove a QuickTime geotag did not survive.

.webm and .svg stay on the format allowlist and are stored *unstripped*:
exiftool 13.55 can write neither, and its SVG reader does not even surface
<metadata>. That is a deliberate, documented hole, not an oversight.

Two things this had to defuse along the way:
- personal_data_sources now reads custom.json, so "!add_photo kot <photo>"
  would have outlawed the word "kot" and refused every future commit, fixable
  only by hand-editing an album the committer cannot see. Minting now refuses
  a word that is already a command, and the gate subtracts the repo's own
  alias vocabulary from custom labels only -- curated people.json names are
  never excused.
- signal_bot/external.py is now the single subprocess site in the repository,
  so ruff's S603 needs exactly one scoped per-file-ignore instead of one per
  module that shells out. A test asserts nothing else imports subprocess.

A failed add changes nothing: media and the three manifests are written, the
album is reloaded, and only a load that succeeds is published; a load that
fails rolls all four back and keeps serving the pack that was already working,
without raising -- Restart=always would turn a ConfigError into a loop.

977 tests, 100% branch coverage, no omits and no suppressions. scripts/e2e.sh
gains 8 scenarios driven against the real exiftool on media generated at run
time, and asserts the invariants a reply cannot: that a refused upload is not
stored, that a message with no attachment leaves custom.json byte-identical,
and that signal-cli's own copy of every ingested attachment is gone.

Closes TODO-add-photo.md.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JqqE22jp94B1ypwxppdr1o
2026-08-31 11:20:00 +02:00

219 lines
7.1 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""The bbernhard adapter: sends, attachments, mode check and reconnect."""
from __future__ import annotations
from collections.abc import AsyncIterator, Callable
from typing import TYPE_CHECKING
import httpx
import pytest
from websockets.exceptions import ConnectionClosedError
from signal_bot.quoting import Quote
from signal_bot.transport_rest import RestTransport, TransportError
if TYPE_CHECKING:
from types import TracebackType
from signal_bot.config import Config
# The callable httpx.MockTransport expects -- not a bot command handler.
MockHandler = Callable[[httpx.Request], httpx.Response]
class FakeSocket:
"""Yields a canned list of frames, optionally failing partway through."""
def __init__(self, frames: list[str], *, fail_after: bool = False) -> None:
self._frames = frames
self._fail_after = fail_after
async def __aiter__(self) -> AsyncIterator[str]:
for frame in self._frames:
yield frame
if self._fail_after:
raise ConnectionClosedError(None, None)
class FakeConnect:
"""Stands in for websockets.connect, handing out sockets in order."""
def __init__(self, sockets: list[FakeSocket]) -> None:
self._sockets = sockets
self.urls: list[str] = []
def __call__(self, url: str) -> FakeConnect:
self.urls.append(url)
return self
async def __aenter__(self) -> FakeSocket:
if not self._sockets:
msg = "no more sockets"
raise OSError(msg)
return self._sockets.pop(0)
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
return None
def _transport(config: Config, handler: MockHandler, **kwargs: object) -> RestTransport:
client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
return RestTransport(config, client, **kwargs)
async def test_send_text_posts_expected_payload(config: Config) -> None:
seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(__import__("json").loads(request.content))
return httpx.Response(201)
await _transport(config, handler).send_text("hi", "group==")
assert seen[0] == {
"message": "hi",
"number": config.phone_number,
"recipients": ["group=="],
}
async def test_a_quoted_text_send_carries_the_quote_keys(config: Config) -> None:
"""This is what makes the bot answer a message rather than the room."""
seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(__import__("json").loads(request.content))
return httpx.Response(201)
quote = Quote(1719177917717, "uuid-alice", "!cat")
await _transport(config, handler).send_text("hi", "group==", quote)
assert seen[0]["quote_timestamp"] == 1719177917717
assert seen[0]["quote_author"] == "uuid-alice"
assert seen[0]["quote_message"] == "!cat"
async def test_a_quoted_image_send_carries_the_quote_keys(config: Config) -> None:
seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(__import__("json").loads(request.content))
return httpx.Response(201)
quote = Quote(17, "uuid-bob", "!dog")
await _transport(config, handler).send_image("Zm9v", "group==", quote)
assert seen[0]["base64_attachments"] == ["Zm9v"]
assert seen[0]["quote_timestamp"] == 17
assert seen[0]["quote_author"] == "uuid-bob"
async def test_send_image_posts_base64_attachment(config: Config) -> None:
seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(__import__("json").loads(request.content))
return httpx.Response(200)
await _transport(config, handler).send_image("BASE64", "group==")
assert seen[0]["base64_attachments"] == ["BASE64"]
async def test_send_raises_on_rejection(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(400, text="nope"))
with pytest.raises(TransportError, match="400"):
await transport.send_text("hi", "g")
async def test_verify_mode_accepts_json_rpc(config: Config) -> None:
transport = _transport(config, lambda r: httpx.Response(200, json={"mode": "json-rpc"}))
assert await transport.verify_mode() == "json-rpc"
async def test_verify_mode_rejects_the_native_build(config: Config) -> None:
"""It serves the same WebSocket and then fails every attachment send."""
transport = _transport(config, lambda r: httpx.Response(200, json={"mode": "json-rpc-native"}))
with pytest.raises(TransportError, match="awt"):
await transport.verify_mode()
@pytest.mark.parametrize("body", [{"mode": "normal"}, {"mode": "native"}, {}, ["nope"]])
async def test_verify_mode_rejects_non_websocket_modes(config: Config, body: object) -> None:
"""In normal/native mode /v1/receive silently degrades to a polling GET."""
transport = _transport(config, lambda r: httpx.Response(200, json=body))
with pytest.raises(TransportError, match="not 'json-rpc'"):
await transport.verify_mode()
async def test_receive_yields_frames(config: Config) -> None:
connector = FakeConnect([FakeSocket(["a", "b"])])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=_no_sleep,
max_reconnects=0,
)
assert [f async for f in transport.receive()] == ["a", "b"]
async def test_receive_decodes_binary_frames(config: Config) -> None:
connector = FakeConnect([FakeSocket([b"bytes-frame"])])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=_no_sleep,
max_reconnects=0,
)
assert [f async for f in transport.receive()] == ["bytes-frame"]
async def test_receive_reconnects_after_a_drop(config: Config) -> None:
"""A container restart used to kill the bot silently."""
slept: list[float] = []
async def sleeper(seconds: float) -> None:
slept.append(seconds)
connector = FakeConnect([FakeSocket(["a"], fail_after=True), FakeSocket(["b"])])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=sleeper,
max_reconnects=1,
)
assert [f async for f in transport.receive()] == ["a", "b"]
assert slept == [1.0]
async def test_receive_backs_off_exponentially(config: Config) -> None:
slept: list[float] = []
async def sleeper(seconds: float) -> None:
slept.append(seconds)
connector = FakeConnect([])
transport = _transport(
config,
lambda r: httpx.Response(200),
connector=connector,
sleeper=sleeper,
max_reconnects=3,
)
assert [f async for f in transport.receive()] == []
assert slept == [1.0, 2.0, 4.0]
async def _no_sleep(seconds: float) -> None:
return None
def _groups(*entries: object) -> MockHandler:
"""Answer /v1/groups with an arbitrary payload."""
return lambda r: httpx.Response(200, json=list(entries))