test_debug_ita_session.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import ast
  2. import io
  3. import json
  4. import tempfile
  5. import unittest
  6. from contextlib import redirect_stderr, redirect_stdout
  7. from pathlib import Path
  8. from unittest.mock import patch
  9. from tools.debug_ita_session import (
  10. DebugConfigurationError,
  11. _text_for_log,
  12. _url_for_log,
  13. build_local_query_session_config,
  14. build_plugin_config,
  15. run_preflight,
  16. run_session,
  17. )
  18. class FakeDebugElement:
  19. pass
  20. class FakeDebugPage:
  21. url = (
  22. "https://prenotami.esteri.it/UserArea"
  23. "?state=sensitive-state#sensitive-fragment"
  24. )
  25. def ele(self, selector, timeout=None):
  26. del timeout
  27. if selector in {".app-menu", "@href=/Services"}:
  28. return FakeDebugElement()
  29. return None
  30. class FakeDebugPlugin:
  31. last_instance = None
  32. def __init__(self, group_id):
  33. self.group_id = group_id
  34. self.page = FakeDebugPage()
  35. self.instance_id = "offline"
  36. self.cleanup_called = False
  37. FakeDebugPlugin.last_instance = self
  38. def set_log(self, logger):
  39. self.logger = logger
  40. def set_config(self, config):
  41. self.config = config
  42. def create_session(self):
  43. return None
  44. def cleanup(self):
  45. self.cleanup_called = True
  46. class DebugItaSessionConfigTests(unittest.TestCase):
  47. def test_builds_login_only_config_without_proxy_or_service_id(self):
  48. config = build_plugin_config({}, username="test@example.com", password="secret")
  49. self.assertEqual(config.account.username, "test@example.com")
  50. self.assertEqual(config.proxy.ip, "")
  51. self.assertEqual(config.free_config, {})
  52. self.assertEqual(config.session_max_life, 900)
  53. def test_rejects_partial_authenticated_proxy(self):
  54. env = {
  55. "ITA_PROXY_IP": "127.0.0.1",
  56. "ITA_PROXY_PORT": "8080",
  57. "ITA_PROXY_USERNAME": "proxy-user",
  58. }
  59. with self.assertRaisesRegex(
  60. DebugConfigurationError,
  61. "ITA_PROXY_USERNAME and ITA_PROXY_PASSWORD",
  62. ):
  63. build_plugin_config(env, username="test@example.com", password="secret")
  64. def test_rejects_proxy_without_port(self):
  65. with self.assertRaisesRegex(DebugConfigurationError, "ITA_PROXY_PORT"):
  66. build_plugin_config(
  67. {"ITA_PROXY_IP": "127.0.0.1"},
  68. username="test@example.com",
  69. password="secret",
  70. )
  71. def test_preflight_does_not_require_credentials(self):
  72. chrome_path = Path("/test/chrome")
  73. with patch("tools.debug_ita_session.resolve_chrome_path", return_value=chrome_path):
  74. self.assertEqual(run_preflight({}), 0)
  75. def test_local_query_login_config_uses_the_private_persistent_profile(self):
  76. local_values = {
  77. "username": "local-query@example.test",
  78. "password": "offline-password",
  79. "account_upload_token": "",
  80. }
  81. repo_root = Path(__file__).resolve().parents[1]
  82. with tempfile.TemporaryDirectory(dir=repo_root) as temp_dir:
  83. config_path = Path(temp_dir) / "ita_query_account.local.json"
  84. config_path.write_text(json.dumps(local_values), encoding="utf-8")
  85. config_path.chmod(0o600)
  86. profile_path = Path(temp_dir) / "profile"
  87. profile_path.mkdir(mode=0o700)
  88. with (
  89. patch(
  90. "tools.debug_ita_session.ITA_QUERY_ACCOUNT_FILE",
  91. config_path,
  92. ),
  93. patch(
  94. "tools.debug_ita_session.prepare_ita_query_profile",
  95. return_value=profile_path,
  96. ),
  97. ):
  98. config = build_local_query_session_config({})
  99. self.assertEqual(config.account.username, local_values["username"])
  100. self.assertEqual(
  101. config.free_config["persistent_browser_profile_path"],
  102. str(profile_path),
  103. )
  104. class DebugItaSessionSafetyTests(unittest.TestCase):
  105. def test_url_logging_removes_dynamic_oauth_values(self):
  106. self.assertEqual(
  107. _url_for_log(
  108. "https://iam.esteri.it/signin/"
  109. "?state=sensitive-state&code_challenge=sensitive-challenge#/"
  110. ),
  111. "https://iam.esteri.it/signin/",
  112. )
  113. sanitized = _text_for_log(
  114. "failed at https://iam.esteri.it/signin/"
  115. "https%3A%2F%2Fiam.esteri.it%2Flogin"
  116. "?state=sensitive-state&code_challenge=sensitive-challenge"
  117. )
  118. self.assertIn("https://iam.esteri.it/signin/<redacted>", sanitized)
  119. self.assertNotIn("sensitive-state", sanitized)
  120. self.assertNotIn("sensitive-challenge", sanitized)
  121. def test_run_session_requires_user_area_markers_and_sanitizes_success_url(self):
  122. stdout = io.StringIO()
  123. stderr = io.StringIO()
  124. env = {
  125. "ITA_USERNAME": "offline-test@example.test",
  126. "ITA_PASSWORD": "offline-password",
  127. }
  128. with (
  129. patch(
  130. "tools.debug_ita_session.resolve_chrome_path",
  131. return_value=Path("/test/chrome"),
  132. ),
  133. patch("tools.debug_ita_session.ItaPlugin", FakeDebugPlugin),
  134. patch.dict("tools.debug_ita_session.os.environ", {}, clear=False),
  135. redirect_stdout(stdout),
  136. redirect_stderr(stderr),
  137. ):
  138. exit_code = run_session(env, non_interactive=True)
  139. self.assertEqual(exit_code, 0)
  140. self.assertIn(
  141. "ITA_SESSION_OK url=https://prenotami.esteri.it/UserArea",
  142. stdout.getvalue(),
  143. )
  144. self.assertIn("ITA_SESSION_CLEANUP_OK", stdout.getvalue())
  145. self.assertNotIn("sensitive-state", stdout.getvalue())
  146. self.assertNotIn("sensitive-fragment", stdout.getvalue())
  147. self.assertEqual(stderr.getvalue(), "")
  148. self.assertTrue(FakeDebugPlugin.last_instance.cleanup_called)
  149. def test_debug_entrypoint_never_calls_query_or_book(self):
  150. source_path = (
  151. Path(__file__).resolve().parents[1] / "tools" / "debug_ita_session.py"
  152. )
  153. tree = ast.parse(source_path.read_text(encoding="utf-8"))
  154. forbidden_calls = [
  155. node.func.attr
  156. for node in ast.walk(tree)
  157. if isinstance(node, ast.Call)
  158. and isinstance(node.func, ast.Attribute)
  159. and node.func.attr in {"query", "book"}
  160. ]
  161. self.assertEqual(forbidden_calls, [])
  162. if __name__ == "__main__":
  163. unittest.main()