From 47f77bdbcc8e74e937b021894d1a29c8f789f54e Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Tue, 15 Sep 2026 15:15:19 +0800 Subject: [PATCH] fix(email): preserve valid sender header forms --- nanobot/channels/email/runtime.py | 22 +++++++++- .../tests/test_authentication_results.py | 43 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) 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("smtp.mailfrom=alice@example.com", '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) + + +@pytest.mark.parametrize("sender", [ + "José ", + '"张三" ', + "=?utf-8?b?5byg5LiJ?= ", +]) +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=["alice@example.com"], 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"] == "alice@example.com" + + +@pytest.mark.parametrize("sender", [ + "alice@example.com, mallory@attacker.example", + "alice@example.com ", +]) +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=["alice@example.com"], 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("alice@xn--fa-hia.de") == "xn--fa-hia.de" + assert EmailChannel._address_domain("alice@bücher.example") == "xn--bcher-kva.example"