hermes-agent/tests/gateway/test_buzz_websocket.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
Second, deeper pass over tools/gateway/hermes_cli plus first pass over
the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker,
dashboard, conformance, monitoring, secret_sources, hermes_state,
providers). Same rubric as wave 1 (AGENTS.md test policy); security,
alternation/caching invariants, issue-number regressions, and E2E kept.

Real test-quality fixes found and rooted out along the way:
- tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls
  (DEFAULT_CONFIG smart-approval leaked in) — pinned approval
  mode=manual via autouse fixture: 17.4s → 0.4s.
- test_model_switch_custom_providers.py / test_user_providers_model_switch.py
  silently probed live provider catalogs (~2s/test) — stubbed
  cached_provider_model_ids/provider_model_ids/fetch_api_models.
- test_telegram_noise_filter.py: 15-platform copy-paste matrix over
  shared gateway.run logic → 3 representative platforms (55s → 3.9s).
- test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on
  MagicMock agents — interrupt.side_effect now clears _running_agents
  (22s → 1.0s).
- test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x
  (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps
  patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait
  5s → 0.5s.
- test_telegram_init_deadline.py: loop-block margin restored to 1.0s
  with rationale comment — the watchdog-dump assertion needs the loop
  blocked well past deadline+grace under parallel load (flaked once in
  the 40-worker verification run at a 0.2s margin).

Verification: full hermetic suite via scripts/run_tests.sh —
2,438 files, 21,718 tests passed, 0 failed, 293.9s wall.
Suite totals vs original baseline: 46,820 → 19,757 test functions
(−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
2026-07-29 13:39:40 -07:00

121 lines
4.2 KiB
Python

"""Tests for the Buzz WebSocket transport (NIP-42) and Nostr signing module.
The signing module and WS transport were contributed in PR #73636 by
@ScaleLeanChris and consolidated onto the merged poll-based adapter; these
tests cover the crypto (against the official BIP-340 vector) and the WS
lifecycle as wired into BuzzAdapter.
"""
import asyncio
import json
import time
import pytest
from tests.gateway._plugin_adapter_loader import load_plugin_adapter
_buzz_mod = load_plugin_adapter("buzz")
BuzzAdapter = _buzz_mod.BuzzAdapter
import importlib.util as _ilu
from pathlib import Path as _Path
_auth_path = _Path(_buzz_mod.__file__).with_name("nostr_auth.py")
_spec = _ilu.spec_from_file_location("plugin_adapter_buzz_nostr_auth", _auth_path)
nostr_auth = _ilu.module_from_spec(_spec)
_spec.loader.exec_module(nostr_auth)
SELF_PUBKEY = "9fd5c7ba6d3ef224da78f541e0fcb9c50f72cc63edb19aae76ac6a0474dfa860"
# BIP-340 test vector 0 private key
TEST_PRIVATE_KEY = "00" * 31 + "03"
CHANNEL = "ccc2bc1a-7a82-5a8f-8c4e-57a070cbe7cd"
def _make_adapter(extra=None):
from gateway.config import PlatformConfig
cfg = PlatformConfig(enabled=True, extra={"relay_url": "https://test.relay", **(extra or {})})
adapter = BuzzAdapter(cfg)
adapter._self_pubkey = SELF_PUBKEY
adapter._private_key = TEST_PRIVATE_KEY
adapter._display_name = "Chip"
return adapter
# ── nostr_auth: BIP-340 / NIP-42 ──────────────────────────────────────────
def test_schnorr_sign_matches_official_bip340_vector_zero():
signature = nostr_auth.schnorr_sign(
bytes(32), TEST_PRIVATE_KEY, auxiliary_randomness=bytes(32)
)
assert nostr_auth.public_key_hex(TEST_PRIVATE_KEY).upper() == (
"F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9"
)
assert signature.hex().upper() == (
"E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA8215"
"25F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0"
)
def test_decode_private_key_rejects_bad_input():
with pytest.raises(ValueError):
nostr_auth.decode_private_key("not-a-key")
with pytest.raises(ValueError):
nostr_auth.decode_private_key("00" * 32) # zero — outside range
with pytest.raises(ValueError):
nostr_auth.decode_private_key("nsec1qqqqqqqq") # bad checksum/length
def test_build_auth_event_shape_and_owner_tag():
tag = json.dumps(["auth", "b" * 64, "", "c" * 128])
event = nostr_auth.build_auth_event(
private_key=TEST_PRIVATE_KEY,
challenge="challenge-1",
relay_url="wss://relay.example",
auth_tag_json=tag,
created_at=1_700_000_000,
auxiliary_randomness=bytes(32),
)
assert event["kind"] == 22242
assert ["relay", "wss://relay.example"] in event["tags"]
assert ["challenge", "challenge-1"] in event["tags"]
assert ["auth", "b" * 64, "", "c" * 128] in event["tags"]
assert len(bytes.fromhex(event["sig"])) == 64
assert event["pubkey"] == nostr_auth.public_key_hex(TEST_PRIVATE_KEY)
# ── Adapter WS wiring ─────────────────────────────────────────────────────
class _FakeWebSocket:
"""Replays a NIP-42 handshake: AUTH challenge, then OK for the reply."""
def __init__(self):
self.sent = []
async def recv(self):
if self.sent:
auth_event = self.sent[0][1]
return json.dumps(["OK", auth_event["id"], True, "authenticated"])
return json.dumps(["AUTH", "relay-challenge"])
async def send(self, raw):
self.sent.append(json.loads(raw))
@pytest.mark.asyncio
async def test_websocket_auth_raises_on_rejection():
adapter = _make_adapter()
class RejectingWs(_FakeWebSocket):
async def recv(self):
if self.sent:
auth_event = self.sent[0][1]
return json.dumps(["OK", auth_event["id"], False, "denied"])
return json.dumps(["AUTH", "relay-challenge"])
with pytest.raises(ConnectionError):
await adapter._authenticate_websocket(RejectingWs())