| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195 |
- import ast
- import io
- import json
- import tempfile
- import unittest
- from contextlib import redirect_stderr, redirect_stdout
- from pathlib import Path
- from unittest.mock import patch
- from tools.debug_ita_session import (
- DebugConfigurationError,
- _text_for_log,
- _url_for_log,
- build_local_query_session_config,
- build_plugin_config,
- run_preflight,
- run_session,
- )
- class FakeDebugElement:
- pass
- class FakeDebugPage:
- url = (
- "https://prenotami.esteri.it/UserArea"
- "?state=sensitive-state#sensitive-fragment"
- )
- def ele(self, selector, timeout=None):
- del timeout
- if selector in {".app-menu", "@href=/Services"}:
- return FakeDebugElement()
- return None
- class FakeDebugPlugin:
- last_instance = None
- def __init__(self, group_id):
- self.group_id = group_id
- self.page = FakeDebugPage()
- self.instance_id = "offline"
- self.cleanup_called = False
- FakeDebugPlugin.last_instance = self
- def set_log(self, logger):
- self.logger = logger
- def set_config(self, config):
- self.config = config
- def create_session(self):
- return None
- def cleanup(self):
- self.cleanup_called = True
- class DebugItaSessionConfigTests(unittest.TestCase):
- def test_builds_login_only_config_without_proxy_or_service_id(self):
- config = build_plugin_config({}, username="test@example.com", password="secret")
- self.assertEqual(config.account.username, "test@example.com")
- self.assertEqual(config.proxy.ip, "")
- self.assertEqual(config.free_config, {})
- self.assertEqual(config.session_max_life, 900)
- def test_rejects_partial_authenticated_proxy(self):
- env = {
- "ITA_PROXY_IP": "127.0.0.1",
- "ITA_PROXY_PORT": "8080",
- "ITA_PROXY_USERNAME": "proxy-user",
- }
- with self.assertRaisesRegex(
- DebugConfigurationError,
- "ITA_PROXY_USERNAME and ITA_PROXY_PASSWORD",
- ):
- build_plugin_config(env, username="test@example.com", password="secret")
- def test_rejects_proxy_without_port(self):
- with self.assertRaisesRegex(DebugConfigurationError, "ITA_PROXY_PORT"):
- build_plugin_config(
- {"ITA_PROXY_IP": "127.0.0.1"},
- username="test@example.com",
- password="secret",
- )
- def test_preflight_does_not_require_credentials(self):
- chrome_path = Path("/test/chrome")
- with patch("tools.debug_ita_session.resolve_chrome_path", return_value=chrome_path):
- self.assertEqual(run_preflight({}), 0)
- def test_local_query_login_config_uses_the_private_persistent_profile(self):
- local_values = {
- "username": "local-query@example.test",
- "password": "offline-password",
- "account_upload_token": "",
- }
- repo_root = Path(__file__).resolve().parents[1]
- with tempfile.TemporaryDirectory(dir=repo_root) as temp_dir:
- config_path = Path(temp_dir) / "ita_query_account.local.json"
- config_path.write_text(json.dumps(local_values), encoding="utf-8")
- config_path.chmod(0o600)
- profile_path = Path(temp_dir) / "profile"
- profile_path.mkdir(mode=0o700)
- with (
- patch(
- "tools.debug_ita_session.ITA_QUERY_ACCOUNT_FILE",
- config_path,
- ),
- patch(
- "tools.debug_ita_session.prepare_ita_query_profile",
- return_value=profile_path,
- ),
- ):
- config = build_local_query_session_config({})
- self.assertEqual(config.account.username, local_values["username"])
- self.assertEqual(
- config.free_config["persistent_browser_profile_path"],
- str(profile_path),
- )
- class DebugItaSessionSafetyTests(unittest.TestCase):
- def test_url_logging_removes_dynamic_oauth_values(self):
- self.assertEqual(
- _url_for_log(
- "https://iam.esteri.it/signin/"
- "?state=sensitive-state&code_challenge=sensitive-challenge#/"
- ),
- "https://iam.esteri.it/signin/",
- )
- sanitized = _text_for_log(
- "failed at https://iam.esteri.it/signin/"
- "https%3A%2F%2Fiam.esteri.it%2Flogin"
- "?state=sensitive-state&code_challenge=sensitive-challenge"
- )
- self.assertIn("https://iam.esteri.it/signin/<redacted>", sanitized)
- self.assertNotIn("sensitive-state", sanitized)
- self.assertNotIn("sensitive-challenge", sanitized)
- def test_run_session_requires_user_area_markers_and_sanitizes_success_url(self):
- stdout = io.StringIO()
- stderr = io.StringIO()
- env = {
- "ITA_USERNAME": "offline-test@example.test",
- "ITA_PASSWORD": "offline-password",
- }
- with (
- patch(
- "tools.debug_ita_session.resolve_chrome_path",
- return_value=Path("/test/chrome"),
- ),
- patch("tools.debug_ita_session.ItaPlugin", FakeDebugPlugin),
- patch.dict("tools.debug_ita_session.os.environ", {}, clear=False),
- redirect_stdout(stdout),
- redirect_stderr(stderr),
- ):
- exit_code = run_session(env, non_interactive=True)
- self.assertEqual(exit_code, 0)
- self.assertIn(
- "ITA_SESSION_OK url=https://prenotami.esteri.it/UserArea",
- stdout.getvalue(),
- )
- self.assertIn("ITA_SESSION_CLEANUP_OK", stdout.getvalue())
- self.assertNotIn("sensitive-state", stdout.getvalue())
- self.assertNotIn("sensitive-fragment", stdout.getvalue())
- self.assertEqual(stderr.getvalue(), "")
- self.assertTrue(FakeDebugPlugin.last_instance.cleanup_called)
- def test_debug_entrypoint_never_calls_query_or_book(self):
- source_path = (
- Path(__file__).resolve().parents[1] / "tools" / "debug_ita_session.py"
- )
- tree = ast.parse(source_path.read_text(encoding="utf-8"))
- forbidden_calls = [
- node.func.attr
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and isinstance(node.func, ast.Attribute)
- and node.func.attr in {"query", "book"}
- ]
- self.assertEqual(forbidden_calls, [])
- if __name__ == "__main__":
- unittest.main()
|