Skip to content

Your lightweight open-source personal agent.

fix(email): preserve valid sender header forms

Xubin Ren47f77bdbcc8e
diff --git a/nanobot/channels/email/runtime.py b/nanobot/channels/email/runtime.py
index 4b13fce55..741333633 100644
--- a/nanobot/channels/email/runtime.py
+++ b/nanobot/channels/email/runtime.py
@@ -11,6 +11,7 @@ from contextlib import suppress
from dataclasses import dataclass
from datetime import date
from email import policy
+from email.errors import UndecodableBytesDefect
from email.header import decode_header, make_header
from email.message import EmailMessage
from email.parser import BytesParser
@@ -881,7 +882,10 @@ class EmailChannel(BaseChannel):
from_headers: list[Any] = parsed_msg.get_all("From") or []
if (
len(from_headers) != 1
- or from_headers[0].defects
+ or any(
+ not isinstance(defect, UndecodableBytesDefect)
+ for defect in from_headers[0].defects
+ )
or len(getaddresses([str(from_headers[0])])) != 1
):
return False, False
@@ -1076,6 +1080,16 @@ class EmailChannel(BaseChannel):
if escaped:
return None
item_value = "".join(parsed_value)
+ if index < length and value[index] == "@" and key.casefold() in {"smtp.mailfrom", "header.i"}:
+ # RFC 8601 pvalue permits a quoted mailbox local part
+ # followed by @domain, not just a standalone quoted string.
+ domain_start = index
+ while index < length and not value[index].isspace():
+ index += 1
+ suffix = value[domain_start:index]
+ if re.fullmatch(r"@[a-zA-Z0-9][a-zA-Z0-9.-]*", suffix) is None:
+ return None
+ item_value += suffix
if index < length and not value[index].isspace():
return None
else:
@@ -1133,11 +1147,15 @@ class EmailChannel(BaseChannel):
candidate = value.strip().strip("<>").rstrip(".")
if "@" in candidate:
candidate = candidate.rsplit("@", 1)[1]
- candidate = candidate.casefold().rstrip(".")
+ candidate = candidate.lower().rstrip(".")
if not candidate or any(char.isspace() for char in candidate):
return ""
try:
ascii_domain = candidate.encode("idna").decode("ascii")
+ # Do not merge distinct modern IDNs via IDNA 2003 mappings (e.g.
+ # sharp-s -> ss). Ambiguous forms must use their ASCII A-label.
+ if not candidate.isascii() and ascii_domain.encode("ascii").decode("idna") != candidate:
+ return ""
except UnicodeError:
return ""
if len(ascii_domain) > 253 or any(
diff --git a/nanobot/channels/email/tests/test_authentication_results.py b/nanobot/channels/email/tests/test_authentication_results.py
index facde501d..f0e5e0bc0 100644
--- a/nanobot/channels/email/tests/test_authentication_results.py
+++ b/nanobot/channels/email/tests/test_authentication_results.py
@@ -81,6 +81,8 @@ def test_repeated_from_identity_is_not_authenticated(monkeypatch, extra_headers)
_PASS.replace("spf=pass", 'spf/1 = PASS reason="" (nested (comment))'),
_PASS.replace("header.d=example.com", 'header (comment) . d = "EXAMPLE.COM."'),
_PASS + "; dkim=fail header.d=attacker.example",
+ _PASS.replace("[email protected]", 'smtp.mailfrom="bounce token"@example.com'),
+ _PASS.replace("header.d=example.com", 'header.i="alice smith"@example.com'),
])
def test_legitimate_receiver_results_remain_accepted(monkeypatch, header):
channel, fake = _channel(monkeypatch, [header])
@@ -106,3 +108,44 @@ def test_historical_fetch_fails_closed_without_trust_anchor(monkeypatch):
channel, fake = _channel(monkeypatch, [_PASS], trusted_authserv_ids=[])
assert channel.fetch_messages_between_dates(date(2026, 1, 1), date(2026, 1, 2)) == []
assert not any("(BODY.PEEK[])" in call for call in fake.uid_calls)
+
+
[email protected]("sender", [
+ "José <[email protected]>",
+ '"张三" <[email protected]>',
+ "=?utf-8?b?5byg5LiJ?= <[email protected]>",
+])
+def test_international_display_name_remains_accepted(monkeypatch, sender):
+ raw = ("From: " + sender + "\r\nAuthentication-Results: " + _PASS + "\r\n\r\nHello").encode()
+ fake = _make_fake_imap(raw)
+ monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
+ channel = EmailChannel(_make_config(
+ allow_from=["[email protected]"], verify_spf=True, verify_dkim=True,
+ trusted_authserv_ids=["mx.receiver.example"],
+ ), MessageBus())
+ items, _ = channel._fetch_new_messages()
+ assert len(items) == 1
+ assert items[0]["sender"] == "[email protected]"
+
+
[email protected]("sender", [
+])
+def test_malformed_or_multiple_visible_mailboxes_are_rejected(monkeypatch, sender):
+ raw = ("From: " + sender + "\r\nAuthentication-Results: " + _PASS + "\r\n\r\nHello").encode()
+ fake = _make_fake_imap(raw)
+ monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
+ channel = EmailChannel(_make_config(
+ allow_from=["[email protected]"], verify_spf=True, verify_dkim=True,
+ trusted_authserv_ids=["mx.receiver.example"],
+ ), MessageBus())
+ items, _ = channel._fetch_new_messages()
+ assert items == []
+ assert not any("(BODY.PEEK[])" in call for call in fake.uid_calls)
+
+
+def test_international_domain_normalization_does_not_merge_distinct_domains():
+ assert EmailChannel._address_domain("alice@faß.de") == ""
+ assert EmailChannel._address_domain("[email protected]") == "xn--fa-hia.de"
+ assert EmailChannel._address_domain("alice@bücher.example") == "xn--bcher-kva.example"