test_ita_login_flow.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """W2/UT-04: real Italy entry and BaseFlow, synthetic browser only."""
  2. from contextlib import ExitStack
  3. from tempfile import TemporaryDirectory
  4. import unittest
  5. from unittest.mock import Mock, patch
  6. from plugins import ita_plugin as ita
  7. from test.ita.ita_test_fakes import FakeChromiumOptions, FakeKeyboard, FakeMouse, FakePage
  8. from utils.flow_engine import BaseFlow
  9. from vs_types import (
  10. BizLogicError, NotFoundError, PermissionDeniedError, RateLimiteddError,
  11. SessionExpiredOrInvalidError, VSAccount, VSPlgConfig,
  12. )
  13. class DelayedFormPage(FakePage):
  14. def __init__(self):
  15. super().__init__()
  16. self.password_reads = 0
  17. def ele(self, selector, timeout=None):
  18. if self.state == "pingid" and selector == "@name=callback_2":
  19. self.password_reads += 1
  20. if self.password_reads < 3:
  21. return None
  22. return super().ele(selector, timeout)
  23. class ServerErrorPage(FakePage):
  24. @property
  25. def html(self):
  26. return "503 Service Temporarily Unavailable" if self.state == "pingid" else ""
  27. class LoginFlowTests(unittest.TestCase):
  28. def setup_plugin(self, page):
  29. stack = ExitStack()
  30. self.addCleanup(stack.close)
  31. workspace = stack.enter_context(TemporaryDirectory())
  32. with patch.object(ita.os.path, "abspath", return_value=workspace):
  33. plugin = ita.ItaPlugin("offline-login-flow")
  34. plugin.set_config(VSPlgConfig(account=VSAccount(username="fixture@example.test", password="synthetic-password")))
  35. plugin.set_log(Mock())
  36. self.addCleanup(plugin.cleanup)
  37. stack.enter_context(patch("utils.plugin_utils.ChromiumOptions", FakeChromiumOptions))
  38. stack.enter_context(patch("utils.plugin_utils.get_free_port", return_value=9900))
  39. stack.enter_context(patch.object(ita, "ChromiumPage", return_value=page))
  40. stack.enter_context(patch.object(ita, "HumanMouse", FakeMouse))
  41. stack.enter_context(patch.object(ita, "HumanKeyboard", FakeKeyboard))
  42. stack.enter_context(patch.object(ita.time, "sleep"))
  43. return plugin
  44. def test_login_uses_tls_host_engine_with_no_stuck_refresh(self):
  45. page = FakePage()
  46. plugin = self.setup_plugin(page)
  47. plugin.create_session()
  48. flow = ita.ItaLoginFlow(plugin)
  49. self.assertIs(ita.ItaLoginFlow.run, BaseFlow.run)
  50. self.assertIsNone(flow.max_stuck_cycles)
  51. self.assertEqual(flow.interval, 3)
  52. self.assertTrue(plugin.is_healthy)
  53. self.assertEqual(page.refresh_calls, 0)
  54. self.assertEqual(page.clicked.count("submit"), 1)
  55. def test_delayed_password_control_does_not_partially_fill_or_repeat_credentials(self):
  56. page = DelayedFormPage()
  57. plugin = self.setup_plugin(page)
  58. plugin.create_session()
  59. self.assertEqual(page.password_reads, 3)
  60. self.assertEqual(page.clicked, ["login", "username", "password", "submit"])
  61. self.assertTrue(plugin.is_healthy)
  62. def test_foreign_origin_or_port_never_receives_credentials(self):
  63. for url in ("https://untrusted.example/signin/", "https://iam.esteri.it.attacker.example/signin/",
  64. "http://iam.esteri.it/signin/", "https://iam.esteri.it:8443/signin/",
  65. "https://userinfo-secret@iam.esteri.it/signin/"):
  66. with self.subTest(url=url):
  67. page = FakePage()
  68. page.URLS = {**page.URLS, "pingid": url}
  69. plugin = self.setup_plugin(page)
  70. with self.assertRaisesRegex(BizLogicError, "left the expected website") as caught:
  71. plugin.create_session()
  72. self.assertEqual(page.input_values, {})
  73. self.assertEqual(page.clicked, ["login"])
  74. self.assertFalse(plugin.is_healthy)
  75. def test_explicit_default_https_port_is_accepted(self):
  76. page = FakePage()
  77. page.URLS = {**page.URLS, "pingid": "https://iam.esteri.it:443/signin/?state=private-state"}
  78. plugin = self.setup_plugin(page)
  79. plugin.create_session()
  80. self.assertTrue(plugin.is_healthy)
  81. def test_stalled_login_keeps_once_only_submission(self):
  82. page = FakePage(submit_succeeds=False)
  83. plugin = self.setup_plugin(page)
  84. with self.assertRaisesRegex(BizLogicError, "流程步数耗尽") as caught:
  85. plugin.create_session()
  86. output = str(caught.exception) + "\n".join(c.args[0] for c in plugin.logger.call_args_list)
  87. self.assertNotIn("synthetic-password", output)
  88. self.assertEqual(page.clicked.count("submit"), 1)
  89. self.assertEqual(page.refresh_calls, 0)
  90. self.assertFalse(plugin.is_healthy)
  91. def test_server_error_after_entry_does_not_refresh_or_submit(self):
  92. page = ServerErrorPage()
  93. plugin = self.setup_plugin(page)
  94. with self.assertRaisesRegex(BizLogicError, "failed after login started"):
  95. plugin.create_session()
  96. self.assertEqual(page.clicked, ["login"])
  97. self.assertEqual(page.input_values, {})
  98. self.assertEqual(page.refresh_calls, 0)
  99. def test_stale_dashboard_on_wrong_host_is_not_authentication(self):
  100. page = FakePage()
  101. page.URLS = {**page.URLS, "dashboard": "https://untrusted.example/UserArea"}
  102. plugin = self.setup_plugin(page)
  103. with self.assertRaisesRegex(BizLogicError, "left the expected website"):
  104. plugin.create_session()
  105. self.assertFalse(plugin.is_healthy)
  106. def test_framework_login_errors_keep_their_original_category(self):
  107. for error_type in (SessionExpiredOrInvalidError, RateLimiteddError,
  108. PermissionDeniedError, NotFoundError, BizLogicError):
  109. with self.subTest(error_type=error_type):
  110. plugin = self.setup_plugin(FakePage())
  111. error = error_type("synthetic failure")
  112. with patch.object(ita.ItaLoginFlow, "run", side_effect=error), \
  113. self.assertRaises(error_type) as caught:
  114. plugin.create_session()
  115. self.assertIs(caught.exception, error)
  116. self.assertFalse(plugin.is_healthy)
  117. def test_missing_credentials_fail_before_starting_browser(self):
  118. for field, value in (("username", ""), ("username", " "),
  119. ("username", None), ("password", ""), ("password", None)):
  120. with self.subTest(field=field, value=value):
  121. plugin = self.setup_plugin(FakePage())
  122. setattr(plugin.config.account, field, value)
  123. with patch.object(ita, "init_chromium_options") as options, \
  124. patch.object(ita, "ChromiumPage") as browser, \
  125. self.assertRaisesRegex(BizLogicError, "username and password"):
  126. plugin.create_session()
  127. options.assert_not_called()
  128. browser.assert_not_called()
  129. self.assertFalse(plugin.is_healthy)
  130. def test_login_preserves_the_configured_password_including_spaces(self):
  131. page = FakePage()
  132. plugin = self.setup_plugin(page)
  133. plugin.config.account.password = " fixture password "
  134. plugin.create_session()
  135. self.assertEqual(plugin.config.account.password, " fixture password ")
  136. self.assertIn(" fixture password ", [item["value"] for item in page.input_values.values()])
  137. if __name__ == "__main__":
  138. unittest.main()