debug_ita_book.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. #!/usr/bin/env python3
  2. """Run one Italy Book recheck; by default stop before AVANTI.
  3. This discovery tool logs in with the eventual user's account, calls
  4. ``ItaPlugin.book()`` exactly once with a weak Query trigger, and cleans up. The
  5. current Book implementation rechecks the explicitly configured route and reads
  6. allowlisted form structure. It never fills or submits the form, opens the
  7. Calendar, sends OTP, or confirms an appointment in default discovery mode.
  8. Explicit --production-workflow exercises applicant login/OTP/selection
  9. through the public Book entry. Final submission remains disabled in both modes.
  10. Optional --verify-receipts reuses the existing receipt-baseline gate after
  11. selection; it never enables final submission or consumes a final-attempt fence.
  12. """
  13. from __future__ import annotations
  14. import argparse
  15. import json
  16. import os
  17. import sys
  18. import time
  19. from pathlib import Path
  20. from typing import Callable, Mapping
  21. REPO_ROOT = Path(__file__).resolve().parents[1]
  22. if str(REPO_ROOT) not in sys.path:
  23. sys.path.insert(0, str(REPO_ROOT))
  24. from plugins.ita_plugin import (
  25. BOOKING_CALENDAR_PREFINAL_STOP_LABEL,
  26. BOOKING_FORM_DISCOVERY_STOP_LABEL,
  27. BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
  28. ItaPlugin,
  29. )
  30. from tools.debug_ita_query import (
  31. ItaDebugRoute,
  32. _print_booking_form_structure,
  33. _print_failure_context,
  34. build_query_config,
  35. resolve_debug_route,
  36. )
  37. from tools.debug_ita_session import (
  38. DebugConfigurationError,
  39. _get_credentials,
  40. _text_for_log,
  41. resolve_chrome_path,
  42. )
  43. from tools.ita_local_handoff import (
  44. ItaLocalSignalStaleError,
  45. claim_local_weak_signal,
  46. )
  47. from utils.ita_local_profile import ITA_QUERY_ACCOUNT_FILE
  48. from utils.local_account import (
  49. LocalAccountConfigurationError,
  50. load_local_account,
  51. )
  52. from vs_types import AvailabilityStatus, BizLogicError, VSQueryResult
  53. class _BookArmCancelled(Exception):
  54. """Internal control flow for a clean Ctrl+C while waiting in armed mode."""
  55. DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS = 900
  56. MAX_LOCAL_SIGNAL_WAIT_SECONDS = 900
  57. LOCAL_SIGNAL_POLL_SECONDS = 0.1
  58. def _assert_distinct_local_accounts(book_username: str) -> None:
  59. """Fail closed unless local Query and Book roles use different accounts."""
  60. if not ITA_QUERY_ACCOUNT_FILE.exists():
  61. raise DebugConfigurationError(
  62. "Automatic local handoff requires the private Italy Query account "
  63. "file so Query and Book accounts can be verified as different"
  64. )
  65. try:
  66. query_account = load_local_account(ITA_QUERY_ACCOUNT_FILE)
  67. except LocalAccountConfigurationError as exc:
  68. raise DebugConfigurationError(
  69. "Local Italy Query account config is invalid"
  70. ) from exc
  71. if (
  72. query_account.username.strip().casefold()
  73. == book_username.strip().casefold()
  74. ):
  75. raise DebugConfigurationError(
  76. "Automatic local handoff requires different Query and Book accounts"
  77. )
  78. def _wait_for_local_signal(
  79. *,
  80. route: ItaDebugRoute,
  81. timeout_seconds: int,
  82. signal_claimer: Callable[[], object | None] | None,
  83. monotonic: Callable[[], float],
  84. sleep: Callable[[float], None],
  85. ) -> object | None:
  86. claimer = signal_claimer or (
  87. lambda: claim_local_weak_signal(
  88. expected_service_id=route.service_id,
  89. expected_routing_key=route.routing_key,
  90. )
  91. )
  92. deadline = monotonic() + timeout_seconds
  93. while True:
  94. try:
  95. signal = claimer()
  96. except ItaLocalSignalStaleError:
  97. print(
  98. "ITA_BOOK_SIGNAL_IGNORED "
  99. f"routing_key={route.routing_key} "
  100. f"service_id={route.service_id} reason=stale",
  101. flush=True,
  102. )
  103. signal = None
  104. if signal is not None:
  105. return signal
  106. remaining = deadline - monotonic()
  107. if remaining <= 0:
  108. return None
  109. try:
  110. sleep(min(LOCAL_SIGNAL_POLL_SECONDS, remaining))
  111. except KeyboardInterrupt:
  112. raise _BookArmCancelled from None
  113. def run_book_recheck_once(
  114. env: Mapping[str, str],
  115. *,
  116. non_interactive: bool,
  117. arm: bool = False,
  118. wait_for_local_signal: bool = False,
  119. signal_timeout: int = DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS,
  120. signal_claimer: Callable[[], object | None] | None = None,
  121. monotonic: Callable[[], float] = time.monotonic,
  122. sleep: Callable[[float], None] = time.sleep,
  123. production_workflow: bool = False,
  124. auto_otp: bool = False,
  125. verify_receipts: bool = False,
  126. ) -> int:
  127. if type(verify_receipts) is not bool or (verify_receipts and not production_workflow):
  128. raise DebugConfigurationError("--verify-receipts requires --production-workflow")
  129. if auto_otp and not production_workflow:
  130. raise DebugConfigurationError("--auto-otp requires --production-workflow")
  131. if production_workflow and (non_interactive or arm or wait_for_local_signal):
  132. raise DebugConfigurationError("--production-workflow requires interactive mode without legacy handoff flags")
  133. route = resolve_debug_route(env)
  134. route_log = (
  135. f"service_id={route.service_id} routing_key={route.routing_key}"
  136. )
  137. if arm and wait_for_local_signal:
  138. raise DebugConfigurationError(
  139. "--arm and --wait-for-local-signal are mutually exclusive"
  140. )
  141. if (
  142. wait_for_local_signal
  143. and not 1 <= signal_timeout <= MAX_LOCAL_SIGNAL_WAIT_SECONDS
  144. ):
  145. raise DebugConfigurationError(
  146. "signal_timeout must be between 1 and "
  147. f"{MAX_LOCAL_SIGNAL_WAIT_SECONDS} seconds"
  148. )
  149. chrome_path = resolve_chrome_path(env)
  150. os.environ["CHROME_BIN"] = str(chrome_path)
  151. credential_env = env
  152. if production_workflow:
  153. # Match the existing Book gate: never silently borrow Query credentials.
  154. credential_env = {"ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""),
  155. "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", "")}
  156. print("ITA_BOOK_WORKFLOW_CREDENTIALS role=applicant profile=temporary source=book_environment_or_prompt", flush=True)
  157. username, password = _get_credentials(credential_env, non_interactive=non_interactive)
  158. if wait_for_local_signal:
  159. _assert_distinct_local_accounts(username)
  160. config_builder = build_query_config
  161. if production_workflow:
  162. from tools.debug_ita_calendar_gate import build_calendar_gate_config
  163. config_builder = build_calendar_gate_config
  164. config = config_builder(
  165. env,
  166. username=username,
  167. password=password,
  168. route=route,
  169. )
  170. if production_workflow:
  171. config.free_config.update(query_mode="services_probe", otp_mode="manual", final_submit_enabled=False)
  172. if auto_otp:
  173. from plugins.ita_otp import validate_cloud_otp_environment
  174. from plugins.ita_protocol import ItaProtocolError, OtpMailConfig
  175. from plugins.ita_calendar_query import CalendarGateError
  176. try:
  177. mail = OtpMailConfig(env.get("ITA_OTP_AUTHORIZATION_EMAIL", ""))
  178. validate_cloud_otp_environment(mail, username)
  179. except (ItaProtocolError, CalendarGateError):
  180. raise DebugConfigurationError(
  181. "Automatic OTP requires ITA_OTP_AUTHORIZATION_EMAIL and INFO-or-higher SDK logging"
  182. ) from None
  183. config.free_config["apt_configs"][route.routing_key]["mail"] = {
  184. "authorization_email": mail.authorization_email,
  185. }
  186. config.free_config["otp_mode"] = "cloud"
  187. print("ITA_BOOK_WORKFLOW_OTP mode=cloud final_submit_enabled=false", flush=True)
  188. plugin = ItaPlugin(group_id="ita-book-local-debug")
  189. plugin.set_log(lambda message: print(message, flush=True))
  190. plugin.set_config(config)
  191. trigger = VSQueryResult(
  192. success=True,
  193. apt_type=route.appointment_type(),
  194. availability_status=AvailabilityStatus.NoneAvailable,
  195. )
  196. exit_code = 0
  197. cleanup_error: Exception | None = None
  198. audit = None
  199. try:
  200. plugin.create_session()
  201. if production_workflow:
  202. from plugins.ita_calendar_session import CalendarRequestAudit
  203. audit = CalendarRequestAudit(plugin.page, include_time_slots=True)
  204. audit.start()
  205. if arm:
  206. print(
  207. "ITA_BOOK_ARMED "
  208. f"{route_log} stage=user-area"
  209. )
  210. try:
  211. input("Press Enter once the Query account reports a weak signal: ")
  212. except KeyboardInterrupt:
  213. raise _BookArmCancelled from None
  214. should_recheck = True
  215. if wait_for_local_signal:
  216. print(
  217. "ITA_BOOK_WAITING_FOR_LOCAL_SIGNAL "
  218. f"{route_log} "
  219. f"timeout_seconds={signal_timeout}",
  220. flush=True,
  221. )
  222. signal = _wait_for_local_signal(
  223. route=route,
  224. timeout_seconds=signal_timeout,
  225. signal_claimer=signal_claimer,
  226. monotonic=monotonic,
  227. sleep=sleep,
  228. )
  229. if signal is None:
  230. print(
  231. "ITA_BOOK_SIGNAL_WAIT_TIMEOUT "
  232. f"{route_log} book_attempts=0"
  233. )
  234. exit_code = 5
  235. should_recheck = False
  236. else:
  237. print(
  238. "ITA_BOOK_SIGNAL_CLAIMED "
  239. f"{route_log} "
  240. "evidence=booking-form",
  241. flush=True,
  242. )
  243. if should_recheck:
  244. print(
  245. "ITA_BOOK_RECHECK_START "
  246. f"{route_log} book_attempt=1"
  247. )
  248. result = plugin.book(trigger, user_inputs={"username": username} if production_workflow else {})
  249. if production_workflow:
  250. from plugins.ita_calendar_book import read_calendar_service, verify_precommit_selection
  251. counts = audit.settled_snapshot()
  252. if counts["finalRequests"] != 0:
  253. raise BizLogicError("Book workflow observed an unexpected final request; do not rerun")
  254. selected = result.label == BOOKING_CALENDAR_PREFINAL_STOP_LABEL and result.success is False
  255. report = {"selectionVerified": False, "bookResultSuccess": result.success,
  256. "finalSubmissionEnabled": False, "requests": counts}
  257. if selected:
  258. approval = plugin.last_booking_precommit
  259. verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page),
  260. approval=approval)
  261. report.update(selectionVerified=True, selectedDate=approval.candidate.day.isoformat(),
  262. selectedTime=approval.candidate.time_label, remaining=approval.candidate.slots_free)
  263. if verify_receipts:
  264. # Reuse the existing gate, including its background-tab
  265. # request audit and selection-preservation check.
  266. from tools.debug_ita_book_gate import _verify_receipt_baseline
  267. baseline = _verify_receipt_baseline(plugin, plugin._resolve_route(trigger.apt_type))
  268. if audit.settled_snapshot() != counts:
  269. raise BizLogicError("Receipt verification changed the Book request budget; do not rerun")
  270. report["receiptBaseline"] = baseline
  271. print("ITA_BOOK_WORKFLOW_RECEIPT_BASELINE=" + json.dumps(baseline, sort_keys=True), flush=True)
  272. elif result.success or result.label != BOOKING_RECHECK_NONE_AVAILABLE_LABEL:
  273. raise BizLogicError("Book workflow did not return the expected pre-final or no-availability result")
  274. exit_code = 0 if selected else 2
  275. print("ITA_BOOK_WORKFLOW_RESULT=" + json.dumps(report, sort_keys=True), flush=True)
  276. elif result.success:
  277. print(
  278. "ITA_BOOK_SAFE_STOP "
  279. f"{route_log} "
  280. "reason=unexpected-success-before-avanti"
  281. )
  282. exit_code = 4
  283. elif result.label == BOOKING_FORM_DISCOVERY_STOP_LABEL:
  284. _print_booking_form_structure(
  285. plugin,
  286. raw_structure=plugin.last_booking_form_structure,
  287. route=route,
  288. )
  289. print(
  290. "ITA_BOOK_DISCOVERY_STOP "
  291. f"{route_log} "
  292. "stage=before-avanti submit_attempts=0"
  293. )
  294. exit_code = 4
  295. elif result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL:
  296. print(
  297. "ITA_BOOK_RECHECK_NONE_AVAILABLE "
  298. f"{route_log}"
  299. )
  300. else:
  301. print(
  302. "ITA_BOOK_SAFE_STOP "
  303. f"{route_log} reason=unexpected-result"
  304. )
  305. exit_code = 4
  306. except _BookArmCancelled:
  307. label = (
  308. "ITA_BOOK_SIGNAL_WAIT_CANCELLED"
  309. if wait_for_local_signal
  310. else "ITA_BOOK_ARM_CANCELLED"
  311. )
  312. print(
  313. f"\n{label} {route_log} book_attempts=0"
  314. )
  315. exit_code = 130
  316. except BizLogicError as exc:
  317. print(
  318. f"ITA_BOOK_FAILED type={type(exc).__name__} "
  319. f"message={_text_for_log(exc)}"
  320. )
  321. _print_failure_context(plugin)
  322. if plugin.last_booking_form_structure is not None:
  323. _print_booking_form_structure(
  324. plugin,
  325. raw_structure=plugin.last_booking_form_structure,
  326. route=route,
  327. )
  328. exit_code = 1
  329. except Exception as exc:
  330. print(
  331. f"ITA_BOOK_FAILED type={type(exc).__name__} "
  332. f"message={_text_for_log(exc)}"
  333. )
  334. _print_failure_context(plugin)
  335. exit_code = 1
  336. finally:
  337. if audit is not None:
  338. try:
  339. counts = audit.settled_snapshot()
  340. if counts["finalRequests"] != 0:
  341. exit_code = 1
  342. print("ITA_BOOK_WORKFLOW_AUDIT=" + json.dumps(counts, sort_keys=True), flush=True)
  343. except Exception:
  344. exit_code = 1
  345. print("ITA_BOOK_WORKFLOW_AUDIT_FAILED", flush=True)
  346. finally:
  347. try:
  348. audit.stop()
  349. except Exception:
  350. exit_code = 1
  351. print("ITA_BOOK_WORKFLOW_AUDIT_CLEANUP_FAILED", flush=True)
  352. try:
  353. plugin.cleanup()
  354. print("ITA_BOOK_CLEANUP_OK")
  355. except Exception as exc:
  356. cleanup_error = exc
  357. print(
  358. f"ITA_BOOK_CLEANUP_FAILED type={type(exc).__name__} "
  359. f"message={_text_for_log(exc)}",
  360. file=sys.stderr,
  361. )
  362. return 3 if cleanup_error is not None else exit_code
  363. def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
  364. parser = argparse.ArgumentParser(
  365. description=(
  366. "One-shot route-configured Italy Book recheck debugger "
  367. "(default: stop before AVANTI; production-workflow: stop after selection; never confirm)."
  368. )
  369. )
  370. parser.add_argument(
  371. "--non-interactive",
  372. action="store_true",
  373. help="Fail instead of prompting when credentials are missing.",
  374. )
  375. parser.add_argument(
  376. "--production-workflow", action="store_true",
  377. help="Exercise the public Book entry through manual OTP and Calendar selection; never submit final.",
  378. )
  379. parser.add_argument(
  380. "--auto-otp", action="store_true",
  381. help="Use the existing cloud mail API in production-workflow instead of prompting for OTP; never confirm.",
  382. )
  383. parser.add_argument(
  384. "--verify-receipts", action="store_true",
  385. help="With production-workflow, verify the existing receipt baseline without submitting a booking.",
  386. )
  387. wait_group = parser.add_mutually_exclusive_group()
  388. wait_group.add_argument(
  389. "--arm",
  390. action="store_true",
  391. help=(
  392. "Log in and wait at /UserArea until Enter is pressed, then perform "
  393. "the one safe Book recheck."
  394. ),
  395. )
  396. wait_group.add_argument(
  397. "--wait-for-local-signal",
  398. action="store_true",
  399. help=(
  400. "Log in with the user account, atomically wait for one local Query "
  401. "weak signal, then perform one independent safe recheck."
  402. ),
  403. )
  404. parser.add_argument(
  405. "--signal-timeout",
  406. type=int,
  407. default=DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS,
  408. help=(
  409. "Maximum seconds to keep the user Session armed while waiting "
  410. f"(ceiling: {MAX_LOCAL_SIGNAL_WAIT_SECONDS})."
  411. ),
  412. )
  413. return parser.parse_args(argv)
  414. def main(argv: list[str] | None = None) -> int:
  415. args = parse_args(argv)
  416. try:
  417. if args.auto_otp and not args.production_workflow:
  418. raise DebugConfigurationError("--auto-otp requires --production-workflow")
  419. if args.verify_receipts and not args.production_workflow:
  420. raise DebugConfigurationError("--verify-receipts requires --production-workflow")
  421. if args.production_workflow:
  422. extra = {"auto_otp": True} if args.auto_otp else {}
  423. if args.verify_receipts:
  424. extra["verify_receipts"] = True
  425. return run_book_recheck_once(
  426. os.environ, non_interactive=args.non_interactive, arm=args.arm,
  427. wait_for_local_signal=args.wait_for_local_signal,
  428. signal_timeout=args.signal_timeout, production_workflow=True, **extra,
  429. )
  430. return run_book_recheck_once(
  431. os.environ,
  432. non_interactive=args.non_interactive,
  433. arm=args.arm,
  434. wait_for_local_signal=args.wait_for_local_signal,
  435. signal_timeout=args.signal_timeout,
  436. )
  437. except DebugConfigurationError as exc:
  438. print(f"ITA_BOOK_CONFIG_ERROR: {exc}", file=sys.stderr)
  439. return 2
  440. if __name__ == "__main__":
  441. raise SystemExit(main())