test_relay_policy.py raw

   1  """Relay policy tests — connection limits, auth gating, HTTP guard, CORS, health.
   2  
   3  Each test class starts its own relay with the specific env vars it needs.
   4  Uses raw sockets for WebSocket to avoid test framework dependencies.
   5  """
   6  
   7  import json
   8  import os
   9  import signal
  10  import socket
  11  import struct
  12  import subprocess
  13  import time
  14  import urllib.request
  15  import urllib.error
  16  
  17  import pytest
  18  
  19  from nostr_helpers import make_event, TEST_SECKEY, TEST_PUBKEY
  20  
  21  # The binary under test and the (optional) static tree come from conftest, so a
  22  # hand-run here and the session fixture agree on which relay is being tested.
  23  # Hardcoding a name here once made a coverage run measure the plain binary for
  24  # every policy test below and report that as the suite's coverage.
  25  from conftest import RELAY_BIN, STATIC_DIR
  26  
  27  HOST = "127.0.0.1"
  28  
  29  
  30  def _fresh_data_dir(name):
  31      d = f"/tmp/morly-test-{name}-{os.getpid()}"
  32      os.makedirs(d, exist_ok=True)
  33      return d
  34  
  35  
  36  def _wait_port_free(port, timeout=5):
  37      """Wait until nothing is listening on port."""
  38      deadline = time.time() + timeout
  39      while time.time() < deadline:
  40          try:
  41              s = socket.create_connection((HOST, port), timeout=0.2)
  42              s.close()
  43              time.sleep(0.1)
  44          except (ConnectionRefusedError, OSError, socket.timeout):
  45              return
  46      raise RuntimeError(f"port {port} still in use after {timeout}s")
  47  
  48  
  49  def _start_relay(port, extra_env=None, data_dir_name=None):
  50      """Start a relay and wait for it to accept connections."""
  51      if not RELAY_BIN or not os.path.exists(RELAY_BIN):
  52          pytest.skip("relay binary not found — run: make build")
  53      _wait_port_free(port)
  54      name = data_dir_name or f"policy-{port}"
  55      data_dir = _fresh_data_dir(name)
  56      env = os.environ.copy()
  57      env["ORLY_DATA_DIR"] = data_dir
  58      env["ORLY_LISTEN"] = HOST
  59      env["ORLY_PORT"] = str(port)
  60      if STATIC_DIR:
  61          env["ORLY_STATIC_DIR"] = STATIC_DIR
  62      env["ORLY_LOG_TO_STDOUT"] = "true"
  63      if extra_env:
  64          env.update(extra_env)
  65      proc = subprocess.Popen(
  66          [RELAY_BIN],
  67          env=env,
  68          stdout=subprocess.PIPE,
  69          stderr=subprocess.PIPE,
  70      )
  71      for _ in range(40):
  72          try:
  73              s = socket.create_connection((HOST, port), timeout=0.5)
  74              s.close()
  75              break
  76          except Exception:
  77              if proc.poll() is not None:
  78                  out = proc.stderr.read().decode(errors="replace")
  79                  pytest.fail(f"Relay on :{port} exited early: {out[:500]}")
  80              time.sleep(0.15)
  81      else:
  82          proc.kill()
  83          out = proc.stderr.read().decode(errors="replace")
  84          pytest.fail(f"Relay on :{port} failed to start: {out[:500]}")
  85      time.sleep(0.05)
  86      return proc, data_dir
  87  
  88  
  89  def _stop_relay(proc):
  90      proc.send_signal(signal.SIGTERM)
  91      try:
  92          proc.wait(timeout=3)
  93      except subprocess.TimeoutExpired:
  94          proc.kill()
  95          proc.wait(timeout=2)
  96  
  97  
  98  # ── WebSocket helpers ────────────────────────────────
  99  
 100  
 101  # Bytes read past the WebSocket upgrade response, keyed by id(sock). A
 102  # socket.socket has no __dict__, so the leftover cannot ride on the object.
 103  _PENDING = {}
 104  
 105  
 106  def _ws_handshake(host, port):
 107      """Open a raw TCP socket and perform a WS upgrade. Returns the socket."""
 108      sock = socket.create_connection((host, port), timeout=5)
 109      import base64
 110      ws_key = base64.b64encode(os.urandom(16)).decode()
 111      handshake = (
 112          f"GET / HTTP/1.1\r\n"
 113          f"Host: {host}:{port}\r\n"
 114          f"Upgrade: websocket\r\n"
 115          f"Connection: Upgrade\r\n"
 116          f"Sec-WebSocket-Key: {ws_key}\r\n"
 117          f"Sec-WebSocket-Version: 13\r\n"
 118          f"\r\n"
 119      )
 120      sock.sendall(handshake.encode())
 121      resp = b""
 122      while b"\r\n\r\n" not in resp:
 123          resp += sock.recv(4096)
 124      if b"101" not in resp:
 125          sock.close()
 126          raise ConnectionError(f"WS upgrade failed: {resp[:200]}")
 127      # The server may send the AUTH challenge in the same segment as the 101,
 128      # and recv(4096) above reads whatever is there. Keep the bytes after the
 129      # header instead of discarding them: dropping them lost the challenge and
 130      # made the AUTH drain time out on roughly 1 connection in 100.
 131      _, _, rest = resp.partition(b"\r\n\r\n")
 132      _PENDING[id(sock)] = rest
 133      return sock
 134  
 135  
 136  def _ws_send(sock, payload):
 137      """Send a masked WS text frame."""
 138      mask = os.urandom(4)
 139      header = bytearray()
 140      header.append(0x81)
 141      length = len(payload)
 142      if length < 126:
 143          header.append(0x80 | length)
 144      elif length < 65536:
 145          header.append(0x80 | 126)
 146          header.extend(struct.pack(">H", length))
 147      else:
 148          header.append(0x80 | 127)
 149          header.extend(struct.pack(">Q", length))
 150      header.extend(mask)
 151      masked = bytearray(payload[i] ^ mask[i % 4] for i in range(len(payload)))
 152      sock.sendall(bytes(header) + bytes(masked))
 153  
 154  
 155  def _ws_recv(sock, timeout=5):
 156      """Read one WS frame (unmasked from server). Returns payload bytes."""
 157      sock.settimeout(timeout)
 158      hdr = _recv_exact(sock, 2)
 159      length = hdr[1] & 0x7F
 160      if length == 126:
 161          length = struct.unpack(">H", _recv_exact(sock, 2))[0]
 162      elif length == 127:
 163          length = struct.unpack(">Q", _recv_exact(sock, 8))[0]
 164      return _recv_exact(sock, length)
 165  
 166  
 167  def _recv_exact(sock, n):
 168      buf = bytearray()
 169      pending = _PENDING.get(id(sock), b"")
 170      if pending:
 171          take = pending[:n]
 172          buf.extend(take)
 173          _PENDING[id(sock)] = pending[len(take):]
 174      while len(buf) < n:
 175          chunk = sock.recv(n - len(buf))
 176          if not chunk:
 177              raise ConnectionError("socket closed")
 178          buf.extend(chunk)
 179      return bytes(buf)
 180  
 181  
 182  def _ws_send_json(sock, obj):
 183      _ws_send(sock, json.dumps(obj).encode())
 184  
 185  
 186  def _ws_recv_json(sock, timeout=5):
 187      return json.loads(_ws_recv(sock, timeout))
 188  
 189  
 190  def _drain_until(sock, label, timeout=5):
 191      """Read WS messages until one with msg[0]==label is found. Returns it."""
 192      deadline = time.time() + timeout
 193      while time.time() < deadline:
 194          msg = _ws_recv_json(sock, timeout=max(0.5, deadline - time.time()))
 195          if msg[0] == label:
 196              return msg
 197      raise TimeoutError(f"never received {label}")
 198  
 199  
 200  # ── Tests ────────────────────────────────────────────
 201  
 202  
 203  class TestHealthEndpoint:
 204      """GET /health returns 200 ok."""
 205  
 206      def test_health(self):
 207          port = 24001
 208          proc, _ = _start_relay(port)
 209          try:
 210              resp = urllib.request.urlopen(f"http://{HOST}:{port}/health", timeout=3)
 211              assert resp.status == 200
 212              assert resp.read() == b"ok"
 213          finally:
 214              _stop_relay(proc)
 215  
 216  
 217  class TestNIP11:
 218      """NIP-11 relay info respects ORLY_APP_NAME."""
 219  
 220      def test_custom_name(self):
 221          port = 24002
 222          proc, _ = _start_relay(port, {"ORLY_APP_NAME": "TestRelay"})
 223          try:
 224              req = urllib.request.Request(
 225                  f"http://{HOST}:{port}/",
 226                  headers={"Accept": "application/nostr+json"},
 227              )
 228              resp = urllib.request.urlopen(req, timeout=3)
 229              data = json.loads(resp.read())
 230              assert data["name"] == "TestRelay"
 231              assert 42 in data["supported_nips"]
 232              assert 50 in data["supported_nips"]
 233          finally:
 234              _stop_relay(proc)
 235  
 236      def test_default_name(self):
 237          port = 24003
 238          proc, _ = _start_relay(port)
 239          try:
 240              req = urllib.request.Request(
 241                  f"http://{HOST}:{port}/",
 242                  headers={"Accept": "application/nostr+json"},
 243              )
 244              resp = urllib.request.urlopen(req, timeout=3)
 245              data = json.loads(resp.read())
 246              assert data["name"] == "ORLY"
 247          finally:
 248              _stop_relay(proc)
 249  
 250  
 251  class TestCORS:
 252      """CORS preflight responses."""
 253  
 254      def test_options_returns_cors(self):
 255          port = 24004
 256          proc, _ = _start_relay(port, {
 257              "ORLY_CORS_ENABLED": "true",
 258          })
 259          try:
 260              req = urllib.request.Request(
 261                  f"http://{HOST}:{port}/health",
 262                  method="OPTIONS",
 263                  headers={"Origin": "http://example.com"},
 264              )
 265              resp = urllib.request.urlopen(req, timeout=3)
 266              assert resp.status == 204
 267              assert "access-control-allow-origin" in {
 268                  k.lower(): v for k, v in resp.headers.items()
 269              }
 270          finally:
 271              _stop_relay(proc)
 272  
 273  
 274  class TestGlobalConnLimit:
 275      """ORLY_MAX_GLOBAL_CONNECTIONS limits total connections."""
 276  
 277      def test_excess_connection_rejected(self):
 278          port = 24005
 279          proc, _ = _start_relay(port, {
 280              "ORLY_MAX_GLOBAL_CONNECTIONS": "2",
 281          })
 282          try:
 283              socks = []
 284              for _ in range(2):
 285                  s = _ws_handshake(HOST, port)
 286                  socks.append(s)
 287              # Third connection should be rejected (TCP close).
 288              try:
 289                  s3 = socket.create_connection((HOST, port), timeout=2)
 290                  # Send HTTP request — if global limit works, server closes this.
 291                  s3.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
 292                  s3.settimeout(2)
 293                  data = s3.recv(4096)
 294                  # Connection either closed or gets no WS upgrade
 295                  s3.close()
 296              except (ConnectionError, socket.timeout, OSError):
 297                  pass  # expected — rejected
 298              for s in socks:
 299                  s.close()
 300          finally:
 301              _stop_relay(proc)
 302  
 303  
 304  class TestPerIPConnLimit:
 305      """ORLY_MAX_CONN_PER_IP limits connections per IP."""
 306  
 307      def test_excess_per_ip_rejected(self):
 308          port = 24006
 309          proc, _ = _start_relay(port, {
 310              "ORLY_MAX_CONN_PER_IP": "2",
 311          })
 312          try:
 313              socks = []
 314              for _ in range(2):
 315                  s = _ws_handshake(HOST, port)
 316                  socks.append(s)
 317              # Third from same IP should fail.
 318              try:
 319                  s3 = socket.create_connection((HOST, port), timeout=2)
 320                  s3.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
 321                  s3.settimeout(2)
 322                  data = s3.recv(4096)
 323                  s3.close()
 324              except (ConnectionError, socket.timeout, OSError):
 325                  pass  # expected
 326              for s in socks:
 327                  s.close()
 328          finally:
 329              _stop_relay(proc)
 330  
 331  
 332  class TestHTTPGuard:
 333      """HTTP guard rate limiting and bot blocking."""
 334  
 335      def test_bot_user_agent_blocked(self):
 336          port = 24007
 337          proc, _ = _start_relay(port, {
 338              "ORLY_HTTP_GUARD_ENABLED": "true",
 339              "ORLY_HTTP_GUARD_BOT_BLOCK": "true",
 340          })
 341          try:
 342              req = urllib.request.Request(
 343                  f"http://{HOST}:{port}/health",
 344                  headers={"User-Agent": "Mozilla/5.0 (compatible; AhrefsBot/7.0)"},
 345              )
 346              try:
 347                  resp = urllib.request.urlopen(req, timeout=3)
 348                  # Should get 403 forbidden
 349                  assert resp.status == 403
 350              except urllib.error.HTTPError as e:
 351                  assert e.code == 403
 352          finally:
 353              _stop_relay(proc)
 354  
 355      def test_normal_user_agent_allowed(self):
 356          port = 24008
 357          proc, _ = _start_relay(port, {
 358              "ORLY_HTTP_GUARD_ENABLED": "true",
 359              "ORLY_HTTP_GUARD_BOT_BLOCK": "true",
 360          })
 361          try:
 362              req = urllib.request.Request(
 363                  f"http://{HOST}:{port}/health",
 364                  headers={"User-Agent": "Mozilla/5.0 Firefox"},
 365              )
 366              resp = urllib.request.urlopen(req, timeout=3)
 367              assert resp.status == 200
 368          finally:
 369              _stop_relay(proc)
 370  
 371  
 372  class TestOpenRelay:
 373      """Default open relay — no auth required, events flow freely."""
 374  
 375      def test_publish_and_query(self):
 376          port = 24010
 377          proc, _ = _start_relay(port)
 378          try:
 379              ws = _ws_handshake(HOST, port)
 380              # Drain any AUTH challenge (only sent if RelayURL is set).
 381              time.sleep(0.2)
 382  
 383              ev = make_event(TEST_SECKEY, "open-relay-test", kind=1)
 384              _ws_send_json(ws, ["EVENT", ev])
 385              ok = _drain_until(ws, "OK")
 386              assert ok[2] is True, f"rejected: {ok}"
 387  
 388              # Query it back.
 389              _ws_send_json(ws, ["REQ", "q1", {"ids": [ev["id"]]}])
 390              msg = _drain_until(ws, "EVENT")
 391              assert msg[2]["id"] == ev["id"]
 392              _drain_until(ws, "EOSE")
 393              _ws_send_json(ws, ["CLOSE", "q1"])
 394              ws.close()
 395          finally:
 396              _stop_relay(proc)
 397  
 398  
 399  class TestAuthToWrite:
 400      """ORLY_AUTH_TO_WRITE=true requires NIP-42 auth before EVENT."""
 401  
 402      def test_unauthed_event_rejected(self):
 403          port = 24011
 404          proc, _ = _start_relay(port, {
 405              "ORLY_RELAY_URL": f"ws://{HOST}:{port}",
 406              "ORLY_AUTH_TO_WRITE": "true",
 407              "ORLY_FREE_WRITE_LIMIT": "0",
 408          })
 409          try:
 410              ws = _ws_handshake(HOST, port)
 411              # Drain AUTH challenge.
 412              auth_msg = _drain_until(ws, "AUTH")
 413              assert auth_msg[0] == "AUTH"
 414  
 415              # Send event without authenticating.
 416              ev = make_event(TEST_SECKEY, "should-be-rejected", kind=1)
 417              _ws_send_json(ws, ["EVENT", ev])
 418              ok = _drain_until(ws, "OK")
 419              assert ok[2] is False, "unauthed event should be rejected"
 420              assert "auth-required" in ok[3]
 421              ws.close()
 422          finally:
 423              _stop_relay(proc)
 424  
 425  
 426  class TestAuthRequired:
 427      """ORLY_AUTH_REQUIRED=true requires auth for REQ/COUNT."""
 428  
 429      def test_unauthed_req_closed(self):
 430          port = 24012
 431          proc, _ = _start_relay(port, {
 432              "ORLY_RELAY_URL": f"ws://{HOST}:{port}",
 433              "ORLY_AUTH_REQUIRED": "true",
 434          })
 435          try:
 436              ws = _ws_handshake(HOST, port)
 437              _drain_until(ws, "AUTH")
 438  
 439              _ws_send_json(ws, ["REQ", "test-sub", {"limit": 1}])
 440              msg = _drain_until(ws, "CLOSED", timeout=10)
 441              assert "auth-required" in msg[2]
 442              ws.close()
 443          finally:
 444              _stop_relay(proc)
 445  
 446  
 447  class TestFreeWriteLimit:
 448      """ORLY_FREE_WRITE_LIMIT caps unauthed writes per IP."""
 449  
 450      def test_free_writes_then_rate_limit(self):
 451          port = 24013
 452          proc, _ = _start_relay(port, {
 453              "ORLY_RELAY_URL": f"ws://{HOST}:{port}",
 454              "ORLY_AUTH_TO_WRITE": "true",
 455              "ORLY_FREE_WRITE_LIMIT": "3",
 456              "ORLY_FREE_WRITE_WINDOW": "3600",
 457          })
 458          try:
 459              ws = _ws_handshake(HOST, port)
 460              _drain_until(ws, "AUTH")
 461  
 462              # First 3 should succeed (free write bucket).
 463              for i in range(3):
 464                  ev = make_event(TEST_SECKEY, f"free-{i}", kind=1)
 465                  _ws_send_json(ws, ["EVENT", ev])
 466                  ok = _drain_until(ws, "OK")
 467                  assert ok[2] is True, f"event {i} rejected: {ok}"
 468  
 469              # 4th should be rate-limited.
 470              ev = make_event(TEST_SECKEY, "free-overflow", kind=1)
 471              _ws_send_json(ws, ["EVENT", ev])
 472              ok = _drain_until(ws, "OK")
 473              assert ok[2] is False
 474              assert "rate-limited" in ok[3]
 475              ws.close()
 476          finally:
 477              _stop_relay(proc)
 478  
 479  
 480  class TestSubscriptionLimit:
 481      """ORLY_MAX_SUBSCRIPTIONS limits active subscriptions per connection."""
 482  
 483      def test_excess_sub_closed(self):
 484          port = 24014
 485          proc, _ = _start_relay(port, {
 486              "ORLY_MAX_SUBSCRIPTIONS": "3",
 487          })
 488          try:
 489              ws = _ws_handshake(HOST, port)
 490              time.sleep(0.2)
 491  
 492              # Open 3 subscriptions.
 493              for i in range(3):
 494                  _ws_send_json(ws, ["REQ", f"sub-{i}", {"limit": 1}])
 495                  _drain_until(ws, "EOSE")
 496  
 497              # 4th should be rejected.
 498              _ws_send_json(ws, ["REQ", "sub-overflow", {"limit": 1}])
 499              msg = _drain_until(ws, "CLOSED")
 500              assert "too many" in msg[2]
 501              ws.close()
 502          finally:
 503              _stop_relay(proc)
 504  
 505  
 506  class TestQueryResultLimit:
 507      """ORLY_QUERY_RESULT_LIMIT caps events returned per REQ."""
 508  
 509      def test_result_capped(self):
 510          port = 24015
 511          proc, _ = _start_relay(port, {
 512              "ORLY_QUERY_RESULT_LIMIT": "5",
 513          })
 514          try:
 515              ws = _ws_handshake(HOST, port)
 516              time.sleep(0.2)
 517  
 518              # Publish 10 events.
 519              for i in range(10):
 520                  ev = make_event(TEST_SECKEY, f"limit-test-{i}", kind=1,
 521                                  created_at=int(time.time()) - 100 + i)
 522                  _ws_send_json(ws, ["EVENT", ev])
 523                  _drain_until(ws, "OK")
 524  
 525              # Query all — should get at most 5.
 526              _ws_send_json(ws, ["REQ", "q-limit", {"authors": [TEST_PUBKEY], "kinds": [1]}])
 527              count = 0
 528              while True:
 529                  msg = _ws_recv_json(ws)
 530                  if msg[0] == "EOSE":
 531                      break
 532                  if msg[0] == "EVENT":
 533                      count += 1
 534              assert count <= 5, f"got {count} events, expected at most 5"
 535              _ws_send_json(ws, ["CLOSE", "q-limit"])
 536              ws.close()
 537          finally:
 538              _stop_relay(proc)
 539  
 540  
 541  class TestLiveSubscription:
 542      """Live subscription receives broadcast events."""
 543  
 544      def test_live_delivery(self):
 545          port = 24016
 546          proc, _ = _start_relay(port)
 547          try:
 548              # Subscriber connects and subscribes.
 549              sub_ws = _ws_handshake(HOST, port)
 550              time.sleep(0.1)
 551              _ws_send_json(sub_ws, ["REQ", "live", {"authors": [TEST_PUBKEY], "kinds": [1]}])
 552              _drain_until(sub_ws, "EOSE")
 553  
 554              # Publisher sends an event.
 555              pub_ws = _ws_handshake(HOST, port)
 556              time.sleep(0.1)
 557              ev = make_event(TEST_SECKEY, "live-broadcast-test", kind=1)
 558              _ws_send_json(pub_ws, ["EVENT", ev])
 559              ok = _drain_until(pub_ws, "OK")
 560              assert ok[2] is True
 561  
 562              # Subscriber should get it.
 563              msg = _ws_recv_json(sub_ws, timeout=5)
 564              assert msg[0] == "EVENT"
 565              assert msg[2]["content"] == "live-broadcast-test"
 566  
 567              _ws_send_json(sub_ws, ["CLOSE", "live"])
 568              sub_ws.close()
 569              pub_ws.close()
 570          finally:
 571              _stop_relay(proc)
 572  
 573  
 574  class TestReplaceableEvents:
 575      """NIP-01 replaceable event handling — newer replaces older."""
 576  
 577      def test_replaceable_kind_overwrites(self):
 578          port = 24017
 579          proc, _ = _start_relay(port)
 580          try:
 581              ws = _ws_handshake(HOST, port)
 582              time.sleep(0.1)
 583  
 584              now = int(time.time())
 585              # Kind 0 (metadata) is replaceable.
 586              ev1 = make_event(TEST_SECKEY, '{"name":"old"}', kind=0, created_at=now - 10)
 587              _ws_send_json(ws, ["EVENT", ev1])
 588              ok1 = _drain_until(ws, "OK")
 589              assert ok1[2] is True
 590  
 591              ev2 = make_event(TEST_SECKEY, '{"name":"new"}', kind=0, created_at=now)
 592              _ws_send_json(ws, ["EVENT", ev2])
 593              ok2 = _drain_until(ws, "OK")
 594              assert ok2[2] is True
 595  
 596              # Query — should only get the newer one.
 597              _ws_send_json(ws, ["REQ", "rep", {"authors": [TEST_PUBKEY], "kinds": [0]}])
 598              events = []
 599              while True:
 600                  msg = _ws_recv_json(ws)
 601                  if msg[0] == "EOSE":
 602                      break
 603                  if msg[0] == "EVENT":
 604                      events.append(msg[2])
 605              assert len(events) == 1
 606              assert events[0]["content"] == '{"name":"new"}'
 607  
 608              _ws_send_json(ws, ["CLOSE", "rep"])
 609              ws.close()
 610          finally:
 611              _stop_relay(proc)
 612  
 613  
 614  class TestEphemeralEvents:
 615      """NIP-16 ephemeral events are accepted but not stored."""
 616  
 617      def test_ephemeral_not_stored(self):
 618          port = 24018
 619          proc, _ = _start_relay(port)
 620          try:
 621              ws = _ws_handshake(HOST, port)
 622              time.sleep(0.1)
 623  
 624              # Kind 20000-29999 are ephemeral.
 625              ev = make_event(TEST_SECKEY, "ephemeral-test", kind=20001)
 626              _ws_send_json(ws, ["EVENT", ev])
 627              ok = _drain_until(ws, "OK")
 628              assert ok[2] is True
 629  
 630              # Query — should not find it.
 631              _ws_send_json(ws, ["REQ", "eph", {"ids": [ev["id"]]}])
 632              msg = _drain_until(ws, "EOSE")
 633              # No EVENT should precede the EOSE for this ID.
 634              ws.close()
 635          finally:
 636              _stop_relay(proc)
 637  
 638  
 639  class TestDeletion:
 640      """NIP-09 event deletion."""
 641  
 642      def test_delete_own_event(self):
 643          port = 24019
 644          proc, _ = _start_relay(port)
 645          try:
 646              ws = _ws_handshake(HOST, port)
 647              time.sleep(0.1)
 648  
 649              ev = make_event(TEST_SECKEY, "to-be-deleted", kind=1)
 650              _ws_send_json(ws, ["EVENT", ev])
 651              ok = _drain_until(ws, "OK")
 652              assert ok[2] is True
 653  
 654              # Delete it — kind 5, with "e" tag pointing to the event.
 655              del_ev = make_event(TEST_SECKEY, "", kind=5, tags=[["e", ev["id"]]])
 656              _ws_send_json(ws, ["EVENT", del_ev])
 657              ok2 = _drain_until(ws, "OK")
 658              assert ok2[2] is True
 659  
 660              # Query — should not find the original event.
 661              _ws_send_json(ws, ["REQ", "del", {"ids": [ev["id"]]}])
 662              msg = _drain_until(ws, "EOSE")
 663              _ws_send_json(ws, ["CLOSE", "del"])
 664              ws.close()
 665          finally:
 666              _stop_relay(proc)
 667  
 668  
 669  class TestNIP42AuthChallenge:
 670      """NIP-42 AUTH challenge is sent when RelayURL is configured."""
 671  
 672      def test_auth_challenge_sent(self):
 673          port = 24020
 674          proc, _ = _start_relay(port, {
 675              "ORLY_RELAY_URL": f"ws://{HOST}:{port}",
 676          })
 677          try:
 678              ws = _ws_handshake(HOST, port)
 679              msg = _drain_until(ws, "AUTH")
 680              assert msg[0] == "AUTH"
 681              assert isinstance(msg[1], str)
 682              assert len(msg[1]) == 64  # 32 bytes hex
 683              ws.close()
 684          finally:
 685              _stop_relay(proc)
 686  
 687      def test_no_challenge_without_relay_url(self):
 688          port = 24021
 689          proc, _ = _start_relay(port)
 690          try:
 691              ws = _ws_handshake(HOST, port)
 692              # With no RelayURL, no AUTH challenge. Send REQ instead.
 693              _ws_send_json(ws, ["REQ", "nochall", {"limit": 1}])
 694              msg = _ws_recv_json(ws)
 695              # Should get EOSE, not AUTH.
 696              assert msg[0] in ("EVENT", "EOSE"), f"unexpected: {msg[0]}"
 697              ws.close()
 698          finally:
 699              _stop_relay(proc)
 700  
 701  
 702  class TestEventValidation:
 703      """Pipeline rejects malformed events."""
 704  
 705      def test_bad_signature_rejected(self):
 706          port = 24022
 707          proc, _ = _start_relay(port)
 708          try:
 709              ws = _ws_handshake(HOST, port)
 710              time.sleep(0.1)
 711  
 712              ev = make_event(TEST_SECKEY, "bad-sig-test", kind=1)
 713              # Corrupt the signature.
 714              ev["sig"] = "00" * 64
 715              _ws_send_json(ws, ["EVENT", ev])
 716              ok = _drain_until(ws, "OK")
 717              assert ok[2] is False
 718              assert "invalid" in ok[3] or "bad" in ok[3].lower() or "signature" in ok[3].lower()
 719              ws.close()
 720          finally:
 721              _stop_relay(proc)
 722  
 723      def test_future_timestamp_rejected(self):
 724          port = 24023
 725          proc, _ = _start_relay(port)
 726          try:
 727              ws = _ws_handshake(HOST, port)
 728              time.sleep(0.1)
 729  
 730              far_future = int(time.time()) + 86400
 731              ev = make_event(TEST_SECKEY, "future-test", kind=1, created_at=far_future)
 732              _ws_send_json(ws, ["EVENT", ev])
 733              ok = _drain_until(ws, "OK")
 734              assert ok[2] is False
 735              assert "future" in ok[3]
 736              ws.close()
 737          finally:
 738              _stop_relay(proc)
 739  
 740  
 741  class TestCloseSubscription:
 742      """CLOSE unsubscribes — no more events after CLOSE."""
 743  
 744      def test_close_stops_delivery(self):
 745          port = 24024
 746          proc, _ = _start_relay(port)
 747          try:
 748              ws = _ws_handshake(HOST, port)
 749              time.sleep(0.1)
 750  
 751              _ws_send_json(ws, ["REQ", "closeme", {"authors": [TEST_PUBKEY], "kinds": [1]}])
 752              _drain_until(ws, "EOSE")
 753              _ws_send_json(ws, ["CLOSE", "closeme"])
 754              time.sleep(0.2)
 755  
 756              # Publish an event — should NOT arrive on the closed sub.
 757              ev = make_event(TEST_SECKEY, "after-close", kind=1)
 758              pub_ws = _ws_handshake(HOST, port)
 759              _ws_send_json(pub_ws, ["EVENT", ev])
 760              _drain_until(pub_ws, "OK")
 761              pub_ws.close()
 762  
 763              # Try to read — should timeout (no event delivered).
 764              try:
 765                  msg = _ws_recv_json(ws, timeout=1)
 766                  # If we get something, it should not be an EVENT for closeme.
 767                  if msg[0] == "EVENT":
 768                      assert msg[1] != "closeme", "received event on closed subscription"
 769              except (socket.timeout, ConnectionError):
 770                  pass  # expected — no message
 771              ws.close()
 772          finally:
 773              _stop_relay(proc)
 774  
 775  
 776  class TestCountEnvelope:
 777      """NIP-45 COUNT returns event counts."""
 778  
 779      def test_count_returns_number(self):
 780          port = 24025
 781          proc, _ = _start_relay(port)
 782          try:
 783              ws = _ws_handshake(HOST, port)
 784              time.sleep(0.1)
 785  
 786              # Publish a few events.
 787              for i in range(3):
 788                  ev = make_event(TEST_SECKEY, f"count-{i}", kind=1,
 789                                  created_at=int(time.time()) + i)
 790                  _ws_send_json(ws, ["EVENT", ev])
 791                  _drain_until(ws, "OK")
 792  
 793              _ws_send_json(ws, ["COUNT", "c1", {"authors": [TEST_PUBKEY], "kinds": [1]}])
 794              msg = _drain_until(ws, "COUNT")
 795              assert msg[1] == "c1"
 796              count = msg[2] if isinstance(msg[2], int) else msg[2].get("count", 0)
 797              assert count >= 3
 798              ws.close()
 799          finally:
 800              _stop_relay(proc)
 801