fix(email): trust configured authentication results
This commit is contained in:
1 parent
8c4eb2c807
commit
0282dbac07
20 files changed
+805
-29
No files matched your search
@@ -767,6 +767,13 @@ Give nanobot its own email account. It polls **IMAP** for incoming mail and repl
|
|||||||
|
|
||||||
> - `consentGranted` must be `true` to allow mailbox access. This is a safety gate — set `false` to fully disable.
|
> - `consentGranted` must be `true` to allow mailbox access. This is a safety gate — set `false` to fully disable.
|
||||||
> - `allowFrom`: Add your email address. Use `["*"]` to accept emails from anyone.
|
> - `allowFrom`: Add your email address. Use `["*"]` to accept emails from anyone.
|
||||||
|
> - `trustedAuthservIds`: Exact `authserv-id` values added by the receiving mail
|
||||||
|
> service. Required while `verifyDkim` or `verifySpf` is enabled. Gmail normally
|
||||||
|
> uses `mx.google.com`; inspect a received message's raw headers for other services.
|
||||||
|
> The service must prepend one consolidated result and remove inbound headers that
|
||||||
|
> claim the same identity; duplicate trusted results are rejected.
|
||||||
|
> Existing installations must follow the [v0.3.5 upgrade instructions](guides/email-ai-agent.md#upgrading-to-v035)
|
||||||
|
> before re-enabling verified email polling.
|
||||||
> - `smtpUseTls` and `smtpUseSsl` default to `true` / `false` respectively, which is correct for Gmail (port 587 + STARTTLS). No need to set them explicitly.
|
> - `smtpUseTls` and `smtpUseSsl` default to `true` / `false` respectively, which is correct for Gmail (port 587 + STARTTLS). No need to set them explicitly.
|
||||||
> - Set `"autoReplyEnabled": false` if you only want to read/analyze emails without sending automatic replies.
|
> - Set `"autoReplyEnabled": false` if you only want to read/analyze emails without sending automatic replies.
|
||||||
> - `postAction`: Optional post-processing for processed emails: `"delete"` or `"move"` (default `null`).
|
> - `postAction`: Optional post-processing for processed emails: `"delete"` or `"move"` (default `null`).
|
||||||
@@ -794,6 +801,7 @@ Give nanobot its own email account. It polls **IMAP** for incoming mail and repl
|
|||||||
"smtpPassword": "your-app-password",
|
"smtpPassword": "your-app-password",
|
||||||
"fromAddress": "my-nanobot@gmail.com",
|
"fromAddress": "my-nanobot@gmail.com",
|
||||||
"allowFrom": ["your-real-email@gmail.com"],
|
"allowFrom": ["your-real-email@gmail.com"],
|
||||||
|
"trustedAuthservIds": ["mx.google.com"],
|
||||||
"postAction": "move",
|
"postAction": "move",
|
||||||
"postActionMoveMailbox": "[Gmail]/Trash",
|
"postActionMoveMailbox": "[Gmail]/Trash",
|
||||||
"postActionIgnoreSkipped": true,
|
"postActionIgnoreSkipped": true,
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ passwords:
|
|||||||
"smtpPassword": "your-app-password",
|
"smtpPassword": "your-app-password",
|
||||||
"fromAddress": "my-nanobot@gmail.com",
|
"fromAddress": "my-nanobot@gmail.com",
|
||||||
"allowFrom": ["your-real-email@gmail.com"],
|
"allowFrom": ["your-real-email@gmail.com"],
|
||||||
|
"trustedAuthservIds": ["mx.google.com"],
|
||||||
"autoReplyEnabled": true
|
"autoReplyEnabled": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,12 +75,71 @@ gateway running long enough for the polling interval to receive it.
|
|||||||
- Set `consentGranted` to `false` to fully disable mailbox access.
|
- Set `consentGranted` to `false` to fully disable mailbox access.
|
||||||
- Email does not use DM pairing. Keep `allowFrom` narrow; `["*"]` accepts mail
|
- Email does not use DM pairing. Keep `allowFrom` narrow; `["*"]` accepts mail
|
||||||
from anyone.
|
from anyone.
|
||||||
|
- Keep SPF/DKIM verification enabled and set `trustedAuthservIds` to the exact
|
||||||
|
`authserv-id` added by your receiving mail service. For Gmail this is normally
|
||||||
|
`mx.google.com`. The service must prepend one consolidated
|
||||||
|
`Authentication-Results` header and remove inbound headers claiming the same
|
||||||
|
identity. nanobot rejects authenticated email when this trust anchor is missing
|
||||||
|
or appears more than once.
|
||||||
- Use environment variables for mailbox passwords.
|
- Use environment variables for mailbox passwords.
|
||||||
- Enable attachment types only when the agent needs them.
|
- Enable attachment types only when the agent needs them.
|
||||||
|
|
||||||
|
## Upgrading to v0.3.5
|
||||||
|
|
||||||
|
Email authentication now requires an explicit receiving-service trust anchor.
|
||||||
|
This is a security-related configuration change: an existing email channel with
|
||||||
|
`verifySpf` or `verifyDkim` enabled will not start without `trustedAuthservIds`.
|
||||||
|
Other channels, mailbox credentials, stored messages, and `allowFrom` do not need
|
||||||
|
to be migrated. Existing values are not automatically rewritten.
|
||||||
|
|
||||||
|
1. Back up your configuration and temporarily disable the Email channel while
|
||||||
|
configuring the receiver. Do not turn off SPF/DKIM verification as an upgrade
|
||||||
|
workaround.
|
||||||
|
2. Confirm with your receiving mail service or administrator which exact
|
||||||
|
`authserv-id` it adds, and that it strips externally supplied headers claiming
|
||||||
|
that identity. It must provide one consolidated `Authentication-Results`
|
||||||
|
header. A name visible in a received email is not, by itself, proof of trust;
|
||||||
|
do not infer it from your IMAP hostname or copy it from an arbitrary message.
|
||||||
|
3. In Email settings, open **Advanced** and set **Trusted authentication services**,
|
||||||
|
or merge the following fields into `channels.email` in your existing config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"verifySpf": true,
|
||||||
|
"verifyDkim": true,
|
||||||
|
"trustedAuthservIds": ["mx.google.com"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The example is for a receiver using `mx.google.com`; use your confirmed
|
||||||
|
receiver identity instead. JSON uses a list; the WebUI accepts comma-separated
|
||||||
|
values. Wildcards and URLs are not accepted. Multiple configured identities
|
||||||
|
are alternatives, not permission to combine multiple trusted result headers.
|
||||||
|
4. Check the IMAP/SMTP connection, re-enable Email, and restart the gateway after
|
||||||
|
editing a configuration file. Send one ordinary message from an allowed
|
||||||
|
address and confirm receipt and reply. A successful connection check verifies
|
||||||
|
credentials and configuration, not your mail service's header-stripping policy.
|
||||||
|
|
||||||
|
Each enabled verification method must pass and identify the visible sender's
|
||||||
|
domain, or a parent/subdomain of it. DKIM uses `header.d` when present, otherwise
|
||||||
|
the domain of the receiver-reported `header.i`. This is not a full DMARC policy
|
||||||
|
implementation, and domain authentication does not independently authenticate
|
||||||
|
the mailbox local part. Forwarders, mailing lists, or receivers that emit separate
|
||||||
|
SPF and DKIM result headers may need mail-service changes. Keep Email disabled
|
||||||
|
if the receiver cannot meet the trust contract.
|
||||||
|
|
||||||
|
Authentication failures remain skipped messages. Keep the default
|
||||||
|
`postActionIgnoreSkipped: true` while checking the migration; setting it to
|
||||||
|
`false` allows your configured move/delete action to affect skipped mail too.
|
||||||
|
If the migration cannot be completed, disable Email rather than reverting to an
|
||||||
|
older authentication policy.
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
- If login fails, confirm IMAP/SMTP access and app-password setup.
|
- If login fails, confirm IMAP/SMTP access and app-password setup.
|
||||||
|
- If Email will not start and reports `trusted_authserv_ids` as missing, complete
|
||||||
|
the upgrade steps above. A configured receiver still needs to emit compatible,
|
||||||
|
aligned authentication results for each enabled verification method.
|
||||||
- If the bot reads but does not reply, check `autoReplyEnabled`, SMTP settings,
|
- If the bot reads but does not reply, check `autoReplyEnabled`, SMTP settings,
|
||||||
and allowed sender addresses.
|
and allowed sender addresses.
|
||||||
- If attachments are missing, review `allowedAttachmentTypes`, size limits, and
|
- If attachments are missing, review `allowedAttachmentTypes`, size limits, and
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ SETUP_SPEC = ChannelSetupSpec(
|
|||||||
"allowedAttachmentTypes": field("list"),
|
"allowedAttachmentTypes": field("list"),
|
||||||
"maxAttachmentSize": field("int", default=2_000_000),
|
"maxAttachmentSize": field("int", default=2_000_000),
|
||||||
"maxAttachmentsPerEmail": field("int", default=5),
|
"maxAttachmentsPerEmail": field("int", default=5),
|
||||||
|
"trustedAuthservIds": field("list"),
|
||||||
},
|
},
|
||||||
required=required_fields(
|
required=required_fields(
|
||||||
"consentGranted",
|
"consentGranted",
|
||||||
|
|||||||
@@ -14,13 +14,13 @@ from email import policy
|
|||||||
from email.header import decode_header, make_header
|
from email.header import decode_header, make_header
|
||||||
from email.message import EmailMessage
|
from email.message import EmailMessage
|
||||||
from email.parser import BytesParser
|
from email.parser import BytesParser
|
||||||
from email.utils import parseaddr
|
from email.utils import getaddresses, parseaddr
|
||||||
from fnmatch import fnmatch
|
from fnmatch import fnmatch
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Literal, cast
|
from typing import Any, Literal, cast
|
||||||
|
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
from pydantic import Field
|
from pydantic import Field, field_validator
|
||||||
|
|
||||||
from nanobot.bus.events import OutboundMessage
|
from nanobot.bus.events import OutboundMessage
|
||||||
from nanobot.bus.outbound_events import ProgressEvent
|
from nanobot.bus.outbound_events import ProgressEvent
|
||||||
@@ -66,6 +66,19 @@ class EmailConfig(Base):
|
|||||||
# Email authentication verification (anti-spoofing)
|
# Email authentication verification (anti-spoofing)
|
||||||
verify_dkim: bool = True # Require Authentication-Results with dkim=pass
|
verify_dkim: bool = True # Require Authentication-Results with dkim=pass
|
||||||
verify_spf: bool = True # Require Authentication-Results with spf=pass
|
verify_spf: bool = True # Require Authentication-Results with spf=pass
|
||||||
|
trusted_authserv_ids: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
@field_validator("trusted_authserv_ids")
|
||||||
|
@classmethod
|
||||||
|
def validate_trusted_authserv_ids(cls, values: list[str]) -> list[str]:
|
||||||
|
normalized: list[str] = []
|
||||||
|
for value in values:
|
||||||
|
authserv_id = value.strip().casefold().rstrip(".")
|
||||||
|
if not authserv_id or re.fullmatch(r"[a-z0-9][a-z0-9._:-]*", authserv_id) is None:
|
||||||
|
raise ValueError(f"invalid trusted Authentication-Results authserv-id: {value!r}")
|
||||||
|
if authserv_id not in normalized:
|
||||||
|
normalized.append(authserv_id)
|
||||||
|
return normalized
|
||||||
|
|
||||||
# Attachment handling — set allowed types to enable (e.g. ["application/pdf", "image/*"], or ["*"] for all)
|
# Attachment handling — set allowed types to enable (e.g. ["application/pdf", "image/*"], or ["*"] for all)
|
||||||
allowed_attachment_types: list[str] = Field(default_factory=list)
|
allowed_attachment_types: list[str] = Field(default_factory=list)
|
||||||
@@ -80,6 +93,13 @@ class _ServerFeatures:
|
|||||||
uid_store: bool | None = None
|
uid_store: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class _AuthenticationResult:
|
||||||
|
method: str
|
||||||
|
result: str
|
||||||
|
properties: tuple[tuple[str, str], ...]
|
||||||
|
|
||||||
|
|
||||||
class EmailChannel(BaseChannel):
|
class EmailChannel(BaseChannel):
|
||||||
"""
|
"""
|
||||||
Email channel.
|
Email channel.
|
||||||
@@ -334,6 +354,9 @@ class EmailChannel(BaseChannel):
|
|||||||
if not self.config.smtp_password:
|
if not self.config.smtp_password:
|
||||||
missing.append("smtp_password")
|
missing.append("smtp_password")
|
||||||
|
|
||||||
|
if (self.config.verify_spf or self.config.verify_dkim) and not self.config.trusted_authserv_ids:
|
||||||
|
missing.append("trusted_authserv_ids")
|
||||||
|
|
||||||
if self.config.post_action == "move" and not (self.config.post_action_move_mailbox or "").strip():
|
if self.config.post_action == "move" and not (self.config.post_action_move_mailbox or "").strip():
|
||||||
missing.append("post_action_move_mailbox")
|
missing.append("post_action_move_mailbox")
|
||||||
|
|
||||||
@@ -486,11 +509,11 @@ class EmailChannel(BaseChannel):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# --- Anti-spoofing: verify Authentication-Results ---
|
# --- Anti-spoofing: verify Authentication-Results ---
|
||||||
spf_pass, dkim_pass = self._check_authentication_results(parsed)
|
spf_pass, dkim_pass = self._check_authentication_results(parsed, sender)
|
||||||
if self.config.verify_spf and not spf_pass:
|
if self.config.verify_spf and not spf_pass:
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
"From {} rejected: SPF verification failed "
|
"From {} rejected: SPF verification failed "
|
||||||
"(no 'spf=pass' in Authentication-Results header)",
|
"(no aligned 'spf=pass' from a trusted Authentication-Results header)",
|
||||||
sender,
|
sender,
|
||||||
)
|
)
|
||||||
self._remember_processed_uid(uid, dedupe, cycle_uids)
|
self._remember_processed_uid(uid, dedupe, cycle_uids)
|
||||||
@@ -499,7 +522,7 @@ class EmailChannel(BaseChannel):
|
|||||||
if self.config.verify_dkim and not dkim_pass:
|
if self.config.verify_dkim and not dkim_pass:
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
"From {} rejected: DKIM verification failed "
|
"From {} rejected: DKIM verification failed "
|
||||||
"(no 'dkim=pass' in Authentication-Results header)",
|
"(no aligned 'dkim=pass' from a trusted Authentication-Results header)",
|
||||||
sender,
|
sender,
|
||||||
)
|
)
|
||||||
self._remember_processed_uid(uid, dedupe, cycle_uids)
|
self._remember_processed_uid(uid, dedupe, cycle_uids)
|
||||||
@@ -853,23 +876,277 @@ class EmailChannel(BaseChannel):
|
|||||||
return cls._html_to_text(payload).strip()
|
return cls._html_to_text(payload).strip()
|
||||||
return payload.strip()
|
return payload.strip()
|
||||||
|
|
||||||
@staticmethod
|
def _check_authentication_results(self, parsed_msg: Any, sender: str) -> tuple[bool, bool]:
|
||||||
def _check_authentication_results(parsed_msg: Any) -> tuple[bool, bool]:
|
"""Return aligned SPF/DKIM verdicts from one trusted producer header."""
|
||||||
"""Parse Authentication-Results headers for SPF and DKIM verdicts.
|
from_headers: list[Any] = parsed_msg.get_all("From") or []
|
||||||
|
if (
|
||||||
|
len(from_headers) != 1
|
||||||
|
or from_headers[0].defects
|
||||||
|
or len(getaddresses([str(from_headers[0])])) != 1
|
||||||
|
):
|
||||||
|
return False, False
|
||||||
|
sender_domain = self._address_domain(sender)
|
||||||
|
if not sender_domain:
|
||||||
|
return False, False
|
||||||
|
|
||||||
Returns:
|
trusted_ids = set(self.config.trusted_authserv_ids)
|
||||||
A tuple of (spf_pass, dkim_pass) booleans.
|
if not trusted_ids:
|
||||||
"""
|
return False, False
|
||||||
spf_pass = False
|
|
||||||
dkim_pass = False
|
trusted_headers: list[tuple[_AuthenticationResult, ...]] = []
|
||||||
for ar_header in cast(list[Any], parsed_msg.get_all("Authentication-Results") or []):
|
# Authentication trace fields are wire syntax, not display text. In
|
||||||
ar_lower = str(ar_header).lower()
|
# particular, RFC 2047 encoded words must not turn into trusted evidence.
|
||||||
if re.search(r"\bspf\s*=\s*pass\b", ar_lower):
|
for name, raw_header in parsed_msg.raw_items():
|
||||||
spf_pass = True
|
if name.casefold() != "authentication-results":
|
||||||
if re.search(r"\bdkim\s*=\s*pass\b", ar_lower):
|
continue
|
||||||
dkim_pass = True
|
parsed_header = self._parse_authentication_results_header(raw_header)
|
||||||
|
if parsed_header is None:
|
||||||
|
continue
|
||||||
|
authserv_id, header_results = parsed_header
|
||||||
|
if authserv_id in trusted_ids:
|
||||||
|
trusted_headers.append(header_results)
|
||||||
|
|
||||||
|
# The configured trust contract requires one consolidated header from
|
||||||
|
# the receiving service. Reject duplicates so a preserved attacker header
|
||||||
|
# cannot be combined with, or ordered ahead of, the genuine result.
|
||||||
|
if len(trusted_headers) != 1:
|
||||||
|
return False, False
|
||||||
|
results = trusted_headers[0]
|
||||||
|
|
||||||
|
spf_pass = self._has_aligned_result(
|
||||||
|
results,
|
||||||
|
method="spf",
|
||||||
|
property_name="smtp.mailfrom",
|
||||||
|
sender_domain=sender_domain,
|
||||||
|
)
|
||||||
|
dkim_pass = self._has_aligned_result(
|
||||||
|
results,
|
||||||
|
method="dkim",
|
||||||
|
property_name="header.d",
|
||||||
|
sender_domain=sender_domain,
|
||||||
|
)
|
||||||
return spf_pass, dkim_pass
|
return spf_pass, dkim_pass
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _parse_authentication_results_header(
|
||||||
|
cls,
|
||||||
|
value: str,
|
||||||
|
) -> tuple[str, tuple[_AuthenticationResult, ...]] | None:
|
||||||
|
parts = cls._split_authentication_results(value)
|
||||||
|
if not parts:
|
||||||
|
return None
|
||||||
|
|
||||||
|
authserv_tokens = parts[0].split()
|
||||||
|
if not authserv_tokens:
|
||||||
|
return None
|
||||||
|
authserv_id = authserv_tokens[0].strip('"').casefold().rstrip(".")
|
||||||
|
if re.fullmatch(r"[a-z0-9][a-z0-9._:-]*", authserv_id) is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Keep the producer even when its result is absent or malformed. A
|
||||||
|
# trusted `none`/invalid header must still count against duplicate claims.
|
||||||
|
no_results: tuple[str, tuple[_AuthenticationResult, ...]] = (authserv_id, ())
|
||||||
|
if (
|
||||||
|
len(parts) < 2
|
||||||
|
or re.fullmatch(r'(?:"[a-zA-Z0-9][a-zA-Z0-9._:-]*"|[a-zA-Z0-9][a-zA-Z0-9._:-]*)(?:\s+1)?', parts[0]) is None
|
||||||
|
):
|
||||||
|
return no_results
|
||||||
|
|
||||||
|
results: list[_AuthenticationResult] = []
|
||||||
|
for part in parts[1:]:
|
||||||
|
assignments = cls._parse_auth_result_assignments(part)
|
||||||
|
if not assignments:
|
||||||
|
return no_results
|
||||||
|
method_key, result = assignments[0]
|
||||||
|
method = method_key.casefold().partition("/")[0]
|
||||||
|
if not method or "." in method:
|
||||||
|
return no_results
|
||||||
|
if re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_-]*", result) is None:
|
||||||
|
return no_results
|
||||||
|
keys = [key.casefold() for key, _ in assignments[1:]]
|
||||||
|
if len(keys) != len(set(keys)) or any(
|
||||||
|
"." not in key and key != "reason" for key in keys
|
||||||
|
):
|
||||||
|
return no_results
|
||||||
|
properties = tuple(
|
||||||
|
(key.casefold(), property_value)
|
||||||
|
for key, property_value in assignments[1:]
|
||||||
|
if "." in key
|
||||||
|
)
|
||||||
|
results.append(
|
||||||
|
_AuthenticationResult(
|
||||||
|
method=method,
|
||||||
|
result=result.casefold(),
|
||||||
|
properties=properties,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return authserv_id, tuple(results)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _split_authentication_results(value: str) -> list[str]:
|
||||||
|
"""Split RFC 8601 fields on top-level semicolons and discard comments."""
|
||||||
|
parts: list[str] = []
|
||||||
|
current: list[str] = []
|
||||||
|
in_quote = False
|
||||||
|
comment_depth = 0
|
||||||
|
escaped = False
|
||||||
|
|
||||||
|
for char in value:
|
||||||
|
if escaped:
|
||||||
|
if comment_depth == 0:
|
||||||
|
current.append(char)
|
||||||
|
escaped = False
|
||||||
|
continue
|
||||||
|
if char == "\\" and (in_quote or comment_depth > 0):
|
||||||
|
if comment_depth == 0:
|
||||||
|
current.append(char)
|
||||||
|
escaped = True
|
||||||
|
continue
|
||||||
|
if comment_depth > 0:
|
||||||
|
if char == "(":
|
||||||
|
comment_depth += 1
|
||||||
|
elif char == ")":
|
||||||
|
comment_depth -= 1
|
||||||
|
continue
|
||||||
|
if in_quote:
|
||||||
|
current.append(char)
|
||||||
|
if char == '"':
|
||||||
|
in_quote = False
|
||||||
|
continue
|
||||||
|
if char == '"':
|
||||||
|
in_quote = True
|
||||||
|
current.append(char)
|
||||||
|
elif char == "(":
|
||||||
|
comment_depth = 1
|
||||||
|
current.append(" ")
|
||||||
|
elif char == ";":
|
||||||
|
parts.append("".join(current).strip())
|
||||||
|
current = []
|
||||||
|
else:
|
||||||
|
current.append(char)
|
||||||
|
|
||||||
|
if escaped or in_quote or comment_depth > 0:
|
||||||
|
return parts + [""]
|
||||||
|
parts.append("".join(current).strip())
|
||||||
|
return parts
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_auth_result_assignments(value: str) -> list[tuple[str, str]] | None:
|
||||||
|
assignments: list[tuple[str, str]] = []
|
||||||
|
index = 0
|
||||||
|
length = len(value)
|
||||||
|
|
||||||
|
while index < length:
|
||||||
|
while index < length and value[index].isspace():
|
||||||
|
index += 1
|
||||||
|
if index >= length:
|
||||||
|
break
|
||||||
|
|
||||||
|
key_match = re.match(
|
||||||
|
r"([a-zA-Z][a-zA-Z0-9_-]*(?:\s*(?:\.\s*[a-zA-Z][a-zA-Z0-9_-]*|/\s*[0-9]+))?)\s*=",
|
||||||
|
value[index:],
|
||||||
|
)
|
||||||
|
if key_match is None:
|
||||||
|
return None
|
||||||
|
key = re.sub(r"\s+", "", key_match.group(1))
|
||||||
|
index += key_match.end()
|
||||||
|
while index < length and value[index].isspace():
|
||||||
|
index += 1
|
||||||
|
if index >= length:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if value[index] == '"':
|
||||||
|
index += 1
|
||||||
|
parsed_value: list[str] = []
|
||||||
|
escaped = False
|
||||||
|
while index < length:
|
||||||
|
char = value[index]
|
||||||
|
index += 1
|
||||||
|
if escaped:
|
||||||
|
parsed_value.append(char)
|
||||||
|
escaped = False
|
||||||
|
elif char == "\\":
|
||||||
|
escaped = True
|
||||||
|
elif char == '"':
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
parsed_value.append(char)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
if escaped:
|
||||||
|
return None
|
||||||
|
item_value = "".join(parsed_value)
|
||||||
|
if index < length and not value[index].isspace():
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
value_start = index
|
||||||
|
while index < length and not value[index].isspace():
|
||||||
|
index += 1
|
||||||
|
item_value = value[value_start:index]
|
||||||
|
|
||||||
|
if not item_value and key.casefold() != "reason":
|
||||||
|
return None
|
||||||
|
assignments.append((key, item_value))
|
||||||
|
|
||||||
|
return assignments or None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _has_aligned_result(
|
||||||
|
cls,
|
||||||
|
results: tuple[_AuthenticationResult, ...],
|
||||||
|
*,
|
||||||
|
method: str,
|
||||||
|
property_name: str,
|
||||||
|
sender_domain: str,
|
||||||
|
) -> bool:
|
||||||
|
for result in results:
|
||||||
|
if result.method != method or result.result != "pass":
|
||||||
|
continue
|
||||||
|
properties = dict(result.properties)
|
||||||
|
value = properties.get(property_name, "")
|
||||||
|
if method == "dkim":
|
||||||
|
# AUID (header.i) is a standard receiver-reported DKIM identity.
|
||||||
|
# Prefer the signing domain when supplied; never use AUID to
|
||||||
|
# override an unaligned or malformed header.d.
|
||||||
|
if property_name not in properties:
|
||||||
|
value = properties.get("header.i", "")
|
||||||
|
if "@" not in value:
|
||||||
|
continue
|
||||||
|
elif any(char in value for char in "@<>"):
|
||||||
|
continue
|
||||||
|
if cls._domains_align(cls._address_domain(value), sender_domain):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _domains_align(authenticated_domain: str, sender_domain: str) -> bool:
|
||||||
|
if not authenticated_domain or not sender_domain:
|
||||||
|
return False
|
||||||
|
return (
|
||||||
|
authenticated_domain == sender_domain
|
||||||
|
or authenticated_domain.endswith(f".{sender_domain}")
|
||||||
|
or sender_domain.endswith(f".{authenticated_domain}")
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _address_domain(value: str) -> str:
|
||||||
|
candidate = value.strip().strip("<>").rstrip(".")
|
||||||
|
if "@" in candidate:
|
||||||
|
candidate = candidate.rsplit("@", 1)[1]
|
||||||
|
candidate = candidate.casefold().rstrip(".")
|
||||||
|
if not candidate or any(char.isspace() for char in candidate):
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
ascii_domain = candidate.encode("idna").decode("ascii")
|
||||||
|
except UnicodeError:
|
||||||
|
return ""
|
||||||
|
if len(ascii_domain) > 253 or any(
|
||||||
|
re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) is None
|
||||||
|
for label in ascii_domain.split(".")
|
||||||
|
):
|
||||||
|
return ""
|
||||||
|
return ascii_domain
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _extract_attachments(
|
def _extract_attachments(
|
||||||
cls,
|
cls,
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Ingress regressions for the receiving-service authentication boundary."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.bus.queue import MessageBus
|
||||||
|
from nanobot.channels.email.runtime import EmailChannel
|
||||||
|
from nanobot.channels.email.tests.test_email_channel import (
|
||||||
|
_make_config,
|
||||||
|
_make_fake_imap,
|
||||||
|
_make_raw_email,
|
||||||
|
)
|
||||||
|
|
||||||
|
_PASS = "mx.receiver.example; spf=pass smtp.mailfrom=alice@example.com; dkim=pass header.d=example.com"
|
||||||
|
|
||||||
|
|
||||||
|
def _channel(monkeypatch, headers: list[str], *, extra_headers: bytes = b"", **config):
|
||||||
|
# Insert wire bytes directly: EmailMessage may otherwise refold/decode them.
|
||||||
|
raw = b"".join(b"Authentication-Results: " + value.encode() + b"\r\n" for value in headers)
|
||||||
|
raw += extra_headers + _make_raw_email()
|
||||||
|
fake = _make_fake_imap(raw, uid=b"1")
|
||||||
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda *_: fake)
|
||||||
|
values = dict(
|
||||||
|
allow_from=["alice@example.com"], verify_spf=True, verify_dkim=True,
|
||||||
|
trusted_authserv_ids=["mx.receiver.example"],
|
||||||
|
)
|
||||||
|
values.update(config)
|
||||||
|
return EmailChannel(_make_config(**values), MessageBus()), fake
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("historical", [False, True])
|
||||||
|
@pytest.mark.parametrize("headers", [
|
||||||
|
[_PASS.replace("mx.receiver.example", "mx.attacker.example")],
|
||||||
|
["mx.receiver.example; none", _PASS],
|
||||||
|
[_PASS, "mx.receiver.example; none"],
|
||||||
|
[_PASS, "mx.receiver.example; spf=fail (unterminated"],
|
||||||
|
["mx.receiver.example; dkim=fail reason=\"unterminated", _PASS],
|
||||||
|
["mx.receiver.example; malformed", _PASS],
|
||||||
|
["mx.receiver.example", _PASS],
|
||||||
|
[_PASS.replace("smtp.mailfrom=alice@example.com", "smtp.mailfrom=attacker.example smtp.mailfrom=example.com")],
|
||||||
|
[_PASS + " header.d=attacker.example"],
|
||||||
|
["=?utf-8?b?" + base64.b64encode(_PASS.encode()).decode() + "?="],
|
||||||
|
[_PASS.replace("mx.receiver.example", "=?utf-8?q?mx.receiver.example?=")],
|
||||||
|
["mx.receiver.example; spf=fail (spf=pass); dkim=fail reason=\"dkim=pass\""],
|
||||||
|
[_PASS.replace("spf=pass", "spf=pass reason=\"comment\"smtp.mailfrom=attacker.example")],
|
||||||
|
[_PASS.replace("header.d=example.com", "header.d=attacker.example header.i=@example.com")],
|
||||||
|
[_PASS.replace("header.d=example.com", "header.d=attacker@example.com")],
|
||||||
|
])
|
||||||
|
def test_untrusted_or_ambiguous_results_never_fetch_body(monkeypatch, headers, historical):
|
||||||
|
channel, fake = _channel(monkeypatch, headers)
|
||||||
|
if historical:
|
||||||
|
items = channel.fetch_messages_between_dates(date(2026, 1, 1), date(2026, 1, 2))
|
||||||
|
else:
|
||||||
|
items, skipped = channel._fetch_new_messages()
|
||||||
|
assert skipped == {"1"}
|
||||||
|
assert items == []
|
||||||
|
assert [call for call in fake.uid_calls if call[0] == "FETCH"] == [
|
||||||
|
("FETCH", "1", "(BODY.PEEK[HEADER])"),
|
||||||
|
]
|
||||||
|
assert not any(call[0] == "STORE" for call in fake.uid_calls)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("extra_headers", [
|
||||||
|
b"From: alice@example.com\r\n",
|
||||||
|
b"From: Mallory <mallory@attacker.example>\r\n",
|
||||||
|
])
|
||||||
|
def test_repeated_from_identity_is_not_authenticated(monkeypatch, extra_headers):
|
||||||
|
channel, fake = _channel(monkeypatch, [_PASS], extra_headers=extra_headers)
|
||||||
|
items, _ = channel._fetch_new_messages()
|
||||||
|
assert items == []
|
||||||
|
assert not any("(BODY.PEEK[])" in call for call in fake.uid_calls)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("header", [
|
||||||
|
_PASS,
|
||||||
|
_PASS.replace("header.d=example.com", "header.i=@example.com header.s=selector header.b=abc"),
|
||||||
|
_PASS.replace("mx.receiver.example", '"MX.Receiver.Example." 1'),
|
||||||
|
_PASS.replace("; ", ";\r\n\t"),
|
||||||
|
_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",
|
||||||
|
])
|
||||||
|
def test_legitimate_receiver_results_remain_accepted(monkeypatch, header):
|
||||||
|
channel, fake = _channel(monkeypatch, [header])
|
||||||
|
items, skipped = channel._fetch_new_messages()
|
||||||
|
assert len(items) == 1
|
||||||
|
assert items[0]["sender"] == "alice@example.com"
|
||||||
|
assert skipped == set()
|
||||||
|
assert any("(BODY.PEEK[])" in call for call in fake.uid_calls)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("spf", "dkim", "headers"), [
|
||||||
|
(False, False, []),
|
||||||
|
(True, False, ["mx.receiver.example; spf=pass smtp.mailfrom=example.com"]),
|
||||||
|
(False, True, ["mx.receiver.example; dkim=pass header.i=@example.com"]),
|
||||||
|
])
|
||||||
|
def test_explicit_verification_modes_preserved(monkeypatch, spf, dkim, headers):
|
||||||
|
channel, _ = _channel(monkeypatch, headers, verify_spf=spf, verify_dkim=dkim)
|
||||||
|
items, _ = channel._fetch_new_messages()
|
||||||
|
assert len(items) == 1
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
@@ -40,15 +40,18 @@ def _make_raw_email(
|
|||||||
from_addr: str = "alice@example.com",
|
from_addr: str = "alice@example.com",
|
||||||
subject: str = "Hello",
|
subject: str = "Hello",
|
||||||
body: str = "This is the body.",
|
body: str = "This is the body.",
|
||||||
auth_results: str | None = None,
|
auth_results: str | list[str] | None = None,
|
||||||
) -> bytes:
|
) -> bytes:
|
||||||
msg = EmailMessage()
|
msg = EmailMessage()
|
||||||
msg["From"] = from_addr
|
msg["From"] = from_addr
|
||||||
msg["To"] = "bot@example.com"
|
msg["To"] = "bot@example.com"
|
||||||
msg["Subject"] = subject
|
msg["Subject"] = subject
|
||||||
msg["Message-ID"] = "<m1@example.com>"
|
msg["Message-ID"] = "<m1@example.com>"
|
||||||
if auth_results:
|
if isinstance(auth_results, str):
|
||||||
msg["Authentication-Results"] = auth_results
|
msg["Authentication-Results"] = auth_results
|
||||||
|
elif auth_results:
|
||||||
|
for auth_result in auth_results:
|
||||||
|
msg["Authentication-Results"] = auth_result
|
||||||
msg.set_content(body)
|
msg.set_content(body)
|
||||||
return msg.as_bytes()
|
return msg.as_bytes()
|
||||||
|
|
||||||
@@ -680,6 +683,24 @@ def test_validate_config_requires_move_mailbox_for_move_post_action() -> None:
|
|||||||
assert channel._validate_config() is False
|
assert channel._validate_config() is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_config_requires_trusted_authserv_ids_when_verification_enabled() -> None:
|
||||||
|
channel = EmailChannel(
|
||||||
|
_make_config(verify_dkim=True, verify_spf=True, trusted_authserv_ids=[]),
|
||||||
|
MessageBus(),
|
||||||
|
)
|
||||||
|
assert channel._validate_config() is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_email_config_normalizes_trusted_authserv_ids() -> None:
|
||||||
|
config = _make_config(
|
||||||
|
trusted_authserv_ids=[" MX.Google.COM. ", "mx.google.com"],
|
||||||
|
)
|
||||||
|
assert config.trusted_authserv_ids == ["mx.google.com"]
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="invalid trusted Authentication-Results authserv-id"):
|
||||||
|
_make_config(trusted_authserv_ids=["*"])
|
||||||
|
|
||||||
|
|
||||||
def test_extract_text_body_falls_back_to_html() -> None:
|
def test_extract_text_body_falls_back_to_html() -> None:
|
||||||
msg = EmailMessage()
|
msg = EmailMessage()
|
||||||
msg["From"] = "alice@example.com"
|
msg["From"] = "alice@example.com"
|
||||||
@@ -1035,7 +1056,11 @@ def test_spoofed_email_rejected_when_verify_enabled(monkeypatch) -> None:
|
|||||||
fake = _make_fake_imap(raw)
|
fake = _make_fake_imap(raw)
|
||||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
cfg = _make_config(verify_dkim=True, verify_spf=True)
|
cfg = _make_config(
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.example.com"],
|
||||||
|
)
|
||||||
channel = EmailChannel(cfg, MessageBus())
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
items, _ = channel._fetch_new_messages()
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
@@ -1052,7 +1077,11 @@ def test_email_with_valid_auth_results_accepted(monkeypatch) -> None:
|
|||||||
fake = _make_fake_imap(raw)
|
fake = _make_fake_imap(raw)
|
||||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
cfg = _make_config(verify_dkim=True, verify_spf=True)
|
cfg = _make_config(
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.example.com"],
|
||||||
|
)
|
||||||
channel = EmailChannel(cfg, MessageBus())
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
items, _ = channel._fetch_new_messages()
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
@@ -1071,13 +1100,144 @@ def test_email_with_partial_auth_rejected(monkeypatch) -> None:
|
|||||||
fake = _make_fake_imap(raw)
|
fake = _make_fake_imap(raw)
|
||||||
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
cfg = _make_config(verify_dkim=True, verify_spf=True)
|
cfg = _make_config(
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.example.com"],
|
||||||
|
)
|
||||||
channel = EmailChannel(cfg, MessageBus())
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
items, _ = channel._fetch_new_messages()
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
assert len(items) == 0, "Email with dkim=fail should be rejected"
|
assert len(items) == 0, "Email with dkim=fail should be rejected"
|
||||||
|
|
||||||
|
|
||||||
|
def test_forged_authentication_results_cannot_override_trusted_failure(monkeypatch) -> None:
|
||||||
|
raw = _make_raw_email(
|
||||||
|
from_addr="owner@example.com",
|
||||||
|
subject="Forged authentication",
|
||||||
|
body="Malicious payload",
|
||||||
|
auth_results=[
|
||||||
|
"mx.receiver.example; spf=fail smtp.mailfrom=attacker.example; "
|
||||||
|
"dkim=fail header.d=attacker.example",
|
||||||
|
"mx.attacker.example; spf=pass smtp.mailfrom=owner@example.com; "
|
||||||
|
"dkim=pass header.d=example.com",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
fake = _make_fake_imap(raw)
|
||||||
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
|
cfg = _make_config(
|
||||||
|
allow_from=["owner@example.com"],
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.receiver.example"],
|
||||||
|
)
|
||||||
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
|
assert items == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_header_with_trusted_id_is_rejected(monkeypatch) -> None:
|
||||||
|
raw = _make_raw_email(
|
||||||
|
from_addr="owner@example.com",
|
||||||
|
subject="Forged trusted producer",
|
||||||
|
body="Malicious payload",
|
||||||
|
auth_results=[
|
||||||
|
"mx.receiver.example; spf=fail smtp.mailfrom=attacker.example; "
|
||||||
|
"dkim=fail header.d=attacker.example",
|
||||||
|
"mx.receiver.example; spf=pass smtp.mailfrom=owner@example.com; "
|
||||||
|
"dkim=pass header.d=example.com",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
fake = _make_fake_imap(raw)
|
||||||
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
|
cfg = _make_config(
|
||||||
|
allow_from=["owner@example.com"],
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.receiver.example"],
|
||||||
|
)
|
||||||
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
|
assert items == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_pass_text_in_authentication_result_comment_is_not_a_verdict() -> None:
|
||||||
|
from email import policy
|
||||||
|
from email.parser import BytesParser
|
||||||
|
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = "owner@example.com"
|
||||||
|
msg["Authentication-Results"] = (
|
||||||
|
"mx.receiver.example; spf=fail (spf=pass smtp.mailfrom=owner@example.com) "
|
||||||
|
"smtp.mailfrom=attacker.example; "
|
||||||
|
"dkim=fail reason=\"dkim=pass header.d=example.com\" header.d=attacker.example"
|
||||||
|
)
|
||||||
|
msg.set_content("malicious")
|
||||||
|
parsed = BytesParser(policy=policy.default).parsebytes(msg.as_bytes())
|
||||||
|
channel = EmailChannel(
|
||||||
|
_make_config(trusted_authserv_ids=["mx.receiver.example"]),
|
||||||
|
MessageBus(),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert channel._check_authentication_results(parsed, "owner@example.com") == (False, False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_trusted_pass_for_unrelated_domain_is_rejected(monkeypatch) -> None:
|
||||||
|
raw = _make_raw_email(
|
||||||
|
from_addr="owner@example.com",
|
||||||
|
subject="Unaligned authentication",
|
||||||
|
body="Malicious payload",
|
||||||
|
auth_results=(
|
||||||
|
"mx.receiver.example; spf=pass smtp.mailfrom=attacker.example; "
|
||||||
|
"dkim=pass header.d=attacker.example; "
|
||||||
|
"dmarc=fail header.from=example.com"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
fake = _make_fake_imap(raw)
|
||||||
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
|
cfg = _make_config(
|
||||||
|
allow_from=["owner@example.com"],
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.receiver.example"],
|
||||||
|
)
|
||||||
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
|
assert items == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_trusted_relaxed_domain_alignment_accepts_legitimate_subdomain_auth(monkeypatch) -> None:
|
||||||
|
raw = _make_raw_email(
|
||||||
|
from_addr="alice@example.com",
|
||||||
|
subject="Aligned authentication",
|
||||||
|
body="Legitimate payload",
|
||||||
|
auth_results=(
|
||||||
|
"mx.receiver.example; spf=pass smtp.mailfrom=bounce.mail.example.com; "
|
||||||
|
"dkim=pass header.d=mail.example.com"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
fake = _make_fake_imap(raw)
|
||||||
|
monkeypatch.setattr("nanobot.channels.email.runtime.imaplib.IMAP4_SSL", lambda _h, _p: fake)
|
||||||
|
|
||||||
|
cfg = _make_config(
|
||||||
|
allow_from=["alice@example.com"],
|
||||||
|
verify_dkim=True,
|
||||||
|
verify_spf=True,
|
||||||
|
trusted_authserv_ids=["mx.receiver.example"],
|
||||||
|
)
|
||||||
|
channel = EmailChannel(cfg, MessageBus())
|
||||||
|
items, _ = channel._fetch_new_messages()
|
||||||
|
|
||||||
|
assert len(items) == 1
|
||||||
|
assert items[0]["sender"] == "alice@example.com"
|
||||||
|
|
||||||
|
|
||||||
def test_backward_compat_verify_disabled(monkeypatch) -> None:
|
def test_backward_compat_verify_disabled(monkeypatch) -> None:
|
||||||
"""When verify_dkim=False and verify_spf=False, emails without auth headers are accepted."""
|
"""When verify_dkim=False and verify_spf=False, emails without auth headers are accepted."""
|
||||||
raw = _make_raw_email(subject="NoAuth", body="No auth headers present")
|
raw = _make_raw_email(subject="NoAuth", body="No auth headers present")
|
||||||
@@ -1108,7 +1268,7 @@ def test_email_content_tagged_with_email_context(monkeypatch) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_check_authentication_results_method() -> None:
|
def test_check_authentication_results_method() -> None:
|
||||||
"""Unit test for the _check_authentication_results static method."""
|
"""Unit test for trusted, aligned Authentication-Results parsing."""
|
||||||
from email import policy
|
from email import policy
|
||||||
from email.parser import BytesParser
|
from email.parser import BytesParser
|
||||||
|
|
||||||
@@ -1117,7 +1277,11 @@ def test_check_authentication_results_method() -> None:
|
|||||||
msg_no_auth["From"] = "alice@example.com"
|
msg_no_auth["From"] = "alice@example.com"
|
||||||
msg_no_auth.set_content("test")
|
msg_no_auth.set_content("test")
|
||||||
parsed = BytesParser(policy=policy.default).parsebytes(msg_no_auth.as_bytes())
|
parsed = BytesParser(policy=policy.default).parsebytes(msg_no_auth.as_bytes())
|
||||||
spf, dkim = EmailChannel._check_authentication_results(parsed)
|
channel = EmailChannel(
|
||||||
|
_make_config(trusted_authserv_ids=["mx.google.com"]),
|
||||||
|
MessageBus(),
|
||||||
|
)
|
||||||
|
spf, dkim = channel._check_authentication_results(parsed, "alice@example.com")
|
||||||
assert spf is False
|
assert spf is False
|
||||||
assert dkim is False
|
assert dkim is False
|
||||||
|
|
||||||
@@ -1129,7 +1293,7 @@ def test_check_authentication_results_method() -> None:
|
|||||||
)
|
)
|
||||||
msg_both.set_content("test")
|
msg_both.set_content("test")
|
||||||
parsed = BytesParser(policy=policy.default).parsebytes(msg_both.as_bytes())
|
parsed = BytesParser(policy=policy.default).parsebytes(msg_both.as_bytes())
|
||||||
spf, dkim = EmailChannel._check_authentication_results(parsed)
|
spf, dkim = channel._check_authentication_results(parsed, "alice@example.com")
|
||||||
assert spf is True
|
assert spf is True
|
||||||
assert dkim is True
|
assert dkim is True
|
||||||
|
|
||||||
@@ -1141,7 +1305,7 @@ def test_check_authentication_results_method() -> None:
|
|||||||
)
|
)
|
||||||
msg_spf_only.set_content("test")
|
msg_spf_only.set_content("test")
|
||||||
parsed = BytesParser(policy=policy.default).parsebytes(msg_spf_only.as_bytes())
|
parsed = BytesParser(policy=policy.default).parsebytes(msg_spf_only.as_bytes())
|
||||||
spf, dkim = EmailChannel._check_authentication_results(parsed)
|
spf, dkim = channel._check_authentication_results(parsed, "alice@example.com")
|
||||||
assert spf is True
|
assert spf is True
|
||||||
assert dkim is False
|
assert dkim is False
|
||||||
|
|
||||||
@@ -1153,7 +1317,7 @@ def test_check_authentication_results_method() -> None:
|
|||||||
)
|
)
|
||||||
msg_dkim_only.set_content("test")
|
msg_dkim_only.set_content("test")
|
||||||
parsed = BytesParser(policy=policy.default).parsebytes(msg_dkim_only.as_bytes())
|
parsed = BytesParser(policy=policy.default).parsebytes(msg_dkim_only.as_bytes())
|
||||||
spf, dkim = EmailChannel._check_authentication_results(parsed)
|
spf, dkim = channel._check_authentication_results(parsed, "alice@example.com")
|
||||||
assert spf is False
|
assert spf is False
|
||||||
assert dkim is True
|
assert dkim is True
|
||||||
|
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ def test_validate_email_presets_are_checked_without_saving(
|
|||||||
"channels.email.smtpHost": "smtp.gmail.com",
|
"channels.email.smtpHost": "smtp.gmail.com",
|
||||||
"channels.email.smtpUsername": "bot@example.com",
|
"channels.email.smtpUsername": "bot@example.com",
|
||||||
"channels.email.smtpPassword": "smtp-secret",
|
"channels.email.smtpPassword": "smtp-secret",
|
||||||
|
"channels.email.trustedAuthservIds": ["mx.google.com"],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -92,6 +93,7 @@ def test_validate_email_rejects_invalid_account_credentials(
|
|||||||
"channels.email.imapHost": "imap.example.com",
|
"channels.email.imapHost": "imap.example.com",
|
||||||
"channels.email.imapUsername": "bot@example.com",
|
"channels.email.imapUsername": "bot@example.com",
|
||||||
"channels.email.imapPassword": "wrong-secret",
|
"channels.email.imapPassword": "wrong-secret",
|
||||||
|
"channels.email.trustedAuthservIds": ["mx.example.com"],
|
||||||
"channels.email.smtpHost": "smtp.example.com",
|
"channels.email.smtpHost": "smtp.example.com",
|
||||||
"channels.email.smtpUsername": "bot@example.com",
|
"channels.email.smtpUsername": "bot@example.com",
|
||||||
"channels.email.smtpPassword": "smtp-secret",
|
"channels.email.smtpPassword": "smtp-secret",
|
||||||
@@ -109,6 +111,68 @@ def test_validate_email_rejects_invalid_account_credentials(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_email_requires_trusted_authserv_ids_for_authentication(
|
||||||
|
tmp_path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
config_path = tmp_path / "config.json"
|
||||||
|
save_config(Config(), config_path)
|
||||||
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||||
|
monkeypatch.setattr(email_validation, "probe_tcp", lambda *_args, **_kwargs: None)
|
||||||
|
monkeypatch.setattr(email_validation, "_imap_login", lambda *_args, **_kwargs: None)
|
||||||
|
monkeypatch.setattr(email_validation, "_smtp_login", lambda *_args, **_kwargs: None)
|
||||||
|
|
||||||
|
result = validate_channel_config(
|
||||||
|
"email",
|
||||||
|
{
|
||||||
|
"channels.email.consentGranted": "true",
|
||||||
|
"channels.email.imapHost": "imap.example.com",
|
||||||
|
"channels.email.imapUsername": "bot@example.com",
|
||||||
|
"channels.email.imapPassword": "imap-secret",
|
||||||
|
"channels.email.smtpHost": "smtp.example.com",
|
||||||
|
"channels.email.smtpUsername": "bot@example.com",
|
||||||
|
"channels.email.smtpPassword": "smtp-secret",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["status"] == "needs_setup"
|
||||||
|
assert result["can_enable"] is False
|
||||||
|
assert "trustedAuthservIds" in result["missing_fields"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("anchors", "verify", "expected"), [
|
||||||
|
(" MX.Google.COM. , mx.receiver.example ", True, "connected"),
|
||||||
|
(["mx.google.com"], True, "connected"),
|
||||||
|
(["*"], True, "invalid"),
|
||||||
|
([""], True, "invalid"),
|
||||||
|
([7], True, "invalid"),
|
||||||
|
("https://mx.google.com", True, "invalid"),
|
||||||
|
("", True, "needs_setup"),
|
||||||
|
([], False, "connected"),
|
||||||
|
(["*"], False, "invalid"),
|
||||||
|
])
|
||||||
|
def test_validate_email_authentication_matches_runtime_and_form_values(
|
||||||
|
tmp_path, monkeypatch, anchors, verify, expected,
|
||||||
|
) -> None:
|
||||||
|
config_path = tmp_path / "config.json"
|
||||||
|
save_config(Config(), config_path)
|
||||||
|
before = config_path.read_bytes()
|
||||||
|
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||||
|
monkeypatch.setattr(email_validation, "probe_tcp", lambda *_args, **_kwargs: None)
|
||||||
|
monkeypatch.setattr(email_validation, "_imap_login", lambda *_args, **_kwargs: None)
|
||||||
|
monkeypatch.setattr(email_validation, "_smtp_login", lambda *_args, **_kwargs: None)
|
||||||
|
result = validate_channel_config("email", {
|
||||||
|
"consentGranted": True,
|
||||||
|
"imapHost": "imap.example.com", "imapUsername": "bot@example.com", "imapPassword": "secret",
|
||||||
|
"smtpHost": "smtp.example.com", "smtpUsername": "bot@example.com", "smtpPassword": "secret",
|
||||||
|
"verifySpf": str(verify).lower(), "verifyDkim": str(verify).lower(),
|
||||||
|
"trustedAuthservIds": anchors,
|
||||||
|
})
|
||||||
|
assert result["status"] == expected
|
||||||
|
assert result["can_enable"] is (expected == "connected")
|
||||||
|
assert config_path.read_bytes() == before
|
||||||
|
|
||||||
|
|
||||||
def test_validate_email_blocks_private_targets_when_local_access_is_disabled(
|
def test_validate_email_blocks_private_targets_when_local_access_is_disabled(
|
||||||
tmp_path,
|
tmp_path,
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
|||||||
@@ -100,6 +100,8 @@ def validate(
|
|||||||
values: dict[str, Any],
|
values: dict[str, Any],
|
||||||
context: ChannelValidationContext,
|
context: ChannelValidationContext,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
|
from nanobot.channels.email.runtime import EmailConfig
|
||||||
|
|
||||||
checks, missing = required_checks("email", values)
|
checks, missing = required_checks("email", values)
|
||||||
if truthy(values.get("consentGranted")):
|
if truthy(values.get("consentGranted")):
|
||||||
checks.append(check("consent", "Mailbox consent", "pass", "Consent is enabled for this mailbox."))
|
checks.append(check("consent", "Mailbox consent", "pass", "Consent is enabled for this mailbox."))
|
||||||
@@ -113,6 +115,42 @@ def validate(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
verify_dkim = _bool_value(values, "verifyDkim", default=True)
|
||||||
|
verify_spf = _bool_value(values, "verifySpf", default=True)
|
||||||
|
trusted_authserv_ids = values.get("trustedAuthservIds")
|
||||||
|
if isinstance(trusted_authserv_ids, str):
|
||||||
|
trusted_authserv_ids = [item.strip() for item in trusted_authserv_ids.split(",") if item.strip()]
|
||||||
|
try:
|
||||||
|
auth_config = EmailConfig.model_validate({
|
||||||
|
"trustedAuthservIds": [] if trusted_authserv_ids is None else trusted_authserv_ids,
|
||||||
|
})
|
||||||
|
except ValueError:
|
||||||
|
checks.append(check(
|
||||||
|
"trusted_authserv_ids", "Trusted mail authentication service", "fail",
|
||||||
|
"Use exact authserv-id values, not wildcards, URLs, or empty entries.",
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
if verify_dkim or verify_spf:
|
||||||
|
if auth_config.trusted_authserv_ids:
|
||||||
|
checks.append(
|
||||||
|
check(
|
||||||
|
"trusted_authserv_ids",
|
||||||
|
"Trusted mail authentication service",
|
||||||
|
"pass",
|
||||||
|
"Authentication-Results is restricted to configured authserv-id values.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
missing.append("trustedAuthservIds")
|
||||||
|
checks.append(
|
||||||
|
check(
|
||||||
|
"trusted_authserv_ids",
|
||||||
|
"Trusted mail authentication service",
|
||||||
|
"fail",
|
||||||
|
"Set trustedAuthservIds when SPF or DKIM verification is enabled.",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
for prefix, default_port in (("imap", 993), ("smtp", 587)):
|
for prefix, default_port in (("imap", 993), ("smtp", 587)):
|
||||||
label = prefix.upper()
|
label = prefix.upper()
|
||||||
host = _resolved_string(values, f"{prefix}Host")
|
host = _resolved_string(values, f"{prefix}Host")
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ export default {
|
|||||||
{ key: "channels.email.allowFrom", section: "access" },
|
{ key: "channels.email.allowFrom", section: "access" },
|
||||||
{ key: "channels.email.verifyDkim", section: "security" },
|
{ key: "channels.email.verifyDkim", section: "security" },
|
||||||
{ key: "channels.email.verifySpf", section: "security" },
|
{ key: "channels.email.verifySpf", section: "security" },
|
||||||
|
{ key: "channels.email.trustedAuthservIds", section: "security" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -154,6 +154,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "Maximum attachments"
|
"label": "Maximum attachments"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "Trusted authentication services",
|
||||||
|
"placeholder": "mx.google.com, comma separated",
|
||||||
|
"help": "Exact authserv-id values added by the receiving mail service. Required when SPF or DKIM verification is on."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "Archivos adjuntos máximos"
|
"label": "Archivos adjuntos máximos"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "Servicios de autenticación confiables",
|
||||||
|
"placeholder": "mx.google.com, separados por comas",
|
||||||
|
"help": "Valores authserv-id exactos añadidos por el servicio receptor. Obligatorio al verificar SPF o DKIM."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "Nombre maximal de pièces jointes"
|
"label": "Nombre maximal de pièces jointes"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "Services d’authentification approuvés",
|
||||||
|
"placeholder": "mx.google.com, séparés par des virgules",
|
||||||
|
"help": "Valeurs authserv-id exactes ajoutées par le service de réception. Requis si SPF ou DKIM est vérifié."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "Lampiran maksimum"
|
"label": "Lampiran maksimum"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "Layanan autentikasi tepercaya",
|
||||||
|
"placeholder": "mx.google.com, pisahkan dengan koma",
|
||||||
|
"help": "Nilai authserv-id persis yang ditambahkan layanan penerima. Wajib saat verifikasi SPF atau DKIM aktif."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "最大添付ファイル数"
|
"label": "最大添付ファイル数"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "信頼する認証サービス",
|
||||||
|
"placeholder": "mx.google.com(カンマ区切り)",
|
||||||
|
"help": "受信メールサービスが追加する正確な authserv-id。SPF または DKIM 検証時は必須です。"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "최대 첨부 파일"
|
"label": "최대 첨부 파일"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "신뢰할 인증 서비스",
|
||||||
|
"placeholder": "mx.google.com, 쉼표로 구분",
|
||||||
|
"help": "수신 메일 서비스가 추가한 정확한 authserv-id입니다. SPF 또는 DKIM 확인 시 필수입니다."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "Máximo de anexos"
|
"label": "Máximo de anexos"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "Serviços de autenticação confiáveis",
|
||||||
|
"placeholder": "mx.google.com, separados por vírgulas",
|
||||||
|
"help": "Valores authserv-id exatos adicionados pelo serviço receptor. Obrigatório ao verificar SPF ou DKIM."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "Tệp đính kèm tối đa"
|
"label": "Tệp đính kèm tối đa"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "Dịch vụ xác thực tin cậy",
|
||||||
|
"placeholder": "mx.google.com, phân tách bằng dấu phẩy",
|
||||||
|
"help": "Giá trị authserv-id chính xác do dịch vụ nhận thư thêm vào. Bắt buộc khi xác minh SPF hoặc DKIM."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -154,6 +154,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "附件数量上限"
|
"label": "附件数量上限"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "可信邮件认证服务",
|
||||||
|
"placeholder": "mx.google.com,用逗号分隔",
|
||||||
|
"help": "接收邮件服务添加的准确 authserv-id。启用 SPF 或 DKIM 验证时必填。"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -155,6 +155,11 @@
|
|||||||
},
|
},
|
||||||
"maxAttachmentsPerEmail": {
|
"maxAttachmentsPerEmail": {
|
||||||
"label": "附件數量上限"
|
"label": "附件數量上限"
|
||||||
|
},
|
||||||
|
"trustedAuthservIds": {
|
||||||
|
"label": "可信郵件驗證服務",
|
||||||
|
"placeholder": "mx.google.com,以逗號分隔",
|
||||||
|
"help": "接收郵件服務加入的正確 authserv-id。啟用 SPF 或 DKIM 驗證時必填。"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ function channelSetupContract(
|
|||||||
field("allowFrom", "list"),
|
field("allowFrom", "list"),
|
||||||
field("verifyDkim", "bool", { defaultValue: "true" }),
|
field("verifyDkim", "bool", { defaultValue: "true" }),
|
||||||
field("verifySpf", "bool", { defaultValue: "true" }),
|
field("verifySpf", "bool", { defaultValue: "true" }),
|
||||||
|
field("trustedAuthservIds", "list"),
|
||||||
],
|
],
|
||||||
requirements: [
|
requirements: [
|
||||||
{ alternatives: [["channels.email.consentGranted"]] },
|
{ alternatives: [["channels.email.consentGranted"]] },
|
||||||
@@ -1599,6 +1600,9 @@ describe("Settings channels", () => {
|
|||||||
expect(screen.queryByRole("button", { name: "Gmail" })).not.toBeInTheDocument();
|
expect(screen.queryByRole("button", { name: "Gmail" })).not.toBeInTheDocument();
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
|
fireEvent.click(screen.getByRole("button", { name: "Advanced" }));
|
||||||
expect(screen.getByText("Quick fill")).toBeVisible();
|
expect(screen.getByText("Quick fill")).toBeVisible();
|
||||||
|
const trustedServices = screen.getByLabelText("Trusted authentication services");
|
||||||
|
expect(trustedServices).toBeVisible();
|
||||||
|
fireEvent.change(trustedServices, { target: { value: "mx.receiver.example" } });
|
||||||
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.custom.test" } });
|
fireEvent.change(screen.getByLabelText("IMAP host"), { target: { value: "imap.custom.test" } });
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Gmail" }));
|
fireEvent.click(screen.getByRole("button", { name: "Gmail" }));
|
||||||
expect(screen.getByLabelText("IMAP host")).toHaveValue("imap.custom.test");
|
expect(screen.getByLabelText("IMAP host")).toHaveValue("imap.custom.test");
|
||||||
@@ -1643,6 +1647,7 @@ describe("Settings channels", () => {
|
|||||||
name: "email",
|
name: "email",
|
||||||
values: expect.objectContaining({
|
values: expect.objectContaining({
|
||||||
"channels.email.consentGranted": "true",
|
"channels.email.consentGranted": "true",
|
||||||
|
"channels.email.trustedAuthservIds": "mx.receiver.example",
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
20_000,
|
20_000,
|
||||||
|
|||||||
Reference in new issue
Block a user