fix(email): preserve valid sender header forms
This commit is contained in:
1 parent
0282dbac07
commit
47f77bdbcc
2 files changed
+63
-2
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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é <alice@example.com>",
|
||||
'"张三" <alice@example.com>',
|
||||
"=?utf-8?b?5byg5LiJ?= <alice@example.com>",
|
||||
])
|
||||
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 <mallory@attacker.example>",
|
||||
])
|
||||
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"
|
||||
Reference in new issue
Block a user