"""Italy-only cloud OTP contract: synthetic messages, no network or credentials.""" import traceback from unittest import TestCase from unittest.mock import Mock from plugins import ita_plugin as otp from plugins.ita_plugin import OtpMailConfig, ItaProtocolError, parse_otp_body, resolve_route_config from vs_types import ( BizLogicError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, ) class OtpParserTests(TestCase): def test_observed_marker_preserves_zero_and_deduplicates_mime_alternatives(self): self.assertEqual(parse_otp_body('OTP Code:001234
OTP Code: 001234
'), '001234') def test_rejects_unknown_ambiguous_and_malformed_messages(self): for body in (None, '', '123456', 'OTP Code:1234567', 'OTP Code:123456x', 'OTP Code:123456', 'OTP Code:1234567', 'OTP Code:123456 OTP Code:654321'): with self.subTest(body=body), self.assertRaises(ItaProtocolError): parse_otp_body(body) with self.assertRaises(ItaProtocolError): parse_otp_body('OTP Code:123456', max_chars=5) def test_mail_filters_cannot_be_broadened(self): for field, value in [('subject_keywords', 'OTP Code,anything'), ('body_keywords', 'Code'), ('expiry_seconds', True), ('expiry_seconds', 301)]: with self.subTest(field=field), self.assertRaises(ItaProtocolError): OtpMailConfig('mailbox@example.test', **{field: value}) def test_account_source_resolves_each_mailbox_without_mutating_shared_config(self): config = OtpMailConfig(authorization_source="account") for address in ("first@example.test", "second@example.test", "first@example.test"): self.assertEqual(config.mailbox_for(address), address) self.assertIsNone(config.authorization_email) self.assertNotIn(address, repr(config)) self.assertEqual(config.authorization_source, "account") with self.assertRaises(ItaProtocolError): config.mailbox_for("not-an-email") def test_mailbox_source_is_explicit_and_rejects_ambiguous_configuration(self): for config in ({}, {"authorization_source": "unknown"}, {"authorization_source": None}, {"authorization_source": "account", "authorization_email": "old@example.test"}, {"authorization_source": "account", "authorization_email": ""}): with self.subTest(config=config), self.assertRaises(ItaProtocolError): OtpMailConfig(**config) fixed = OtpMailConfig("shared@example.test") self.assertEqual(fixed.mailbox_for("different@example.test"), "shared@example.test") def test_route_parser_accepts_account_source_without_widening_sender_filters(self): from test.ita.test_ita_protocol import live_route route = live_route() route["mail"] = {"authorization_source": "account"} result = resolve_route_config({"slot.sample.it.tourist": route}, "slot.sample.it.tourist") self.assertEqual(result.mail.mailbox_for("pooled@example.test"), "pooled@example.test") for key, value in (("sender", "other@example.test"), ("subject_keywords", "anything"), ("body_keywords", "anything"), ("expiry_seconds", 301)): with self.subTest(key=key), self.assertRaises(ItaProtocolError): changed = {**route, "mail": {**route["mail"], key: value}} resolve_route_config({"slot.sample.it.tourist": changed}, "slot.sample.it.tourist") class CloudOtpTests(TestCase): def setUp(self): self.config = OtpMailConfig('mailbox@example.test') self.client = Mock() self.client.fetch_mail_content.return_value = 'OTP Code:001234' def fetch(self): return otp.fetch_otp_from_cloud(self.config, recipient='applicant@example.test', sent_at='2026-08-31 01:02:03', api=self.client) def test_exact_sdk_call_and_no_top_fallback(self): self.assertEqual(self.fetch(), '001234') self.client.fetch_mail_content.assert_called_once_with( email='mailbox@example.test', sender='noreply-prenotami@esteri.it', recipient='applicant@example.test', subject_keywords='OTP Code', body_keywords='OTP Code:', sent_date='2026-08-31 01:02:03', expiry=300, only_text=True) self.client.fetch_mail_content_from_top.assert_not_called() def test_account_source_uses_each_actual_account_for_mailbox_and_recipient(self): config = OtpMailConfig(authorization_source="account") for address in ("first@example.test", "second@example.test", "first@example.test"): with self.subTest(address=address): self.client.reset_mock() self.assertEqual(otp.fetch_otp_from_cloud(config, recipient=address, sent_at="2026-08-31 01:02:03", api=self.client), "001234") self.client.fetch_mail_content.assert_called_once_with( email=address, recipient=address, sender="noreply-prenotami@esteri.it", subject_keywords="OTP Code", body_keywords="OTP Code:", sent_date="2026-08-31 01:02:03", expiry=300, only_text=True) self.client.fetch_mail_content_from_top.assert_not_called() self.assertIsNone(config.authorization_email) def test_account_mailbox_failure_does_not_read_another_inbox(self): config = OtpMailConfig(authorization_source="account") self.client.fetch_mail_content.side_effect = PermissionDeniedError("private-provider-details") with self.assertRaisesRegex(PermissionDeniedError, "not permitted"): otp.fetch_otp_from_cloud(config, recipient="second@example.test", sent_at="2026-08-31 01:02:03", api=self.client) self.client.fetch_mail_content.assert_called_once() self.assertEqual(self.client.fetch_mail_content.call_args.kwargs["email"], "second@example.test") self.client.fetch_mail_content_from_top.assert_not_called() def test_mail_environment_validation_has_no_logger_policy(self): self.assertEqual( otp.validate_cloud_otp_environment(self.config, ' applicant@example.test '), 'applicant@example.test', ) self.client.fetch_mail_content.assert_not_called() def test_provider_failures_are_redacted_and_not_site_session_errors(self): marker = 'PRIVATE_MAIL_CONTENT_001234' cases = ( (BizLogicError(marker), BizLogicError), (PermissionDeniedError(marker), PermissionDeniedError), (SessionExpiredOrInvalidError(marker), SessionExpiredOrInvalidError), (ValueError(marker), BizLogicError), (TimeoutError(marker), BizLogicError), ) for error, expected in cases: self.client.reset_mock() self.client.fetch_mail_content.side_effect = error with self.subTest(error=type(error).__name__): with self.assertRaises(expected) as caught: self.fetch() rendered = ''.join(traceback.format_exception(caught.exception)) self.assertNotIn(marker, rendered) self.client.fetch_mail_content.assert_called_once() self.client.fetch_mail_content_from_top.assert_not_called() def test_invalid_input_never_reads_mail(self): with self.assertRaises(BizLogicError): otp.fetch_otp_from_cloud(self.config, recipient='not-an-address', sent_at='invalid', api=self.client) self.client.fetch_mail_content.assert_not_called() def test_real_sdk_contract_with_fake_transport(self): # Exercise the actual VFS/BLS shared SDK without its singleton settings # or any external HTTP. Neither existing SDK nor global log state is edited. client = object.__new__(otp.VSCloudApi) client.base_url = "https://mail.example.test" client.api_token = "synthetic-only" client.session = Mock() for status in (200, 401, 403, 429, 504): with self.subTest(status=status): response = Mock(status_code=status, text="PRIVATE_MAIL OTP Code:001234") response.json.return_value = {"code": 0, "data": {"body": "OTP Code:001234"}} client.session.request.reset_mock() client.session.request.return_value = response if status == 200: self.assertEqual(otp.fetch_otp_from_cloud(self.config, recipient="applicant@example.test", sent_at="2026-08-31 01:02:03", api=client), "001234") else: expected = { 401: SessionExpiredOrInvalidError, 403: PermissionDeniedError, 429: RateLimiteddError, 504: BizLogicError, }[status] with self.assertRaises(expected) as raised: otp.fetch_otp_from_cloud(self.config, recipient="applicant@example.test", sent_at="2026-08-31 01:02:03", api=client) rendered = ''.join(traceback.format_exception(raised.exception)) self.assertNotIn("PRIVATE_MAIL", rendered) self.assertNotIn("001234", rendered) client.session.request.assert_called_once() args = client.session.request.call_args.kwargs self.assertEqual(args["params"]["sentDate"], "2026-08-31 01:02:03") self.assertEqual(args["params"]["expiry"], "300") self.assertEqual(args["timeout"], 300) def test_bad_mail_body_is_rejected_without_fallback(self): for body in (None, "unknown template", "OTP Code:123456 OTP Code:654321"): with self.subTest(body=body): self.client.fetch_mail_content.return_value = body with self.assertRaises(BizLogicError): self.fetch() self.client.fetch_mail_content_from_top.assert_not_called()