test_ita_otp.py 9.6 KB

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