feat: add sender/recipient accept gates, security+stress test harnesses, nix flake, and docs
This commit is contained in:
parent
a0950fab52
commit
5dda6567af
18 changed files with 1764 additions and 44 deletions
|
|
@ -1,7 +1,60 @@
|
|||
from email.message import EmailMessage
|
||||
from types import SimpleNamespace
|
||||
|
||||
from pneumatube.email_to_smol import EmailToSmolBridge, _single_line
|
||||
|
||||
_DEFAULT_PORT = 1961
|
||||
|
||||
|
||||
class _Address:
|
||||
def __init__(self, user, host, port):
|
||||
self.user, self.host, self.port = user, host, port
|
||||
|
||||
@property
|
||||
def short(self):
|
||||
return f"{self.user}@{self.host}" + ("" if self.port == _DEFAULT_PORT else f":{self.port}")
|
||||
|
||||
|
||||
class _StubAddressClass:
|
||||
@staticmethod
|
||||
def parse(text):
|
||||
user, _, hostport = text.partition("@")
|
||||
host, _, port = hostport.partition(":")
|
||||
return _Address(user, host, int(port) if port else _DEFAULT_PORT)
|
||||
|
||||
|
||||
class _StubSmol:
|
||||
Address = _StubAddressClass
|
||||
|
||||
|
||||
class _StubStore:
|
||||
def __init__(self, tokens):
|
||||
self.tokens = tokens
|
||||
|
||||
def one(self, sql, address):
|
||||
return (b"token",) if address in self.tokens else None
|
||||
|
||||
|
||||
def test_recipient_accepted_gateway_true_when_token_held():
|
||||
bridge = EmailToSmolBridge(_StubSmol(), _StubStore({"alice@smol.example"}),
|
||||
config=SimpleNamespace(smolmail_domain="smol.example"))
|
||||
assert bridge.recipient_accepted_gateway("alice") is True
|
||||
|
||||
|
||||
def test_recipient_accepted_gateway_false_when_no_token():
|
||||
bridge = EmailToSmolBridge(_StubSmol(), _StubStore(set()),
|
||||
config=SimpleNamespace(smolmail_domain="smol.example"))
|
||||
assert bridge.recipient_accepted_gateway("alice") is False
|
||||
|
||||
|
||||
def test_recipient_accepted_gateway_normalizes_default_port():
|
||||
"""A configured smolmail_domain carrying an explicit default port must
|
||||
still match a token stored under Address.short's normalized form (which
|
||||
drops it) -- naive string concatenation would never match."""
|
||||
bridge = EmailToSmolBridge(_StubSmol(), _StubStore({"alice@smol.example"}),
|
||||
config=SimpleNamespace(smolmail_domain="smol.example:1961"))
|
||||
assert bridge.recipient_accepted_gateway("alice") is True
|
||||
|
||||
|
||||
def test_single_line_strips_crlf():
|
||||
assert _single_line("alice@example.org\r\nAccept: forged") == "alice@example.org Accept: forged"
|
||||
|
|
|
|||
|
|
@ -8,22 +8,27 @@ from pneumatube.lookup_server import _lookup
|
|||
|
||||
|
||||
class _StubBridge:
|
||||
def __init__(self, known):
|
||||
def __init__(self, known, accepted=None):
|
||||
self.known = known
|
||||
self.accepted = known if accepted is None else accepted
|
||||
|
||||
def user_exists(self, username):
|
||||
if username == "broken":
|
||||
return None
|
||||
return username in self.known
|
||||
|
||||
def recipient_accepted_gateway(self, username):
|
||||
return username in self.accepted
|
||||
|
||||
|
||||
class _InlineWorker:
|
||||
async def run(self, fn, *args):
|
||||
return fn(*args)
|
||||
|
||||
|
||||
def _config():
|
||||
return SimpleNamespace(email_domain="gateway.example")
|
||||
def _config(**overrides):
|
||||
defaults = {"email_domain": "gateway.example", "require_accepted_recipient": True}
|
||||
return SimpleNamespace(**{**defaults, **overrides})
|
||||
|
||||
|
||||
def test_lookup_known_user_returns_ok():
|
||||
|
|
@ -52,3 +57,20 @@ def test_lookup_other_domain_has_no_opinion():
|
|||
bridge = _StubBridge({"alice"})
|
||||
reply = asyncio.run(_lookup(bridge, _InlineWorker(), _config(), "alice@other.example"))
|
||||
assert reply == "500 not found"
|
||||
|
||||
|
||||
def test_lookup_rejects_unaccepted_recipient_by_default():
|
||||
bridge = _StubBridge({"alice"}, accepted=set())
|
||||
reply = asyncio.run(_lookup(bridge, _InlineWorker(), _config(), "alice@gateway.example"))
|
||||
code, _, text = reply.partition(" ")
|
||||
assert code == "200"
|
||||
assert unquote(text) == "550 5.7.1 recipient has not accepted mail from this gateway"
|
||||
|
||||
|
||||
def test_lookup_allows_unaccepted_recipient_when_disabled():
|
||||
bridge = _StubBridge({"alice"}, accepted=set())
|
||||
config = _config(require_accepted_recipient=False)
|
||||
reply = asyncio.run(_lookup(bridge, _InlineWorker(), config, "alice@gateway.example"))
|
||||
code, _, text = reply.partition(" ")
|
||||
assert code == "200"
|
||||
assert unquote(text) == "OK"
|
||||
|
|
|
|||
65
tests/test_smol_to_email.py
Normal file
65
tests/test_smol_to_email.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
from types import SimpleNamespace
|
||||
|
||||
from pneumatube.smol_to_email import SmolToEmailBridge
|
||||
|
||||
|
||||
class _StubSmol:
|
||||
SmolError = RuntimeError
|
||||
|
||||
def cmd_fetch(self, args, store):
|
||||
pass
|
||||
|
||||
|
||||
class _StubStore:
|
||||
def __init__(self, rows):
|
||||
self._rows = rows
|
||||
self.requested_box = None
|
||||
|
||||
def mail(self, box):
|
||||
self.requested_box = box
|
||||
return self._rows
|
||||
|
||||
|
||||
def _config(**overrides):
|
||||
defaults = {"smolmail_key": "k", "smolmail_db": "d", "require_accepted_sender": True}
|
||||
return SimpleNamespace(**{**defaults, **overrides})
|
||||
|
||||
|
||||
def test_poll_once_does_not_stop_after_one_message_fails():
|
||||
"""A message that keeps raising out of _relay() (e.g. a value
|
||||
smtp_client.send() rejects that _relay()'s own except clause doesn't
|
||||
cover) must not block every message behind it -- it always sorts first
|
||||
on the next poll, since only a successful _relay() deletes it."""
|
||||
rows = [(b"poison", b"", 0, None), (b"ok", b"", 1, None)]
|
||||
bridge = SmolToEmailBridge(_StubSmol(), _StubStore(rows), account=None, config=_config())
|
||||
|
||||
relayed = []
|
||||
|
||||
def fake_relay(mid, envelope):
|
||||
if mid == b"poison":
|
||||
raise ValueError("simulated failure unrelated to InvalidAddress/OSError")
|
||||
relayed.append(mid)
|
||||
|
||||
bridge._relay = fake_relay
|
||||
bridge.poll_once()
|
||||
|
||||
assert relayed == [b"ok"]
|
||||
|
||||
|
||||
def test_poll_once_uses_main_tier_only_by_default():
|
||||
"""require_accepted_sender=True (the default) must poll "inbox" (main
|
||||
tier), not "all" -- "all" would include requests-tier mail from
|
||||
first-contact senders with no accept token (SPEC.md S5.8), which is
|
||||
exactly what this setting exists to keep the gateway from relaying."""
|
||||
store = _StubStore([])
|
||||
bridge = SmolToEmailBridge(_StubSmol(), store, account=None, config=_config())
|
||||
bridge.poll_once()
|
||||
assert store.requested_box == "inbox"
|
||||
|
||||
|
||||
def test_poll_once_uses_all_tiers_when_open_bridge_enabled():
|
||||
store = _StubStore([])
|
||||
bridge = SmolToEmailBridge(_StubSmol(), store, account=None,
|
||||
config=_config(require_accepted_sender=False))
|
||||
bridge.poll_once()
|
||||
assert store.requested_box == "all"
|
||||
|
|
@ -7,14 +7,22 @@ from pneumatube.smtp_server import GatewayHandler
|
|||
|
||||
|
||||
class _StubBridge:
|
||||
def __init__(self):
|
||||
def __init__(self, known=("alice", "bob", "broken"), accepted=("alice", "bob", "broken")):
|
||||
self.forwarded = []
|
||||
self.known = set(known)
|
||||
self.accepted = set(accepted)
|
||||
|
||||
def forward(self, username, sender, subject, body):
|
||||
def forward(self, username, subject, body):
|
||||
self.forwarded.append(username)
|
||||
if username == "broken":
|
||||
raise RuntimeError("smolmail server unreachable")
|
||||
|
||||
def user_exists(self, username):
|
||||
return username in self.known
|
||||
|
||||
def recipient_accepted_gateway(self, username):
|
||||
return username in self.accepted
|
||||
|
||||
@staticmethod
|
||||
def extract_text(message):
|
||||
return message.get_payload(decode=True).decode("utf-8", "replace")
|
||||
|
|
@ -36,9 +44,58 @@ def _envelope(rcpt_tos):
|
|||
)
|
||||
|
||||
|
||||
def _config(**overrides):
|
||||
defaults = {"email_domain": "gateway.example", "require_accepted_recipient": True}
|
||||
return SimpleNamespace(**{**defaults, **overrides})
|
||||
|
||||
|
||||
def test_handle_rcpt_rejects_wrong_domain():
|
||||
handler = GatewayHandler(_StubBridge(), _InlineWorker(), config=_config())
|
||||
reply = asyncio.run(handler.handle_RCPT(None, None, _envelope([]),
|
||||
"alice@other.example", None))
|
||||
assert reply.startswith("550")
|
||||
|
||||
|
||||
def test_handle_rcpt_rejects_unknown_user():
|
||||
handler = GatewayHandler(_StubBridge(known=()), _InlineWorker(), config=_config())
|
||||
reply = asyncio.run(handler.handle_RCPT(None, None, _envelope([]),
|
||||
"ghost@gateway.example", None))
|
||||
assert reply.startswith("550")
|
||||
|
||||
|
||||
def test_handle_rcpt_rejects_unaccepted_recipient_by_default():
|
||||
"""The all-or-nothing gate: a recipient who exists but has not accepted
|
||||
the gateway (no token held) must be rejected live, not silently demoted
|
||||
to the recipient's own requests tier."""
|
||||
bridge = _StubBridge(known=("alice",), accepted=())
|
||||
handler = GatewayHandler(bridge, _InlineWorker(), config=_config())
|
||||
reply = asyncio.run(handler.handle_RCPT(None, None, _envelope([]),
|
||||
"alice@gateway.example", None))
|
||||
assert reply.startswith("550")
|
||||
|
||||
|
||||
def test_handle_rcpt_allows_unaccepted_recipient_when_disabled():
|
||||
bridge = _StubBridge(known=("alice",), accepted=())
|
||||
handler = GatewayHandler(bridge, _InlineWorker(),
|
||||
config=_config(require_accepted_recipient=False))
|
||||
envelope = _envelope([])
|
||||
reply = asyncio.run(handler.handle_RCPT(None, None, envelope, "alice@gateway.example", None))
|
||||
assert reply.startswith("250")
|
||||
assert envelope.rcpt_tos == ["alice@gateway.example"]
|
||||
|
||||
|
||||
def test_handle_rcpt_accepts_known_accepted_recipient():
|
||||
bridge = _StubBridge(known=("alice",), accepted=("alice",))
|
||||
handler = GatewayHandler(bridge, _InlineWorker(), config=_config())
|
||||
envelope = _envelope([])
|
||||
reply = asyncio.run(handler.handle_RCPT(None, None, envelope, "alice@gateway.example", None))
|
||||
assert reply.startswith("250")
|
||||
assert envelope.rcpt_tos == ["alice@gateway.example"]
|
||||
|
||||
|
||||
def test_handle_data_replies_once_per_recipient():
|
||||
bridge = _StubBridge()
|
||||
handler = GatewayHandler(bridge, _InlineWorker(), config=SimpleNamespace())
|
||||
handler = GatewayHandler(bridge, _InlineWorker(), config=_config())
|
||||
envelope = _envelope(["alice@gateway.example", "broken@gateway.example"])
|
||||
|
||||
reply = asyncio.run(handler.handle_DATA(None, None, envelope))
|
||||
|
|
@ -52,7 +109,7 @@ def test_handle_data_replies_once_per_recipient():
|
|||
|
||||
def test_handle_data_all_succeed():
|
||||
bridge = _StubBridge()
|
||||
handler = GatewayHandler(bridge, _InlineWorker(), config=SimpleNamespace())
|
||||
handler = GatewayHandler(bridge, _InlineWorker(), config=_config())
|
||||
envelope = _envelope(["alice@gateway.example", "bob@gateway.example"])
|
||||
|
||||
reply = asyncio.run(handler.handle_DATA(None, None, envelope))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue