The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(email): parse the From mailbox with the stdlib, not a first angle-bracket match
KeelTraced0c588972ec3
diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex c8e27c6955b..37cbacbc452 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -16,7 +16,7 @@ from email.header import decode_headerfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBase-from email.utils import formatdate+from email.utils import formatdate, parseaddrfrom email import encodersfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple@@ -243,9 +243,24 @@ def _strip_html(html: str) -> str:def _extract_email_address(raw: str) -> str:- """Extract bare email address from 'Name <addr>' format."""- match = re.search(r"<([^>]+)>", raw)- return (match.group(1) if match else raw).strip().lower()+ """Bare address from a From: value, via the stdlib address parser.++ A regex taking the FIRST ``<...>`` pair reads+ ``"Victim <[email protected]>" <[email protected]>`` as the victim,+ causing allowlist, pairing, and session-identity decisions to use an+ address the sender does not control (GHSA-rxqh-5572-8m77).++ ``parseaddr`` keeps the quoted text as the display name and returns the+ actual addr-spec (``[email protected]``), so authorization is evaluated+ against the real sender identity.++ RFC 5322 header folding is unfolded before parsing. Without that step,+ ``parseaddr`` can mistake a folded quoted display name for the mailbox+ itself, dropping legitimate allowlisted mail or polluting session identity.+ """+ value = re.sub(r"\r?\n[ \t]+", " ", str(raw or ""))+ _, addr = parseaddr(value)+ return addr.strip().lower()def _domain_of(address: str) -> str:diff --git a/tests/gateway/test_email.py b/tests/gateway/test_email.pyindex 06be3037425..787118da58d 100644--- a/tests/gateway/test_email.py+++ b/tests/gateway/test_email.py@@ -72,6 +72,38 @@ class TestHelperFunctions(unittest.TestCase):)+ def test_extract_email_address_ignores_angle_brackets_in_display_name(self):+ from plugins.platforms.email.adapter import _extract_email_address+ self.assertEqual(+ _extract_email_address('"Victim <[email protected]>" <[email protected]>'),+ "[email protected]",+ )++ def test_extract_email_address_still_reads_a_normal_address(self):+ """The fail-closed path must not break the ordinary forms."""+ from plugins.platforms.email.adapter import _extract_email_address+ self.assertEqual(_extract_email_address("Plain <[email protected]>"), "[email protected]")+ self.assertEqual(_extract_email_address("[email protected]"), "[email protected]")+ self.assertEqual(_extract_email_address("JOHN DOE <[email protected]>"), "[email protected]")++ def test_extract_email_address_unfolds_display_name_before_parsing(self):+ from plugins.platforms.email.adapter import _extract_email_address+ self.assertEqual(+ _extract_email_address(+ '"Some Very Long Display Name That Exceeds The Line\r\n Limit" <[email protected]>'+ ),+ "[email protected]",+ )++ def test_extract_email_address_unfolds_spoof_before_parsing(self):+ from plugins.platforms.email.adapter import _extract_email_address+ self.assertEqual(+ _extract_email_address(+ '"Victim\r\n <[email protected]>" <[email protected]>'+ ),+ "[email protected]",+ )+def test_strip_html_basic(self):from plugins.platforms.email.adapter import _strip_html@@ -373,6 +405,68 @@ class TestDispatchDefersToGatewayAuthorization(unittest.TestCase):"auth_reason": "dmarc=pass" if authenticated else "no Authentication-Results header"}))return captured+ def test_authenticated_attacker_cannot_impersonate_allowlisted_display_name(self):+ """End-to-end: parse -> authenticate -> dispatch, for the spoofed From.++ The attacker's domain passes DMARC truthfully, so the only thing+ standing between their mail and a MessageEvent carrying the victim's+ identity is that the parser reads the right address.+ """+ import asyncio+ from gateway.config import PlatformConfig+ from plugins.platforms.email.adapter import EmailAdapter++ raw = (b'From: "Victim <[email protected]>" <[email protected]>\r\n'+ b'Authentication-Results: mx.example.com; dmarc=pass header.from=evil.test\r\n'+ b'Subject: run task\r\nMessage-ID: <[email protected]>\r\n\r\nhello')+ with patch.dict(os.environ, {+ "EMAIL_ADDRESS": "[email protected]", "EMAIL_PASSWORD": "secret",+ "EMAIL_IMAP_HOST": "imap.example.com", "EMAIL_SMTP_HOST": "smtp.example.com",+ "EMAIL_ALLOWED_USERS": "[email protected]",+ }):+ adapter = EmailAdapter(PlatformConfig(enabled=True))+ captured = []++ async def capture(event):+ captured.append(event)++ adapter.handle_message = capture+ parsed = adapter._parse_fetched_message(b"1", raw)+ self.assertEqual(parsed["sender_addr"], "[email protected]")+ self.assertTrue(parsed["sender_authenticated"])+ asyncio.run(adapter._dispatch_message(parsed))+ self.assertEqual(captured, [])++ def test_folded_allowlisted_sender_still_dispatches(self):+ """A folded display name must not turn a legitimate sender into a non-address."""+ import asyncio+ from gateway.config import PlatformConfig+ from plugins.platforms.email.adapter import EmailAdapter++ raw = (+ b'From: "Some Very Long Display Name That Exceeds The Line\r\n'+ b' Limit" <[email protected]>\r\n'+ b'Authentication-Results: mx.example.com; dmarc=pass header.from=example.com\r\n'+ b'Subject: hello\r\nMessage-ID: <[email protected]>\r\n\r\nhello'+ )+ with patch.dict(os.environ, {+ "EMAIL_ADDRESS": "[email protected]", "EMAIL_PASSWORD": "secret",+ "EMAIL_IMAP_HOST": "imap.example.com", "EMAIL_SMTP_HOST": "smtp.example.com",+ "EMAIL_ALLOWED_USERS": "[email protected]",+ }):+ adapter = EmailAdapter(PlatformConfig(enabled=True))+ captured = []++ async def capture(event):+ captured.append(event)++ adapter.handle_message = capture+ parsed = adapter._parse_fetched_message(b"2", raw)+ self.assertEqual(parsed["sender_addr"], "[email protected]")+ self.assertTrue(parsed["sender_authenticated"])+ asyncio.run(adapter._dispatch_message(parsed))+ self.assertEqual(len(captured), 1)+def test_mail_the_gateway_admits_or_answers_reaches_it(self):cases = {"pair opt-in": {"extra": {"unauthorized_dm_behavior": "pair"}},@@ -1177,6 +1271,25 @@ class TestSenderAuthentication(unittest.TestCase):)self.assertTrue(ok, reason)+ def test_spoofed_from_is_judged_as_the_attacker_not_the_victim(self):+ """A spoofed From: reaches the allowlist as the ATTACKER, not the victim.++ ``"Victim <[email protected]>" <[email protected]>`` puts the victim's+ address inside the QUOTED display name, so a first-pair regex reads the+ From: as ``[email protected]`` and every downstream check -- the+ allowlist, the pairing decision, the session identity -- is made against+ the victim. parseaddr takes the real addr-spec instead.++ Note ``dmarc=pass`` is accepted for either domain by design: the+ receiving MTA already enforced From alignment, so+ ``_verify_sender_authentication`` trusts that verdict rather than+ re-deriving it. The allowlist is the gate this bug defeated.+ """+ from plugins.platforms.email.adapter import _extract_email_address+ spoofed = '"Victim <[email protected]>" <[email protected]>'+ self.assertEqual(_extract_email_address(spoofed), "[email protected]")+ self.assertNotEqual(_extract_email_address(spoofed), "[email protected]")+def test_dkim_pass_aligned_authenticates(self):ok, reason = self._verify(