#!/usr/bin/env python3 """Run an isolated Italy-plugin login session without querying or booking. Credentials are read from environment variables or interactive prompts. They are never accepted as command-line arguments, which keeps them out of shell history and process listings. """ from __future__ import annotations import argparse import getpass import os import re import sys import traceback from datetime import datetime from pathlib import Path from typing import Mapping from urllib.parse import urlparse REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) import configure from plugins.ita_plugin import PERSISTENT_BROWSER_PROFILE_KEY, ItaPlugin from utils.ita_local_profile import ( ITA_QUERY_ACCOUNT_FILE, ItaLocalProfileError, prepare_ita_query_profile, ) from utils.local_account import LocalAccountConfigurationError, load_local_account from vs_types import VSAccount, VSPlgConfig, VSProxy MACOS_CHROME_PATH = Path( "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ) class DebugConfigurationError(ValueError): """Raised when the isolated debug session is configured unsafely.""" _URL_PATTERN = re.compile(r"https?://[^\s\"'<>]+") _DYNAMIC_OAUTH_PARAMETER_PATTERN = re.compile( r"\b(state|code|code_challenge|goto)=([^&\s]+)", re.IGNORECASE, ) def _url_for_log(raw_url: str) -> str: parsed = urlparse(str(raw_url or "")) path = parsed.path or "/" if path.startswith("/signin/") and path != "/signin/": path = "/signin/" if parsed.scheme and parsed.netloc: return f"{parsed.scheme}://{parsed.netloc}{path}" return path def _text_for_log(value: object) -> str: sanitized = _URL_PATTERN.sub( lambda match: _url_for_log(match.group(0)), str(value), ) return _DYNAMIC_OAUTH_PARAMETER_PATTERN.sub( lambda match: f"{match.group(1)}=", sanitized, ) def _env_text(env: Mapping[str, str], name: str) -> str: return env.get(name, "").strip() def _env_int( env: Mapping[str, str], name: str, *, default: int, minimum: int = 0, ) -> int: raw_value = _env_text(env, name) if not raw_value: return default try: value = int(raw_value) except ValueError as exc: raise DebugConfigurationError(f"{name} must be an integer") from exc if value < minimum: raise DebugConfigurationError(f"{name} must be >= {minimum}") return value def _env_bool(env: Mapping[str, str], name: str, *, default: bool) -> bool: raw_value = _env_text(env, name).lower() if not raw_value: return default if raw_value in {"1", "true", "yes", "on"}: return True if raw_value in {"0", "false", "no", "off"}: return False raise DebugConfigurationError( f"{name} must be one of: 1/0, true/false, yes/no, on/off" ) def resolve_chrome_path(env: Mapping[str, str]) -> Path: candidates = [ getattr(configure, "CHROME_PATH", None), _env_text(env, "CHROME_BIN"), str(MACOS_CHROME_PATH), ] for candidate in candidates: if candidate: path = Path(candidate).expanduser().resolve() if path.is_file() and os.access(path, os.X_OK): return path raise DebugConfigurationError( "Chromium executable not found. Set CHROME_BIN to an executable browser." ) def resolve_mihomo_path(env: Mapping[str, str]) -> Path: candidates = [ getattr(configure, "MIHOMO_BIN_PATH", None), _env_text(env, "MIHOMO_BIN"), ] for candidate in candidates: if candidate: path = Path(candidate).expanduser().resolve() if path.is_file() and os.access(path, os.X_OK): return path raise DebugConfigurationError( "Authenticated proxy requires an executable Mihomo binary. Set MIHOMO_BIN." ) def validate_proxy_settings( env: Mapping[str, str], ) -> tuple[str, int, str, str]: proxy_ip = _env_text(env, "ITA_PROXY_IP") proxy_username = _env_text(env, "ITA_PROXY_USERNAME") proxy_password = _env_text(env, "ITA_PROXY_PASSWORD") proxy_port = _env_int( env, "ITA_PROXY_PORT", default=0, minimum=0, ) if not proxy_ip and (proxy_port or proxy_username or proxy_password): raise DebugConfigurationError( "ITA_PROXY_IP is required when other proxy settings are present" ) if proxy_ip and proxy_port <= 0: raise DebugConfigurationError( "ITA_PROXY_PORT must be greater than zero when ITA_PROXY_IP is set" ) if bool(proxy_username) != bool(proxy_password): raise DebugConfigurationError( "ITA_PROXY_USERNAME and ITA_PROXY_PASSWORD must be provided together" ) if proxy_username: resolve_mihomo_path(env) return proxy_ip, proxy_port, proxy_username, proxy_password def build_plugin_config( env: Mapping[str, str], *, username: str, password: str, ) -> VSPlgConfig: username = username.strip() if not username: raise DebugConfigurationError("Italy test username is required") if not password: raise DebugConfigurationError("Italy test password is required") proxy_ip, proxy_port, proxy_username, proxy_password = validate_proxy_settings(env) service_id = _env_int(env, "ITA_SERVICE_ID", default=0, minimum=0) free_config = {"service_id": service_id} if service_id else {} return VSPlgConfig( debug=_env_bool(env, "ITA_DEBUG", default=False), account=VSAccount( id=_env_int(env, "ITA_ACCOUNT_ID", default=0, minimum=0), username=username, password=password, ), proxy=VSProxy( id=_env_int(env, "ITA_PROXY_ID", default=0, minimum=0), proto=_env_text(env, "ITA_PROXY_PROTO") or "http", ip=proxy_ip, port=proxy_port, username=proxy_username, password=proxy_password, ), free_config=free_config, session_max_life=_env_int( env, "ITA_SESSION_MAX_LIFE", default=900, minimum=1, ), ) def _credential_status(env: Mapping[str, str]) -> str: username_set = bool(_env_text(env, "ITA_USERNAME")) password_set = bool(env.get("ITA_PASSWORD", "")) return "ready" if username_set and password_set else "missing" def _proxy_status(env: Mapping[str, str]) -> str: if not _env_text(env, "ITA_PROXY_IP"): return "none" if _env_text(env, "ITA_PROXY_USERNAME"): return "authenticated" return "direct" def run_preflight(env: Mapping[str, str]) -> int: chrome_path = resolve_chrome_path(env) validate_proxy_settings(env) proxy_status = _proxy_status(env) mihomo_status = "not-required" if proxy_status == "authenticated": mihomo_status = str(resolve_mihomo_path(env)) print("ITA_PREFLIGHT_OK") print(f"python={sys.version.split()[0]}") print(f"chrome={chrome_path}") print(f"credentials={_credential_status(env)}") print(f"proxy={proxy_status}") print(f"mihomo={mihomo_status}") print(f"service_id={'set' if _env_text(env, 'ITA_SERVICE_ID') else 'not-required-for-login'}") print("external_request=not-performed") return 0 def _get_credentials(env: Mapping[str, str], *, non_interactive: bool) -> tuple[str, str]: username = _env_text(env, "ITA_USERNAME") password = env.get("ITA_PASSWORD", "") if username and password: return username, password if non_interactive or not sys.stdin.isatty(): raise DebugConfigurationError( "Set ITA_USERNAME and ITA_PASSWORD, or run interactively to enter them." ) if not username: username = input("Italy test username: ").strip() if not password: password = getpass.getpass("Italy test password: ") return username, password def build_local_query_session_config(env: Mapping[str, str]) -> VSPlgConfig: """Build a login-only config that shares the private local Query profile.""" try: account = load_local_account(ITA_QUERY_ACCOUNT_FILE) profile_path = prepare_ita_query_profile(account.username) except (LocalAccountConfigurationError, ItaLocalProfileError) as exc: raise DebugConfigurationError( "Local Italy Query session configuration is invalid" ) from exc config = build_plugin_config( env, username=account.username, password=account.password, ) config.free_config = { **config.free_config, PERSISTENT_BROWSER_PROFILE_KEY: str(profile_path), } return config def _save_failure_diagnostics(plugin: ItaPlugin, output_dir: Path) -> None: page = getattr(plugin, "page", None) if page is None: print("diagnostic_page=not-created") return try: print(f"diagnostic_url={_url_for_log(page.url)}") except Exception as exc: print( "diagnostic_url=unavailable " f"({type(exc).__name__}: {_text_for_log(exc)})" ) try: print(f"diagnostic_title={page.title}") except Exception as exc: print( "diagnostic_title=unavailable " f"({type(exc).__name__}: {_text_for_log(exc)})" ) output_dir.mkdir(parents=True, exist_ok=True) timestamp = datetime.now().strftime("%Y%m%d-%H%M%S") screenshot_path = output_dir / f"ita-{plugin.instance_id}-{timestamp}.png" try: page.get_screenshot(path=str(screenshot_path), full_page=False) print(f"diagnostic_screenshot={screenshot_path}") except Exception as exc: print( "diagnostic_screenshot=failed " f"({type(exc).__name__}: {_text_for_log(exc)})" ) def run_session( env: Mapping[str, str], *, non_interactive: bool, use_local_query_profile: bool = False, ) -> int: chrome_path = resolve_chrome_path(env) os.environ["CHROME_BIN"] = str(chrome_path) if use_local_query_profile: config = build_local_query_session_config(env) else: username, password = _get_credentials( env, non_interactive=non_interactive, ) config = build_plugin_config(env, username=username, password=password) output_dir = Path( _env_text(env, "ITA_DEBUG_OUTPUT_DIR") or REPO_ROOT / "data" / "ita_debug" ).expanduser() plugin = ItaPlugin(group_id="ita-local-debug") plugin.set_log(lambda message: print(message, flush=True)) plugin.set_config(config) exit_code = 0 cleanup_error: Exception | None = None try: plugin.create_session() page = plugin.page current_url = page.url if page else "" current_path = urlparse(current_url).path.rstrip("/") or "/" has_app_menu = bool(page and page.ele(".app-menu", timeout=0.5)) has_services_link = bool(page and page.ele("@href=/Services", timeout=0.5)) if ( current_path != "/UserArea" or not has_app_menu or not has_services_link ): raise RuntimeError( "create_session returned without authenticated /UserArea " f"markers: {_url_for_log(current_url)}" ) print(f"ITA_SESSION_OK url={_url_for_log(current_url)}") except Exception as exc: print( f"ITA_SESSION_FAILED type={type(exc).__name__} " f"message={_text_for_log(exc)}" ) _save_failure_diagnostics(plugin, output_dir) sanitized_traceback = _text_for_log( "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) ) print(sanitized_traceback, file=sys.stderr, end="") exit_code = 1 finally: try: plugin.cleanup() print("ITA_SESSION_CLEANUP_OK") except Exception as exc: cleanup_error = exc print( f"ITA_SESSION_CLEANUP_FAILED type={type(exc).__name__} " f"message={_text_for_log(exc)}", file=sys.stderr, ) return 3 if cleanup_error is not None else exit_code def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description="Isolated Italy plugin login debugger (never queries or books)." ) parser.add_argument( "--preflight", action="store_true", help="Check the local runtime without opening a browser or making a request.", ) parser.add_argument( "--non-interactive", action="store_true", help="Fail instead of prompting when credentials are missing.", ) parser.add_argument( "--local-query-account", action="store_true", help=( "Use the ignored local Italy Query account and its persistent " "browser profile; still performs login only." ), ) return parser.parse_args(argv) def main(argv: list[str] | None = None) -> int: args = parse_args(argv) try: if args.preflight: return run_preflight(os.environ) return run_session( os.environ, non_interactive=args.non_interactive, use_local_query_profile=args.local_query_account, ) except DebugConfigurationError as exc: print(f"ITA_DEBUG_CONFIG_ERROR: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())