test_ita_otp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 OtpMailConfig, ItaProtocolError, parse_otp_body, resolve_route_config
  7. from vs_types import (
  8. BizLogicError, PermissionDeniedError, RateLimiteddError,
  9. SessionExpiredOrInvalidError,
  10. )
  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.ita.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. def fetch(self):
  61. return otp.fetch_otp_from_cloud(self.config, recipient='applicant@example.test',
  62. sent_at='2026-08-31 01:02:03', api=self.client)
  63. def test_exact_sdk_call_and_no_top_fallback(self):
  64. self.assertEqual(self.fetch(), '001234')
  65. self.client.fetch_mail_content.assert_called_once_with(
  66. email='mailbox@example.test', sender='noreply-prenotami@esteri.it',
  67. recipient='applicant@example.test', subject_keywords='OTP Code',
  68. body_keywords='OTP Code:', sent_date='2026-08-31 01:02:03', expiry=300, only_text=True)
  69. self.client.fetch_mail_content_from_top.assert_not_called()
  70. def test_account_source_uses_each_actual_account_for_mailbox_and_recipient(self):
  71. config = OtpMailConfig(authorization_source="account")
  72. for address in ("first@example.test", "second@example.test", "first@example.test"):
  73. with self.subTest(address=address):
  74. self.client.reset_mock()
  75. self.assertEqual(otp.fetch_otp_from_cloud(config, recipient=address,
  76. sent_at="2026-08-31 01:02:03", api=self.client), "001234")
  77. self.client.fetch_mail_content.assert_called_once_with(
  78. email=address, recipient=address, sender="noreply-prenotami@esteri.it",
  79. subject_keywords="OTP Code", body_keywords="OTP Code:",
  80. sent_date="2026-08-31 01:02:03", expiry=300, only_text=True)
  81. self.client.fetch_mail_content_from_top.assert_not_called()
  82. self.assertIsNone(config.authorization_email)
  83. def test_account_mailbox_failure_does_not_read_another_inbox(self):
  84. config = OtpMailConfig(authorization_source="account")
  85. self.client.fetch_mail_content.side_effect = PermissionDeniedError("private-provider-details")
  86. with self.assertRaisesRegex(PermissionDeniedError, "not permitted"):
  87. otp.fetch_otp_from_cloud(config, recipient="second@example.test",
  88. sent_at="2026-08-31 01:02:03", api=self.client)
  89. self.client.fetch_mail_content.assert_called_once()
  90. self.assertEqual(self.client.fetch_mail_content.call_args.kwargs["email"], "second@example.test")
  91. self.client.fetch_mail_content_from_top.assert_not_called()
  92. def test_mail_environment_validation_has_no_logger_policy(self):
  93. self.assertEqual(
  94. otp.validate_cloud_otp_environment(self.config, ' applicant@example.test '),
  95. 'applicant@example.test',
  96. )
  97. self.client.fetch_mail_content.assert_not_called()
  98. def test_provider_failures_are_redacted_and_not_site_session_errors(self):
  99. marker = 'PRIVATE_MAIL_CONTENT_001234'
  100. cases = (
  101. (BizLogicError(marker), BizLogicError),
  102. (PermissionDeniedError(marker), PermissionDeniedError),
  103. (SessionExpiredOrInvalidError(marker), SessionExpiredOrInvalidError),
  104. (ValueError(marker), BizLogicError),
  105. (TimeoutError(marker), BizLogicError),
  106. )
  107. for error, expected in cases:
  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(expected) 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(BizLogicError):
  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(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. for status in (200, 401, 403, 429, 504):
  129. with self.subTest(status=status):
  130. response = Mock(status_code=status, text="PRIVATE_MAIL OTP Code:001234")
  131. response.json.return_value = {"code": 0, "data": {"body": "OTP Code:001234"}}
  132. client.session.request.reset_mock()
  133. client.session.request.return_value = response
  134. if status == 200:
  135. self.assertEqual(otp.fetch_otp_from_cloud(self.config,
  136. recipient="applicant@example.test", sent_at="2026-08-31 01:02:03", api=client), "001234")
  137. else:
  138. expected = {
  139. 401: SessionExpiredOrInvalidError,
  140. 403: PermissionDeniedError,
  141. 429: RateLimiteddError,
  142. 504: BizLogicError,
  143. }[status]
  144. with self.assertRaises(expected) as raised:
  145. otp.fetch_otp_from_cloud(self.config, recipient="applicant@example.test",
  146. sent_at="2026-08-31 01:02:03", api=client)
  147. rendered = ''.join(traceback.format_exception(raised.exception))
  148. self.assertNotIn("PRIVATE_MAIL", rendered)
  149. self.assertNotIn("001234", rendered)
  150. client.session.request.assert_called_once()
  151. args = client.session.request.call_args.kwargs
  152. self.assertEqual(args["params"]["sentDate"], "2026-08-31 01:02:03")
  153. self.assertEqual(args["params"]["expiry"], "300")
  154. self.assertEqual(args["timeout"], 300)
  155. def test_bad_mail_body_is_rejected_without_fallback(self):
  156. for body in (None, "unknown template", "OTP Code:123456 OTP Code:654321"):
  157. with self.subTest(body=body):
  158. self.client.fetch_mail_content.return_value = body
  159. with self.assertRaises(BizLogicError):
  160. self.fetch()
  161. self.client.fetch_mail_content_from_top.assert_not_called()