fix(stalwart): fix all comments, fix tor approach, SPOT fixes and chagne some values to follow standars + remove comemnts

This commit is contained in:
Alejandro Roman committed 2026-09-02 22:05:45 +04:00
1 parent e809765e23
commit 942fdb5fad
25 files changed
+802 -2

No files matched your search

@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
@@ -0,0 +1,136 @@
"""What the Tor SMTP gateway accepts, and where it routes each recipient.
The gateway is not an open relay: it accepts a recipient ONLY when the domain
ends with ``.onion``, and it delivers each ``.onion`` domain's recipients in one
hop. The heavy dependencies (aiosmtpd, PySocks) are stubbed here so the routing
logic is testable without them, and ``_deliver`` is replaced so nothing dials
the network.
"""
from __future__ import annotations
import asyncio
import importlib.util
import os
import sys
import types
import unittest
from unittest import mock
from . import PROJECT_ROOT
MODULE = PROJECT_ROOT / "roles" / "svc-net-tor-smtp" / "files" / "python" / "tor_smtp_gateway.py"
REQUIRED_ENV = {
"TOR_SMTP_LISTEN_PORT": "1525",
"TOR_SOCKS_HOST": "tor",
"TOR_SOCKS_PORT": "9050",
"TOR_SMTP_HELO": "node.example.onion",
}
def _load(env=None):
"""Import the daemon with the required env stubbed. A None override drops
the key, so a test can assert a required var is missing."""
socks_stub = types.ModuleType("socks")
socks_stub.SOCKS5 = 2
socks_stub.create_connection = lambda *a, **k: None
controller_stub = types.ModuleType("aiosmtpd.controller")
controller_stub.Controller = object
aiosmtpd_pkg = types.ModuleType("aiosmtpd")
aiosmtpd_pkg.controller = controller_stub
merged = {k: v for k, v in {**REQUIRED_ENV, **(env or {})}.items() if v is not None}
with mock.patch.dict(sys.modules, {
"socks": socks_stub,
"aiosmtpd": aiosmtpd_pkg,
"aiosmtpd.controller": controller_stub,
}), mock.patch.dict(os.environ, merged, clear=True):
spec = importlib.util.spec_from_file_location("tor_smtp_gateway", MODULE)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class _Envelope:
def __init__(self, mail_from="bot@x.onion", rcpt_tos=None, content=b"msg"):
self.mail_from = mail_from
self.rcpt_tos = list(rcpt_tos or [])
self.content = content
class TestDomainGrouping(unittest.TestCase):
def setUp(self):
self.mod = _load()
def test_recipients_group_by_domain(self):
grouped = self.mod._group_by_domain(
["a@one.onion", "b@one.onion", "c@two.onion"]
)
self.assertEqual(grouped, {"one.onion": ["a@one.onion", "b@one.onion"], "two.onion": ["c@two.onion"]})
def test_domain_match_is_case_insensitive(self):
grouped = self.mod._group_by_domain(["A@One.Onion"])
self.assertEqual(list(grouped), ["one.onion"])
class TestRcptGate(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.mod = _load()
self.relay = self.mod.OnionRelay()
async def _rcpt(self, address):
env = _Envelope(rcpt_tos=[])
reply = await self.relay.handle_RCPT(None, None, env, address, [])
return reply, env
async def test_an_onion_recipient_is_accepted(self):
reply, env = await self._rcpt("biber@abc.onion")
self.assertTrue(reply.startswith("250"))
self.assertEqual(env.rcpt_tos, ["biber@abc.onion"])
async def test_a_clearnet_recipient_is_refused(self):
reply, env = await self._rcpt("biber@infinito.test")
self.assertTrue(reply.startswith("550"))
self.assertEqual(env.rcpt_tos, [])
class TestDataDelivery(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.mod = _load()
self.relay = self.mod.OnionRelay()
async def test_each_onion_domain_gets_one_delivery(self):
calls = []
with mock.patch.object(self.mod, "_deliver", side_effect=lambda *a: calls.append(a)):
env = _Envelope(rcpt_tos=["a@one.onion", "b@one.onion", "c@two.onion"])
reply = await self.relay.handle_DATA(None, None, env)
self.assertTrue(reply.startswith("250"))
self.assertEqual({c[0] for c in calls}, {"one.onion", "two.onion"})
async def test_a_failed_hop_is_a_transient_error(self):
def boom(*_a):
raise OSError("tor down")
with mock.patch.object(self.mod, "_deliver", side_effect=boom):
env = _Envelope(rcpt_tos=["a@one.onion"])
reply = await self.relay.handle_DATA(None, None, env)
self.assertTrue(reply.startswith("451"))
class TestConfiguration(unittest.TestCase):
def test_the_helo_name_comes_from_the_environment(self):
mod = _load({"TOR_SMTP_HELO": "biber.node.onion"})
self.assertEqual(mod.HELO_NAME, "biber.node.onion")
def test_the_helo_never_falls_back_to_the_bind_address(self):
"""EHLO 0.0.0.0 is malformed; a missing HELO must fail loudly, not
silently announce the bind address to the peer."""
with self.assertRaises(KeyError):
_load({"TOR_SMTP_HELO": None})
def test_the_onion_hop_targets_the_well_known_smtp_port(self):
self.assertEqual(_load().ONION_SMTP_PORT, 25)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,137 @@
"""How Stalwart routes .onion recipients to the Tor SMTP gateway.
Stalwart has no outbound SOCKS of its own, so ``14_onion_route.yml`` provisions
a relay ``MtaRoute`` to the gateway and points the ``MtaOutboundStrategy`` route
expression at it for ``.onion`` recipients. The one property that must never
regress: the strategy still sends local recipients to ``local`` and everything
else to ``mx`` — adding the onion branch must not break normal delivery.
"""
from __future__ import annotations
import json
import unittest
from jinja2 import Environment, StrictUndefined
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml_any
from . import PROJECT_ROOT
ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart"
TASK = ROLE / "tasks" / "14_onion_route.yml"
ROUTE_CREATE = ROLE / "templates" / "jmap" / "route" / "create.json.j2"
STRATEGY_GET = ROLE / "templates" / "jmap" / "strategy" / "get.json.j2"
STRATEGY_CREATE = ROLE / "templates" / "jmap" / "strategy" / "create.json.j2"
STRATEGY_UPDATE = ROLE / "templates" / "jmap" / "strategy" / "update.json.j2"
ROUTE_NAME = "onion"
def _render(template_path, **variables) -> str:
env = Environment(
trim_blocks=True,
lstrip_blocks=True,
undefined=StrictUndefined,
autoescape=False, # noqa: S701 - JMAP request bodies, never HTML
)
env.filters["to_json"] = json.dumps
env.filters["int"] = int
return env.from_string(read_text(template_path)).render(**variables)
def _route_expr_from_task() -> dict:
tasks = load_yaml_any(str(TASK), default_if_missing=[])
for task in tasks:
facts = task.get("set_fact") or task.get("ansible.builtin.set_fact") or {}
if "stalwart_route_expr" in facts:
return facts["stalwart_route_expr"]
raise AssertionError("stalwart_route_expr set_fact not found in 14_onion_route.yml")
class TestOutboundStrategyExpression(unittest.TestCase):
def setUp(self):
self.expr = _route_expr_from_task()
def test_local_recipients_still_route_to_local(self):
first = self.expr["match"]["0"]
self.assertEqual(first["if"], "is_local_domain(rcpt_domain)")
self.assertEqual(first["then"], "'local'")
def test_local_is_evaluated_before_onion(self):
"""A local .onion address must be delivered locally, not relayed out."""
keys = list(self.expr["match"].keys())
self.assertEqual(keys, ["0", "1"])
self.assertIn("is_local_domain", self.expr["match"]["0"]["if"])
self.assertIn("ends_with", self.expr["match"]["1"]["if"])
def test_onion_recipients_route_to_the_onion_route(self):
"""then is a Stalwart expression string literal naming the route, from
the same SPOT var the relay route registers itself under."""
onion = self.expr["match"]["1"]
self.assertEqual(onion["if"], "ends_with(rcpt_domain, '.onion')")
self.assertEqual(onion["then"], "'{{ STALWART_ONION_ROUTE_NAME }}'")
def test_everything_else_falls_back_to_mx(self):
self.assertEqual(self.expr["else"], "'mx'")
class TestStrategyTemplateRendersValidJson(unittest.TestCase):
def test_the_singleton_route_is_set_from_the_expression(self):
expr = _route_expr_from_task()
rendered = _render(STRATEGY_UPDATE, stalwart_route_expr=expr)
body = json.loads(rendered)
method, args, _tag = body["methodCalls"][0]
self.assertEqual(method, "x:MtaOutboundStrategy/set")
self.assertEqual(args["update"]["singleton"]["route"], expr)
def test_create_seeds_a_new_singleton_with_the_route(self):
expr = _route_expr_from_task()
rendered = _render(STRATEGY_CREATE, stalwart_route_expr=expr)
body = json.loads(rendered)
method, args, _tag = body["methodCalls"][0]
self.assertEqual(method, "x:MtaOutboundStrategy/set")
(created,) = args["create"].values()
self.assertEqual(created["route"], expr)
def test_get_queries_the_singleton_by_id(self):
"""The singleton is NOT enumerated by get(ids:null); it must be queried
by its fixed "singleton" id or existence detection is always wrong."""
body = json.loads(_render(STRATEGY_GET))
method, args, _tag = body["methodCalls"][0]
self.assertEqual(method, "x:MtaOutboundStrategy/get")
self.assertEqual(args["ids"], ["singleton"])
class TestRelayRouteRendersValidJson(unittest.TestCase):
def _create(self):
rendered = _render(
ROUTE_CREATE,
STALWART_ONION_ROUTE_NAME=ROUTE_NAME,
STALWART_ONION_RELAY_HOST="tor-smtp",
STALWART_ONION_RELAY_PORT=1525,
)
body = json.loads(rendered)
return body["methodCalls"][0]
def test_it_creates_a_relay_route_to_the_gateway(self):
method, args, _tag = self._create()
self.assertEqual(method, "x:MtaRoute/set")
route = args["create"][ROUTE_NAME]
self.assertEqual(route["@type"], "Relay")
self.assertEqual(route["name"], ROUTE_NAME)
self.assertEqual(route["address"], "tor-smtp")
self.assertEqual(route["port"], 1525)
def test_the_relay_hop_is_plaintext_smtp(self):
"""The gateway speaks plaintext SMTP on an internal network; there is no
cert to validate on a .onion relay hop."""
_method, args, _tag = self._create()
route = args["create"][ROUTE_NAME]
self.assertEqual(route["protocol"], "smtp")
self.assertFalse(route["implicitTls"])
if __name__ == "__main__":
unittest.main()