The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(email): require the pre-fetch authorization gate
kshitijk4poore9a385c603b0
diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex 1922fcf8443..5449d6e71d4 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -650,10 +650,8 @@ class EmailAdapter(BasePlatformAdapter):if status != "OK":logger.warning("[Email] Could not mark rejected UID %s seen", uid)- def _fetch_new_messages(- self, preauthorize: Optional[Callable[[Dict[str, Any]], bool]] = None,- ) -> List[Dict[str, Any]]:- """Fetch unseen messages. When *preauthorize* is set, bounded headers are gated before RFC822."""+ def _fetch_new_messages(self, preauthorize: Callable[[Dict[str, Any]], bool]) -> List[Dict[str, Any]]:+ """Fetch unseen messages; bounded headers pass *preauthorize* before RFC822 is requested."""results = []try:with self._inbox() as imap:@@ -661,34 +659,33 @@ class EmailAdapter(BasePlatformAdapter):for uid in (data[0].split() if status == "OK" and data and data[0] else []):if uid in self._seen_uids:continue- if preauthorize is not None:- header_status, header_data = imap.uid("fetch", uid, _PREAUTH_FETCH)- if header_status != "OK":- continue- try:- raw_headers = header_data[0][1]- except (IndexError, TypeError):- logger.warning("[Email] Unexpected IMAP header response for UID %s, skipping", uid)- self._mark_uid_consumed(imap, uid)- continue- if not isinstance(raw_headers, (bytes, bytearray)):- logger.warning("[Email] Non-bytes IMAP header payload for UID %s, skipping", uid)- self._mark_uid_consumed(imap, uid)- continue- if len(raw_headers) > _MAX_PREAUTH_HEADER_BYTES:- logger.warning("[Email] Pre-authorization headers exceed %d bytes for UID %s, skipping",- _MAX_PREAUTH_HEADER_BYTES, uid)- self._mark_uid_consumed(imap, uid)- continue- try:- candidate = self._parse_fetched_headers(uid, raw_headers)- accepted = candidate is not None and preauthorize(candidate)- except Exception as auth_exc:- logger.error("[Email] Failed to authorize message UID %s, skipping: %s", uid, auth_exc)- accepted = False- if not accepted:- self._mark_uid_consumed(imap, uid)- continue+ header_status, header_data = imap.uid("fetch", uid, _PREAUTH_FETCH)+ if header_status != "OK":+ continue+ try:+ raw_headers = header_data[0][1]+ except (IndexError, TypeError):+ logger.warning("[Email] Unexpected IMAP header response for UID %s, skipping", uid)+ self._mark_uid_consumed(imap, uid)+ continue+ if not isinstance(raw_headers, (bytes, bytearray)):+ logger.warning("[Email] Non-bytes IMAP header payload for UID %s, skipping", uid)+ self._mark_uid_consumed(imap, uid)+ continue+ if len(raw_headers) > _MAX_PREAUTH_HEADER_BYTES:+ logger.warning("[Email] Pre-authorization headers exceed %d bytes for UID %s, skipping",+ _MAX_PREAUTH_HEADER_BYTES, uid)+ self._mark_uid_consumed(imap, uid)+ continue+ try:+ candidate = self._parse_fetched_headers(uid, raw_headers)+ accepted = candidate is not None and preauthorize(candidate)+ except Exception as auth_exc:+ logger.error("[Email] Failed to authorize message UID %s, skipping: %s", uid, auth_exc)+ accepted = False+ if not accepted:+ self._mark_uid_consumed(imap, uid)+ continuestatus, msg_data = imap.uid("fetch", uid, "(RFC822)")if status != "OK":continue # transient per-UID refusal: leave unseen so the next poll retriesdiff --git a/tests/gateway/test_email.py b/tests/gateway/test_email.pyindex c859726acee..b7bfe97b333 100644--- a/tests/gateway/test_email.py+++ b/tests/gateway/test_email.py@@ -651,7 +651,7 @@ class TestFetchNewMessages(unittest.TestCase):mock_imap.uid.side_effect = uid_handlerwith patch("imaplib.IMAP4_SSL", return_value=mock_imap):- results = adapter._fetch_new_messages()+ results = adapter._fetch_new_messages(lambda _c: True)# Only UID 3 should be fetched (1 and 2 already seen)self.assertEqual(len(results), 1)@@ -885,7 +885,7 @@ class TestPollLoop(unittest.TestCase):return ("OK", [b"1 2 3"])if command == "fetch":fetches.append(args)- if len(fetches) == 1:+ if args[0] == b"1":return ("OK", [(b"1", raw_email.as_bytes())])raise OSError("connection dropped")return ("NO", [])@@ -893,7 +893,7 @@ class TestPollLoop(unittest.TestCase):mock_imap.uid.side_effect = uid_handlerwith patch("imaplib.IMAP4_SSL", return_value=mock_imap):- results = adapter._fetch_new_messages()+ results = adapter._fetch_new_messages(lambda _c: True)self.assertEqual(len(results), 1)self.assertIn(b"1", adapter._seen_uids) # fetched → seen@@ -919,6 +919,8 @@ class TestPollLoop(unittest.TestCase):return ("OK", [b"1 2"])if command == "fetch":uid = args[0]+ if "BODY.PEEK" in args[1]:+ return ("OK", [(uid, good_email.as_bytes())])if uid == b"1":return ("OK", [(b"1", b"poison")])return ("OK", [(b"2", good_email.as_bytes())])@@ -930,7 +932,7 @@ class TestPollLoop(unittest.TestCase):"plugins.platforms.email.adapter.EmailAdapter._parse_fetched_message",side_effect=[ValueError("unparseable"), {"subject": "good"}],):- results = adapter._fetch_new_messages()+ results = adapter._fetch_new_messages(lambda _c: True)# Poison message consumed (seen, skipped); good message survived.self.assertEqual(len(results), 1)@@ -1122,7 +1124,7 @@ class TestImapConnectionCleanup(unittest.TestCase):mock_imap.uid.side_effect = uid_handlerwith patch("imaplib.IMAP4_SSL", return_value=mock_imap):- results = adapter._fetch_new_messages()+ results = adapter._fetch_new_messages(lambda _c: True)self.assertEqual(results, [])mock_imap.logout.assert_called_once()diff --git a/tests/gateway/test_email_imap_id_protocol.py b/tests/gateway/test_email_imap_id_protocol.pyindex 9a103f384cb..f9ee6c5a6ae 100644--- a/tests/gateway/test_email_imap_id_protocol.py+++ b/tests/gateway/test_email_imap_id_protocol.py@@ -102,7 +102,7 @@ def test_id_negotiation_preserves_inbox_connection(monkeypatch, id_mode):lambda *args, **kwargs: imaplib.IMAP4(*address, timeout=5),)- assert adapter._fetch_new_messages() == []+ assert adapter._fetch_new_messages(lambda _c: True) == []assert adapter._last_fetch_failed is Falseassert commands.count("ID") == (0 if id_mode == "absent" else 1)diff --git a/tests/gateway/test_email_robustness.py b/tests/gateway/test_email_robustness.pyindex 34044c60888..9c78c6feb1e 100644--- a/tests/gateway/test_email_robustness.py+++ b/tests/gateway/test_email_robustness.py@@ -50,13 +50,15 @@ class TestImapResponseGuard(unittest.TestCase):if command == "search":return ("OK", [uids])if command == "fetch":+ if "BODY.PEEK" in args[1]:+ return ("OK", [(args[0], _raw_email())])return next(fetch_iter)return ("NO", [])mock_imap = MagicMock()mock_imap.uid.side_effect = uid_handlerwith patch("imaplib.IMAP4_SSL", return_value=mock_imap):- return adapter._fetch_new_messages()+ return adapter._fetch_new_messages(lambda _c: True)def test_normal_response_parses(self):results = self._fetch_with([("OK", [(b"1 (RFC822 {123}", _raw_email())])])diff --git a/tests/gateway/test_poller_fd_lifecycle.py b/tests/gateway/test_poller_fd_lifecycle.pyindex 8cc0bcb45a8..1bbaea2526d 100644--- a/tests/gateway/test_poller_fd_lifecycle.py+++ b/tests/gateway/test_poller_fd_lifecycle.py@@ -82,7 +82,7 @@ class TestFetchClosesSocketOnBrokenLogout(unittest.TestCase):mock_imap.logout.side_effect = imaplib.IMAP4.abort("EOF")with patch("imaplib.IMAP4_SSL", return_value=mock_imap):- results = adapter._fetch_new_messages()+ results = adapter._fetch_new_messages(lambda _c: True)self.assertEqual(results, [])mock_imap.shutdown.assert_called_once()