signal-bot/tests/test_fake_account.py
Krzysztof kuhy Rudnicki b48c945d89 feat: make the bot actually reply on Signal, and gate every way it went silent
First live reply, as its own registered account. `!cat` and `!dog` from the
phone return images -- verified in the production shape (the bot *invited to
an already-existing group*) and under a systemd user unit.

Four failures, each of which left the bot looking perfectly healthy:

- Invited is not joined. Signal only adds an account outright if the adder
  holds its profile key; with no profile the add becomes a pending invite,
  and signal-cli cannot accept one addressed to a phone number ("Cannot find
  service ID for self"). Group listed, websocket up, /healthz OK, zero
  messages. register_bot.sh now sets the profile *before* the add, and
  startup refuses on `member: false`.
- MODE=json-rpc-native is a GraalVM build with no AWT: text sends work,
  every attachment 400s with "Can't load library: awt". Both mode guards now
  demand exactly json-rpc, and start_container replaces a wrong-mode
  container instead of reusing it.
- The API spells one group two ways -- /v1/groups returns `group.<base64>`,
  envelopes carry what that decodes to -- so the scoping gate rejected the
  bot's own group. e2e.sh now models both spellings; reverting the fix fails
  4 scenarios, which is why the offline suite missed it before.
- BIND_PORT in .env was dead: __main__ read os.getenv before anything loaded
  a .env. The bind address comes from Config now.

A taken port used to be uvicorn logging the collision and exiting 0, which
every supervisor reads as success. portcheck.py refuses to start, exits
non-zero, and names the holder by reading /proc directly -- no subprocess, no
PATH assumptions, testable against a fake proc tree. Default port is 8137:
not 8000, and below the ephemeral range so the kernel cannot take it.

The bot now runs as signal-bot.service (Restart=always, linger checked rather
than assumed, StartLimitBurst so a config error fails visibly instead of
looping). Verified by SIGKILL and by re-running a command under the unit.

100% branch coverage, 230 tests, all gates green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yaBT45KhHqxTKVCTA87iy
2026-08-29 14:37:27 +02:00

114 lines
4.5 KiB
Python

# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence.
"""Registration and group endpoints on the fake server."""
from __future__ import annotations
import pytest
from fastapi.testclient import TestClient
from fake_signal.routes_account import CAPTCHA_REQUIRED, expected_code
from fake_signal.server import create_app
from fake_signal.state import State
NUMBER = "+15550001234"
@pytest.fixture
def state() -> State:
return State(base_url="http://testserver")
@pytest.fixture
def client(state: State) -> TestClient:
return TestClient(create_app(state))
def test_no_accounts_before_registration(client: TestClient) -> None:
assert client.get("/v1/accounts").json() == []
def test_register_without_captcha_is_refused(client: TestClient) -> None:
"""The exact failure the real container returns, so the script can match it."""
response = client.post(f"/v1/register/{NUMBER}", json={})
assert response.status_code == 400
assert "signalcaptchas.org" in response.json()["error"]
assert response.json()["error"] == CAPTCHA_REQUIRED
def test_register_with_captcha_starts_verification(client: TestClient, state: State) -> None:
response = client.post(f"/v1/register/{NUMBER}", json={"captcha": "signalcaptcha://x"})
assert response.status_code == 201
assert state.pending[NUMBER] == "001234"
def test_verify_completes_registration(client: TestClient) -> None:
client.post(f"/v1/register/{NUMBER}", json={"captcha": "signalcaptcha://x"})
code = expected_code(NUMBER)
assert client.post(f"/v1/register/{NUMBER}/verify/{code}").status_code == 201
assert client.get("/v1/accounts").json() == [NUMBER]
def test_verify_is_idempotent_on_the_account_list(client: TestClient) -> None:
for _ in range(2):
client.post(f"/v1/register/{NUMBER}", json={"captcha": "c"})
client.post(f"/v1/register/{NUMBER}/verify/{expected_code(NUMBER)}")
assert client.get("/v1/accounts").json() == [NUMBER]
def test_verify_rejects_a_wrong_code(client: TestClient) -> None:
client.post(f"/v1/register/{NUMBER}", json={"captcha": "c"})
response = client.post(f"/v1/register/{NUMBER}/verify/000000")
assert response.status_code == 400
assert "invalid verification code" in response.json()["error"]
def test_verify_without_a_pending_registration_is_refused(client: TestClient) -> None:
response = client.post(f"/v1/register/{NUMBER}/verify/001234")
assert response.status_code == 400
assert "no registration in progress" in response.json()["error"]
def test_groups_require_a_registered_account(client: TestClient) -> None:
response = client.get(f"/v1/groups/{NUMBER}")
assert response.status_code == 400
assert "not registered" in response.json()["error"]
def test_groups_are_listed_once_registered(client: TestClient, state: State) -> None:
state.accounts.append(NUMBER)
state.groups.extend([{"id": "gA==", "name": "Alpha"}, {"id": "gB==", "name": "Bravo"}])
body = client.get(f"/v1/groups/{NUMBER}").json()
assert [g["name"] for g in body] == ["Alpha", "Bravo"]
def test_expected_code_uses_the_last_six_digits() -> None:
assert expected_code("+48 123 456 789") == "456789"
def test_control_can_seed_groups(client: TestClient, state: State) -> None:
"""The picker in scripts/lib_signal.sh is rehearsed against this."""
state.accounts.append(NUMBER)
body = [{"id": "gA==", "name": "Alpha"}, {"id": "gB==", "name": "Bravo"}]
assert client.post("/_control/groups", json=body).json() == {"groups": 2}
assert client.get(f"/v1/groups/{NUMBER}").json() == body
def test_seeding_groups_replaces_the_previous_list(client: TestClient, state: State) -> None:
state.accounts.append(NUMBER)
client.post("/_control/groups", json=[{"id": "old==", "name": "Old"}])
client.post("/_control/groups", json=[{"id": "new==", "name": "New"}])
assert [g["id"] for g in client.get(f"/v1/groups/{NUMBER}").json()] == ["new=="]
def test_control_seeds_registered_accounts(client: TestClient) -> None:
"""/v1/groups answers 400 for an unknown account, so the fake needs this."""
assert client.get("/v1/groups/+15550000000").status_code == 400
assert client.post("/_control/accounts", json=["+15550000000"]).json() == {"accounts": 1}
assert client.get("/v1/groups/+15550000000").status_code == 200
def test_control_replaces_accounts_rather_than_appending(client: TestClient) -> None:
client.post("/_control/accounts", json=["+15550000001"])
client.post("/_control/accounts", json=["+15550000002"])
assert client.get("/v1/accounts").json() == ["+15550000002"]