debug_ita_session.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. #!/usr/bin/env python3
  2. """Run an isolated Italy-plugin login session without querying or booking.
  3. Credentials are read from environment variables or interactive prompts. They are
  4. never accepted as command-line arguments, which keeps them out of shell history
  5. and process listings.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import getpass
  10. import os
  11. import re
  12. import sys
  13. import traceback
  14. from datetime import datetime
  15. from pathlib import Path
  16. from typing import Mapping
  17. from urllib.parse import urlparse
  18. REPO_ROOT = Path(__file__).resolve().parents[1]
  19. if str(REPO_ROOT) not in sys.path:
  20. sys.path.insert(0, str(REPO_ROOT))
  21. import configure
  22. from plugins.ita_plugin import PERSISTENT_BROWSER_PROFILE_KEY, ItaPlugin
  23. from utils.ita_local_profile import (
  24. ITA_QUERY_ACCOUNT_FILE,
  25. ItaLocalProfileError,
  26. prepare_ita_query_profile,
  27. )
  28. from utils.local_account import LocalAccountConfigurationError, load_local_account
  29. from vs_types import VSAccount, VSPlgConfig, VSProxy
  30. MACOS_CHROME_PATH = Path(
  31. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
  32. )
  33. class DebugConfigurationError(ValueError):
  34. """Raised when the isolated debug session is configured unsafely."""
  35. _URL_PATTERN = re.compile(r"https?://[^\s\"'<>]+")
  36. _DYNAMIC_OAUTH_PARAMETER_PATTERN = re.compile(
  37. r"\b(state|code|code_challenge|goto)=([^&\s]+)",
  38. re.IGNORECASE,
  39. )
  40. def _url_for_log(raw_url: str) -> str:
  41. parsed = urlparse(str(raw_url or ""))
  42. path = parsed.path or "/"
  43. if path.startswith("/signin/") and path != "/signin/":
  44. path = "/signin/<redacted>"
  45. if parsed.scheme and parsed.netloc:
  46. return f"{parsed.scheme}://{parsed.netloc}{path}"
  47. return path
  48. def _text_for_log(value: object) -> str:
  49. sanitized = _URL_PATTERN.sub(
  50. lambda match: _url_for_log(match.group(0)),
  51. str(value),
  52. )
  53. return _DYNAMIC_OAUTH_PARAMETER_PATTERN.sub(
  54. lambda match: f"{match.group(1)}=<redacted>",
  55. sanitized,
  56. )
  57. def _env_text(env: Mapping[str, str], name: str) -> str:
  58. return env.get(name, "").strip()
  59. def _env_int(
  60. env: Mapping[str, str],
  61. name: str,
  62. *,
  63. default: int,
  64. minimum: int = 0,
  65. ) -> int:
  66. raw_value = _env_text(env, name)
  67. if not raw_value:
  68. return default
  69. try:
  70. value = int(raw_value)
  71. except ValueError as exc:
  72. raise DebugConfigurationError(f"{name} must be an integer") from exc
  73. if value < minimum:
  74. raise DebugConfigurationError(f"{name} must be >= {minimum}")
  75. return value
  76. def _env_bool(env: Mapping[str, str], name: str, *, default: bool) -> bool:
  77. raw_value = _env_text(env, name).lower()
  78. if not raw_value:
  79. return default
  80. if raw_value in {"1", "true", "yes", "on"}:
  81. return True
  82. if raw_value in {"0", "false", "no", "off"}:
  83. return False
  84. raise DebugConfigurationError(
  85. f"{name} must be one of: 1/0, true/false, yes/no, on/off"
  86. )
  87. def resolve_chrome_path(env: Mapping[str, str]) -> Path:
  88. candidates = [
  89. getattr(configure, "CHROME_PATH", None),
  90. _env_text(env, "CHROME_BIN"),
  91. str(MACOS_CHROME_PATH),
  92. ]
  93. for candidate in candidates:
  94. if candidate:
  95. path = Path(candidate).expanduser().resolve()
  96. if path.is_file() and os.access(path, os.X_OK):
  97. return path
  98. raise DebugConfigurationError(
  99. "Chromium executable not found. Set CHROME_BIN to an executable browser."
  100. )
  101. def resolve_mihomo_path(env: Mapping[str, str]) -> Path:
  102. candidates = [
  103. getattr(configure, "MIHOMO_BIN_PATH", None),
  104. _env_text(env, "MIHOMO_BIN"),
  105. ]
  106. for candidate in candidates:
  107. if candidate:
  108. path = Path(candidate).expanduser().resolve()
  109. if path.is_file() and os.access(path, os.X_OK):
  110. return path
  111. raise DebugConfigurationError(
  112. "Authenticated proxy requires an executable Mihomo binary. Set MIHOMO_BIN."
  113. )
  114. def validate_proxy_settings(
  115. env: Mapping[str, str],
  116. ) -> tuple[str, int, str, str]:
  117. proxy_ip = _env_text(env, "ITA_PROXY_IP")
  118. proxy_username = _env_text(env, "ITA_PROXY_USERNAME")
  119. proxy_password = _env_text(env, "ITA_PROXY_PASSWORD")
  120. proxy_port = _env_int(
  121. env,
  122. "ITA_PROXY_PORT",
  123. default=0,
  124. minimum=0,
  125. )
  126. if not proxy_ip and (proxy_port or proxy_username or proxy_password):
  127. raise DebugConfigurationError(
  128. "ITA_PROXY_IP is required when other proxy settings are present"
  129. )
  130. if proxy_ip and proxy_port <= 0:
  131. raise DebugConfigurationError(
  132. "ITA_PROXY_PORT must be greater than zero when ITA_PROXY_IP is set"
  133. )
  134. if bool(proxy_username) != bool(proxy_password):
  135. raise DebugConfigurationError(
  136. "ITA_PROXY_USERNAME and ITA_PROXY_PASSWORD must be provided together"
  137. )
  138. if proxy_username:
  139. resolve_mihomo_path(env)
  140. return proxy_ip, proxy_port, proxy_username, proxy_password
  141. def build_plugin_config(
  142. env: Mapping[str, str],
  143. *,
  144. username: str,
  145. password: str,
  146. ) -> VSPlgConfig:
  147. username = username.strip()
  148. if not username:
  149. raise DebugConfigurationError("Italy test username is required")
  150. if not password:
  151. raise DebugConfigurationError("Italy test password is required")
  152. proxy_ip, proxy_port, proxy_username, proxy_password = validate_proxy_settings(env)
  153. service_id = _env_int(env, "ITA_SERVICE_ID", default=0, minimum=0)
  154. free_config = {"service_id": service_id} if service_id else {}
  155. return VSPlgConfig(
  156. debug=_env_bool(env, "ITA_DEBUG", default=False),
  157. account=VSAccount(
  158. id=_env_int(env, "ITA_ACCOUNT_ID", default=0, minimum=0),
  159. username=username,
  160. password=password,
  161. ),
  162. proxy=VSProxy(
  163. id=_env_int(env, "ITA_PROXY_ID", default=0, minimum=0),
  164. proto=_env_text(env, "ITA_PROXY_PROTO") or "http",
  165. ip=proxy_ip,
  166. port=proxy_port,
  167. username=proxy_username,
  168. password=proxy_password,
  169. ),
  170. free_config=free_config,
  171. session_max_life=_env_int(
  172. env,
  173. "ITA_SESSION_MAX_LIFE",
  174. default=900,
  175. minimum=1,
  176. ),
  177. )
  178. def _credential_status(env: Mapping[str, str]) -> str:
  179. username_set = bool(_env_text(env, "ITA_USERNAME"))
  180. password_set = bool(env.get("ITA_PASSWORD", ""))
  181. return "ready" if username_set and password_set else "missing"
  182. def _proxy_status(env: Mapping[str, str]) -> str:
  183. if not _env_text(env, "ITA_PROXY_IP"):
  184. return "none"
  185. if _env_text(env, "ITA_PROXY_USERNAME"):
  186. return "authenticated"
  187. return "direct"
  188. def run_preflight(env: Mapping[str, str]) -> int:
  189. chrome_path = resolve_chrome_path(env)
  190. validate_proxy_settings(env)
  191. proxy_status = _proxy_status(env)
  192. mihomo_status = "not-required"
  193. if proxy_status == "authenticated":
  194. mihomo_status = str(resolve_mihomo_path(env))
  195. print("ITA_PREFLIGHT_OK")
  196. print(f"python={sys.version.split()[0]}")
  197. print(f"chrome={chrome_path}")
  198. print(f"credentials={_credential_status(env)}")
  199. print(f"proxy={proxy_status}")
  200. print(f"mihomo={mihomo_status}")
  201. print(f"service_id={'set' if _env_text(env, 'ITA_SERVICE_ID') else 'not-required-for-login'}")
  202. print("external_request=not-performed")
  203. return 0
  204. def _get_credentials(env: Mapping[str, str], *, non_interactive: bool) -> tuple[str, str]:
  205. username = _env_text(env, "ITA_USERNAME")
  206. password = env.get("ITA_PASSWORD", "")
  207. if username and password:
  208. return username, password
  209. if non_interactive or not sys.stdin.isatty():
  210. raise DebugConfigurationError(
  211. "Set ITA_USERNAME and ITA_PASSWORD, or run interactively to enter them."
  212. )
  213. if not username:
  214. username = input("Italy test username: ").strip()
  215. if not password:
  216. password = getpass.getpass("Italy test password: ")
  217. return username, password
  218. def build_local_query_session_config(env: Mapping[str, str]) -> VSPlgConfig:
  219. """Build a login-only config that shares the private local Query profile."""
  220. try:
  221. account = load_local_account(ITA_QUERY_ACCOUNT_FILE)
  222. profile_path = prepare_ita_query_profile(account.username)
  223. except (LocalAccountConfigurationError, ItaLocalProfileError) as exc:
  224. raise DebugConfigurationError(
  225. "Local Italy Query session configuration is invalid"
  226. ) from exc
  227. config = build_plugin_config(
  228. env,
  229. username=account.username,
  230. password=account.password,
  231. )
  232. config.free_config = {
  233. **config.free_config,
  234. PERSISTENT_BROWSER_PROFILE_KEY: str(profile_path),
  235. }
  236. return config
  237. def _save_failure_diagnostics(plugin: ItaPlugin, output_dir: Path) -> None:
  238. page = getattr(plugin, "page", None)
  239. if page is None:
  240. print("diagnostic_page=not-created")
  241. return
  242. try:
  243. print(f"diagnostic_url={_url_for_log(page.url)}")
  244. except Exception as exc:
  245. print(
  246. "diagnostic_url=unavailable "
  247. f"({type(exc).__name__}: {_text_for_log(exc)})"
  248. )
  249. try:
  250. print(f"diagnostic_title={page.title}")
  251. except Exception as exc:
  252. print(
  253. "diagnostic_title=unavailable "
  254. f"({type(exc).__name__}: {_text_for_log(exc)})"
  255. )
  256. output_dir.mkdir(parents=True, exist_ok=True)
  257. timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
  258. screenshot_path = output_dir / f"ita-{plugin.instance_id}-{timestamp}.png"
  259. try:
  260. page.get_screenshot(path=str(screenshot_path), full_page=False)
  261. print(f"diagnostic_screenshot={screenshot_path}")
  262. except Exception as exc:
  263. print(
  264. "diagnostic_screenshot=failed "
  265. f"({type(exc).__name__}: {_text_for_log(exc)})"
  266. )
  267. def run_session(
  268. env: Mapping[str, str],
  269. *,
  270. non_interactive: bool,
  271. use_local_query_profile: bool = False,
  272. ) -> int:
  273. chrome_path = resolve_chrome_path(env)
  274. os.environ["CHROME_BIN"] = str(chrome_path)
  275. if use_local_query_profile:
  276. config = build_local_query_session_config(env)
  277. else:
  278. username, password = _get_credentials(
  279. env,
  280. non_interactive=non_interactive,
  281. )
  282. config = build_plugin_config(env, username=username, password=password)
  283. output_dir = Path(
  284. _env_text(env, "ITA_DEBUG_OUTPUT_DIR") or REPO_ROOT / "data" / "ita_debug"
  285. ).expanduser()
  286. plugin = ItaPlugin(group_id="ita-local-debug")
  287. plugin.set_log(lambda message: print(message, flush=True))
  288. plugin.set_config(config)
  289. exit_code = 0
  290. cleanup_error: Exception | None = None
  291. try:
  292. plugin.create_session()
  293. page = plugin.page
  294. current_url = page.url if page else ""
  295. current_path = urlparse(current_url).path.rstrip("/") or "/"
  296. has_app_menu = bool(page and page.ele(".app-menu", timeout=0.5))
  297. has_services_link = bool(page and page.ele("@href=/Services", timeout=0.5))
  298. if (
  299. current_path != "/UserArea"
  300. or not has_app_menu
  301. or not has_services_link
  302. ):
  303. raise RuntimeError(
  304. "create_session returned without authenticated /UserArea "
  305. f"markers: {_url_for_log(current_url)}"
  306. )
  307. print(f"ITA_SESSION_OK url={_url_for_log(current_url)}")
  308. except Exception as exc:
  309. print(
  310. f"ITA_SESSION_FAILED type={type(exc).__name__} "
  311. f"message={_text_for_log(exc)}"
  312. )
  313. _save_failure_diagnostics(plugin, output_dir)
  314. sanitized_traceback = _text_for_log(
  315. "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
  316. )
  317. print(sanitized_traceback, file=sys.stderr, end="")
  318. exit_code = 1
  319. finally:
  320. try:
  321. plugin.cleanup()
  322. print("ITA_SESSION_CLEANUP_OK")
  323. except Exception as exc:
  324. cleanup_error = exc
  325. print(
  326. f"ITA_SESSION_CLEANUP_FAILED type={type(exc).__name__} "
  327. f"message={_text_for_log(exc)}",
  328. file=sys.stderr,
  329. )
  330. return 3 if cleanup_error is not None else exit_code
  331. def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
  332. parser = argparse.ArgumentParser(
  333. description="Isolated Italy plugin login debugger (never queries or books)."
  334. )
  335. parser.add_argument(
  336. "--preflight",
  337. action="store_true",
  338. help="Check the local runtime without opening a browser or making a request.",
  339. )
  340. parser.add_argument(
  341. "--non-interactive",
  342. action="store_true",
  343. help="Fail instead of prompting when credentials are missing.",
  344. )
  345. parser.add_argument(
  346. "--local-query-account",
  347. action="store_true",
  348. help=(
  349. "Use the ignored local Italy Query account and its persistent "
  350. "browser profile; still performs login only."
  351. ),
  352. )
  353. return parser.parse_args(argv)
  354. def main(argv: list[str] | None = None) -> int:
  355. args = parse_args(argv)
  356. try:
  357. if args.preflight:
  358. return run_preflight(os.environ)
  359. return run_session(
  360. os.environ,
  361. non_interactive=args.non_interactive,
  362. use_local_query_profile=args.local_query_account,
  363. )
  364. except DebugConfigurationError as exc:
  365. print(f"ITA_DEBUG_CONFIG_ERROR: {exc}", file=sys.stderr)
  366. return 2
  367. if __name__ == "__main__":
  368. raise SystemExit(main())