test_ita_otp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """Italy-only cloud OTP contract: synthetic messages, no network or credentials."""
  2. import logging
  3. import traceback
  4. from io import StringIO
  5. from unittest import TestCase
  6. from unittest.mock import Mock, patch
  7. from plugins import ita_plugin as otp
  8. from plugins.ita_plugin import CalendarGateError
  9. from plugins.ita_plugin import OtpMailConfig, ItaProtocolError, parse_otp_body, resolve_route_config
  10. from vs_types import BizLogicError, PermissionDeniedError, SessionExpiredOrInvalidError
  11. class OtpParserTests(TestCase):
  12. def test_observed_marker_preserves_zero_and_deduplicates_mime_alternatives(self):
  13. self.assertEqual(parse_otp_body('OTP Code:001234 <p>OTP Code: <b>001234</b></p>'), '001234')
  14. def test_rejects_unknown_ambiguous_and_malformed_messages(self):
  15. for body in (None, '', '123456', 'OTP Code:1234567', 'OTP Code:123456x',
  16. 'OTP Code:123456', 'OTP Code:1234567',
  17. 'OTP Code:123456 OTP Code:654321'):
  18. with self.subTest(body=body), self.assertRaises(ItaProtocolError):
  19. parse_otp_body(body)
  20. with self.assertRaises(ItaProtocolError):
  21. parse_otp_body('OTP Code:123456', max_chars=5)
  22. def test_mail_filters_cannot_be_broadened(self):
  23. for field, value in [('subject_keywords', 'OTP Code,anything'), ('body_keywords', 'Code'),
  24. ('expiry_seconds', True), ('expiry_seconds', 301)]:
  25. with self.subTest(field=field), self.assertRaises(ItaProtocolError):
  26. OtpMailConfig('mailbox@example.test', **{field: value})
  27. def test_account_source_resolves_each_mailbox_without_mutating_shared_config(self):
  28. config = OtpMailConfig(authorization_source="account")
  29. for address in ("first@example.test", "second@example.test", "first@example.test"):
  30. self.assertEqual(config.mailbox_for(address), address)
  31. self.assertIsNone(config.authorization_email)
  32. self.assertNotIn(address, repr(config))
  33. self.assertEqual(config.authorization_source, "account")
  34. with self.assertRaises(ItaProtocolError):
  35. config.mailbox_for("not-an-email")
  36. def test_mailbox_source_is_explicit_and_rejects_ambiguous_configuration(self):
  37. for config in ({}, {"authorization_source": "unknown"}, {"authorization_source": None},
  38. {"authorization_source": "account", "authorization_email": "old@example.test"},
  39. {"authorization_source": "account", "authorization_email": ""}):
  40. with self.subTest(config=config), self.assertRaises(ItaProtocolError):
  41. OtpMailConfig(**config)
  42. fixed = OtpMailConfig("shared@example.test")
  43. self.assertEqual(fixed.mailbox_for("different@example.test"), "shared@example.test")
  44. def test_route_parser_accepts_account_source_without_widening_sender_filters(self):
  45. from test.test_ita_protocol import live_route
  46. route = live_route()
  47. route["mail"] = {"authorization_source": "account"}
  48. result = resolve_route_config({"slot.sample.it.tourist": route}, "slot.sample.it.tourist")
  49. self.assertEqual(result.mail.mailbox_for("pooled@example.test"), "pooled@example.test")
  50. for key, value in (("sender", "other@example.test"), ("subject_keywords", "anything"),
  51. ("body_keywords", "anything"), ("expiry_seconds", 301)):
  52. with self.subTest(key=key), self.assertRaises(ItaProtocolError):
  53. changed = {**route, "mail": {**route["mail"], key: value}}
  54. resolve_route_config({"slot.sample.it.tourist": changed}, "slot.sample.it.tourist")
  55. class CloudOtpTests(TestCase):
  56. def setUp(self):
  57. self.config = OtpMailConfig('mailbox@example.test')
  58. self.client = Mock()
  59. self.client.fetch_mail_content.return_value = 'OTP Code:001234'
  60. self.logger = logging.Logger('offline-italy', level=logging.INFO)
  61. p = patch.object(otp.vs_log_macros, '_active_logger', self.logger)
  62. p.start()
  63. self.addCleanup(p.stop)
  64. def fetch(self):
  65. return otp.fetch_otp_from_cloud(self.config, recipient='applicant@example.test',
  66. sent_at='2026-08-31 01:02:03', api=self.client)
  67. def test_exact_sdk_call_and_no_top_fallback(self):
  68. self.assertEqual(self.fetch(), '001234')
  69. self.client.fetch_mail_content.assert_called_once_with(
  70. email='mailbox@example.test', sender='noreply-prenotami@esteri.it',
  71. recipient='applicant@example.test', subject_keywords='OTP Code',
  72. body_keywords='OTP Code:', sent_date='2026-08-31 01:02:03', expiry=300, only_text=True)
  73. self.client.fetch_mail_content_from_top.assert_not_called()
  74. def test_account_source_uses_each_actual_account_for_mailbox_and_recipient(self):
  75. config = OtpMailConfig(authorization_source="account")
  76. for address in ("first@example.test", "second@example.test", "first@example.test"):
  77. with self.subTest(address=address):
  78. self.client.reset_mock()
  79. self.assertEqual(otp.fetch_otp_from_cloud(config, recipient=address,
  80. sent_at="2026-08-31 01:02:03", api=self.client), "001234")
  81. self.client.fetch_mail_content.assert_called_once_with(
  82. email=address, recipient=address, sender="noreply-prenotami@esteri.it",
  83. subject_keywords="OTP Code", body_keywords="OTP Code:",
  84. sent_date="2026-08-31 01:02:03", expiry=300, only_text=True)
  85. self.client.fetch_mail_content_from_top.assert_not_called()
  86. self.assertIsNone(config.authorization_email)
  87. def test_account_mailbox_failure_does_not_read_another_inbox(self):
  88. config = OtpMailConfig(authorization_source="account")
  89. self.client.fetch_mail_content.side_effect = PermissionDeniedError("private-provider-details")
  90. with self.assertRaisesRegex(CalendarGateError, "not permitted"):
  91. otp.fetch_otp_from_cloud(config, recipient="second@example.test",
  92. sent_at="2026-08-31 01:02:03", api=self.client)
  93. self.client.fetch_mail_content.assert_called_once()
  94. self.assertEqual(self.client.fetch_mail_content.call_args.kwargs["email"], "second@example.test")
  95. self.client.fetch_mail_content_from_top.assert_not_called()
  96. def test_debug_logging_is_rejected_without_mutating_shared_logger_or_reading_mail(self):
  97. self.logger.setLevel(logging.DEBUG)
  98. before = list(self.logger.filters)
  99. with self.assertRaisesRegex(CalendarGateError, 'DEBUG'):
  100. self.fetch()
  101. self.client.fetch_mail_content.assert_not_called()
  102. self.assertEqual(self.logger.filters, before)
  103. self.assertEqual(self.logger.level, logging.DEBUG)
  104. def test_provider_failures_are_redacted_and_not_site_session_errors(self):
  105. marker = 'PRIVATE_MAIL_CONTENT_001234'
  106. for error in (BizLogicError(marker), PermissionDeniedError(marker),
  107. SessionExpiredOrInvalidError(marker), ValueError(marker), TimeoutError(marker)):
  108. self.client.reset_mock()
  109. self.client.fetch_mail_content.side_effect = error
  110. with self.subTest(error=type(error).__name__):
  111. with self.assertRaises(CalendarGateError) as caught:
  112. self.fetch()
  113. rendered = ''.join(traceback.format_exception(caught.exception))
  114. self.assertNotIn(marker, rendered)
  115. self.client.fetch_mail_content.assert_called_once()
  116. self.client.fetch_mail_content_from_top.assert_not_called()
  117. def test_invalid_input_never_reads_mail(self):
  118. with self.assertRaises(CalendarGateError):
  119. otp.fetch_otp_from_cloud(self.config, recipient='not-an-address', sent_at='invalid', api=self.client)
  120. self.client.fetch_mail_content.assert_not_called()
  121. def test_real_sdk_contract_with_fake_transport_and_no_payload_output(self):
  122. # Exercise the actual VFS/BLS shared SDK without its singleton settings
  123. # or any external HTTP. Neither existing SDK nor global log state is edited.
  124. client = object.__new__(otp.VSCloudApi)
  125. client.base_url = "https://mail.example.test"
  126. client.api_token = "synthetic-only"
  127. client.session = Mock()
  128. output = StringIO()
  129. self.logger.addHandler(logging.StreamHandler(output))
  130. for status in (200, 401, 403, 429, 504):
  131. with self.subTest(status=status):
  132. response = Mock(status_code=status, text="PRIVATE_MAIL OTP Code:001234")
  133. response.json.return_value = {"code": 0, "data": {"body": "OTP Code:001234"}}
  134. client.session.request.reset_mock()
  135. client.session.request.return_value = response
  136. if status == 200:
  137. self.assertEqual(otp.fetch_otp_from_cloud(self.config,
  138. recipient="applicant@example.test", sent_at="2026-08-31 01:02:03", api=client), "001234")
  139. else:
  140. with self.assertRaises(CalendarGateError) as raised:
  141. otp.fetch_otp_from_cloud(self.config, recipient="applicant@example.test",
  142. sent_at="2026-08-31 01:02:03", api=client)
  143. rendered = ''.join(traceback.format_exception(raised.exception))
  144. self.assertNotIn("PRIVATE_MAIL", rendered)
  145. self.assertNotIn("001234", rendered)
  146. client.session.request.assert_called_once()
  147. args = client.session.request.call_args.kwargs
  148. self.assertEqual(args["params"]["sentDate"], "2026-08-31 01:02:03")
  149. self.assertEqual(args["params"]["expiry"], "300")
  150. self.assertEqual(args["timeout"], 300)
  151. self.assertEqual(output.getvalue(), "")
  152. def test_bad_mail_body_is_rejected_without_fallback(self):
  153. for body in (None, "unknown template", "OTP Code:123456 OTP Code:654321"):
  154. with self.subTest(body=body):
  155. self.client.fetch_mail_content.return_value = body
  156. with self.assertRaises(CalendarGateError):
  157. self.fetch()
  158. self.client.fetch_mail_content_from_top.assert_not_called()