debug_ita_reservation.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #!/usr/bin/env python3
  2. """Accept the receipt reader against an existing receipt; never book.
  3. Default is a local preflight. --run uses a temporary applicant browser and only
  4. reads Reservation -> one cancelled detail -> Reservation after login. Neither
  5. raw receipts nor original exception messages are written to the console/files.
  6. --expect-confirmed instead checks one unique confirmed receipt matching the
  7. explicit date, assigned time and displayed service. This is existing-receipt
  8. verification, NOT attribution to a prior booking attempt or runtime service ID.
  9. """
  10. from __future__ import annotations
  11. import argparse
  12. import hashlib
  13. import json
  14. import os
  15. import re
  16. import sys
  17. from datetime import date
  18. from pathlib import Path
  19. from typing import Mapping
  20. REPO_ROOT = Path(__file__).resolve().parents[1]
  21. if str(REPO_ROOT) not in sys.path:
  22. sys.path.insert(0, str(REPO_ROOT))
  23. from plugins.ita_booking_final import ReservationState
  24. from plugins.ita_calendar_query import same_origin_path
  25. from plugins.ita_plugin import ItaPlugin, SERVICES_PROBE_QUERY_MODE
  26. from plugins.ita_reservation import (
  27. ReservationReadError, read_reservation_detail, read_reservation_listing,
  28. read_reservation_date_diagnostic,
  29. )
  30. from tools.debug_ita_calendar_gate import CalendarRequestAudit
  31. from tools.debug_ita_session import (
  32. DebugConfigurationError, _get_credentials, build_plugin_config, resolve_chrome_path,
  33. )
  34. CONTRACT = "receipt-readonly-confirmed-v4"
  35. LIST_URL = "https://prenotami.esteri.it/Reservation"
  36. COUNTERS = frozenset(("otpRequests", "avantiPosts", "availabilityRequests",
  37. "timeSlotRequests", "finalRequests"))
  38. CONFIG_ENV_KEYS = frozenset((
  39. "ITA_PROXY_IP", "ITA_PROXY_PORT", "ITA_PROXY_PROTO", "ITA_PROXY_USERNAME",
  40. "ITA_PROXY_PASSWORD", "ITA_PROXY_ID", "MIHOMO_BIN", "ITA_SESSION_MAX_LIFE",
  41. ))
  42. READ_REASONS = frozenset((
  43. "field_invalid", "date_unrecognized", "time_unrecognized", "detail_url_invalid",
  44. "detail_schema_changed", "fields_ambiguous", "status_code_invalid", "coverage_invalid",
  45. "coverage_incomplete", "pagination_invalid", "list_schema_changed", "table_ambiguous",
  46. "headers_changed", "waitlist_ambiguous", "waitlist_schema_unverified", "row_nodes_incomplete",
  47. "row_schema_changed", "duplicate_record", "wrong_page", "context_changed", "not_ready",
  48. "page_read_rejected", "browser_read_failed", "wait_config_invalid", "stability_timeout",
  49. ))
  50. class ReceiptGateError(ValueError):
  51. pass
  52. def source_fingerprint() -> str:
  53. digest = hashlib.sha256()
  54. for name in (
  55. "tools/debug_ita_reservation.py", "plugins/ita_reservation.py",
  56. "plugins/ita_booking_final.py", "plugins/ita_plugin.py", "plugins/ita_protocol.py",
  57. "plugins/ita_calendar_query.py", "plugins/ita_calendar_book.py",
  58. "tools/debug_ita_session.py", "tools/debug_ita_calendar_gate.py",
  59. ):
  60. digest.update(name.encode())
  61. digest.update((REPO_ROOT / name).read_bytes())
  62. return digest.hexdigest()[:12]
  63. def build_receipt_config(env: Mapping[str, str], *, username: str, password: str):
  64. # Explicit projection: saved Query accounts, persistent profiles, debug and
  65. # regional/service settings must not leak into this applicant-only reader.
  66. projected = {key: env[key] for key in CONFIG_ENV_KEYS if key in env}
  67. config = build_plugin_config(projected, username=username, password=password)
  68. config.free_config = {"query_mode": SERVICES_PROBE_QUERY_MODE, "final_submit_enabled": False}
  69. return config
  70. def _check(condition: bool, reason: str) -> None:
  71. if not condition:
  72. raise ReceiptGateError(reason)
  73. def _check_page_url(page, expected: str) -> None:
  74. try:
  75. path, parsed = same_origin_path(page.url)
  76. except Exception:
  77. raise ReceiptGateError("navigation_rejected") from None
  78. _check(page.url == expected and not parsed.query and not parsed.fragment and bool(path),
  79. "navigation_rejected")
  80. def run_receipt_gate(env: Mapping[str, str], *, execute: bool = False,
  81. non_interactive: bool = False, expect_confirmed: bool = False,
  82. expected_date: str | None = None, expected_time: str | None = None,
  83. expected_service: str | None = None) -> int:
  84. plugin = audit = None
  85. audit_started = False
  86. previous_chrome = os.environ.get("CHROME_BIN")
  87. chrome_changed = False
  88. result = {
  89. "contract": CONTRACT, "passed": False, "exitCode": 1, "stage": "preflight",
  90. "reason": "", "listReady": False, "cancelledDetailMatched": False,
  91. "listUnchanged": False, "reservationCountBefore": None,
  92. "reservationCountAfter": None, "postLoginBusinessRequests": None,
  93. "cleanupOk": False, "auditVerified": False, "finalSubmissionEnabled": False,
  94. "dateDiagnostic": None,
  95. "confirmedDetailMatched": False, "existingReservationConfirmed": False,
  96. "bookingAttemptAttributed": False, "confirmedReceipt": None,
  97. }
  98. def verify_audit():
  99. result["auditVerified"] = False
  100. try:
  101. counts = audit.settled_snapshot()
  102. except Exception:
  103. raise ReceiptGateError("audit_unavailable") from None
  104. _check(isinstance(counts, dict) and set(counts) == COUNTERS and
  105. all(type(v) is int and v >= 0 for v in counts.values()), "audit_unavailable")
  106. result["postLoginBusinessRequests"] = counts
  107. _check(all(v == 0 for v in counts.values()), "unexpected_business_request")
  108. result["auditVerified"] = True
  109. try:
  110. _check(all(type(v) is bool for v in (execute, non_interactive, expect_confirmed)),
  111. "invalid_execution_flag")
  112. print(f"ITA_RECEIPT_TOOL_CONTRACT version={CONTRACT} source_sha256={source_fingerprint()}", flush=True)
  113. expected_day = None
  114. if expect_confirmed:
  115. try:
  116. expected_day = date.fromisoformat(expected_date)
  117. valid = (expected_day.isoformat() == expected_date and
  118. isinstance(expected_time, str) and
  119. re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", expected_time) is not None and
  120. isinstance(expected_service, str) and 0 < len(expected_service) <= 256 and
  121. expected_service == expected_service.strip() and
  122. all(ord(c) >= 32 and ord(c) != 127 for c in expected_service))
  123. except (TypeError, ValueError):
  124. valid = False
  125. _check(valid, "confirmed_expectations_invalid")
  126. else:
  127. _check(all(v is None for v in (expected_date, expected_time, expected_service)),
  128. "confirmed_expectations_without_mode")
  129. chrome = resolve_chrome_path(env)
  130. build_receipt_config(env, username="preflight@example.invalid", password="placeholder")
  131. if not execute:
  132. print("ITA_RECEIPT_PREFLIGHT_OK external_requests=0 credentials_read=false browser_created=false")
  133. return 0
  134. result["stage"] = "credentials"
  135. username, password = _get_credentials({
  136. "ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""),
  137. "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", ""),
  138. }, non_interactive=non_interactive)
  139. config = build_receipt_config(env, username=username, password=password)
  140. result["stage"] = "login"
  141. os.environ["CHROME_BIN"] = str(chrome)
  142. chrome_changed = True
  143. plugin = ItaPlugin(group_id="ita-receipt-readonly")
  144. plugin.set_log(lambda _message: None)
  145. plugin.set_config(config)
  146. print("ITA_RECEIPT_LOGIN_START profile=temporary role=applicant", flush=True)
  147. plugin.create_session()
  148. page = plugin.page
  149. _check_page_url(page, "https://prenotami.esteri.it/UserArea")
  150. _check(bool(page.ele(".app-menu", timeout=0.5)) and
  151. bool(page.ele("@href=/Services", timeout=0.5)), "login_unverified")
  152. tab_id, generation = page.tab_id, plugin.session_create_time
  153. account_name = config.account.username
  154. _check(isinstance(tab_id, str) and bool(tab_id) and generation > 0, "context_changed")
  155. def verify_context():
  156. _check(plugin.page is page and page.tab_id == tab_id and
  157. plugin.session_create_time == generation and
  158. plugin.config.account.username == account_name and
  159. plugin._persistent_profile_path is None and
  160. plugin.free_config == {"query_mode": SERVICES_PROBE_QUERY_MODE,
  161. "final_submit_enabled": False}, "context_changed")
  162. def navigate(url):
  163. verify_context()
  164. _check(page.get(url, retry=0, timeout=30) is not False, "navigation_failed")
  165. verify_context()
  166. _check_page_url(page, url)
  167. verify_context()
  168. print("ITA_RECEIPT_LOGIN_OK", flush=True)
  169. result["stage"] = "audit_start"
  170. audit = CalendarRequestAudit(page, include_time_slots=True)
  171. audit.start()
  172. audit_started = True
  173. result["stage"] = "list_before"
  174. navigate(LIST_URL)
  175. before = read_reservation_listing(page)
  176. verify_context()
  177. verify_audit()
  178. result.update(listReady=True, reservationCountBefore=len(before.rows))
  179. if expect_confirmed:
  180. candidates = [row for row in before.rows if row.state is ReservationState.ACTIVE and
  181. row.day == expected_day and row.appointment_time == expected_time and
  182. row.service_name == expected_service]
  183. _check(len(candidates) == 1, "confirmed_sample_missing" if not candidates else
  184. "confirmed_sample_ambiguous")
  185. sample = candidates[0]
  186. else:
  187. sample = next((row for row in before.rows if row.state is ReservationState.CANCELLED), None)
  188. _check(sample is not None, "cancelled_sample_missing")
  189. result["stage"] = "confirmed_detail" if expect_confirmed else "cancelled_detail"
  190. # The actual link has already passed the receipt adapter's strict URL validation.
  191. navigate(sample.detail_url)
  192. receipt = read_reservation_detail(page)
  193. verify_context()
  194. verify_audit()
  195. wanted_state = ReservationState.ACTIVE if expect_confirmed else ReservationState.CANCELLED
  196. wanted_code = "2" if expect_confirmed else "3"
  197. _check(receipt.state is wanted_state and receipt.status_code == wanted_code and
  198. receipt.booking_type == "Prenotazione Singola" and
  199. all(getattr(receipt, field) == getattr(sample, field) for field in (
  200. "reference", "office", "service_name", "day", "appointment_time", "status_text")),
  201. "confirmed_detail_mismatch" if expect_confirmed else "cancelled_detail_mismatch")
  202. if expect_confirmed:
  203. result["confirmedDetailMatched"] = True
  204. result["confirmedReceipt"] = {
  205. "date": receipt.day.isoformat(), "assignedTime": receipt.appointment_time,
  206. "state": receipt.state.value, "statusText": receipt.status_text,
  207. "statusCode": receipt.status_code, "singleBooking": True,
  208. "serviceDisplayMatches": True,
  209. }
  210. else:
  211. result["cancelledDetailMatched"] = True
  212. result["stage"] = "list_after"
  213. navigate(LIST_URL)
  214. after = read_reservation_listing(page)
  215. verify_context()
  216. verify_audit()
  217. result["reservationCountAfter"] = len(after.rows)
  218. _check({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and
  219. before.waitlist_count == after.waitlist_count, "listing_changed")
  220. result.update(listUnchanged=True, stage="completed", exitCode=0)
  221. except KeyboardInterrupt:
  222. result.update(reason="interrupted", exitCode=130)
  223. except DebugConfigurationError:
  224. result.update(reason="configuration_rejected")
  225. except ReservationReadError as exc:
  226. result.update(reason=exc.reason if exc.reason in READ_REASONS else "receipt_read_rejected")
  227. if exc.reason == "date_unrecognized" and result["stage"] in ("list_before", "list_after"):
  228. try:
  229. verify_context()
  230. result["dateDiagnostic"] = read_reservation_date_diagnostic(page)
  231. verify_context()
  232. except Exception:
  233. result["dateDiagnostic"] = {"available": False}
  234. except ReceiptGateError as exc:
  235. # Only fixed reasons constructed above, not raw website/browser exceptions.
  236. safe = {"navigation_rejected", "navigation_failed", "invalid_execution_flag", "login_unverified",
  237. "context_changed", "audit_unavailable", "unexpected_business_request",
  238. "cancelled_sample_missing", "cancelled_detail_mismatch", "listing_changed",
  239. "confirmed_expectations_invalid", "confirmed_expectations_without_mode",
  240. "confirmed_sample_missing", "confirmed_sample_ambiguous", "confirmed_detail_mismatch"}
  241. result.update(reason=str(exc) if str(exc) in safe else "gate_rejected")
  242. except Exception:
  243. result.update(reason="stage_failed")
  244. finally:
  245. if audit_started:
  246. try:
  247. verify_audit()
  248. except Exception as exc:
  249. result.update(exitCode=1 if result["exitCode"] == 0 else result["exitCode"])
  250. if not result["reason"]:
  251. result["reason"] = ("unexpected_business_request" if
  252. isinstance(exc, ReceiptGateError) and
  253. str(exc) == "unexpected_business_request" else "audit_unavailable")
  254. if audit is not None:
  255. try:
  256. audit.stop()
  257. except Exception:
  258. result.update(exitCode=1, auditVerified=False,
  259. reason=result["reason"] or "audit_stop_failed")
  260. if plugin is not None:
  261. try:
  262. plugin.cleanup()
  263. result["cleanupOk"] = True
  264. except Exception:
  265. result.update(exitCode=3, reason="cleanup_failed")
  266. if chrome_changed:
  267. if previous_chrome is None:
  268. os.environ.pop("CHROME_BIN", None)
  269. else:
  270. os.environ["CHROME_BIN"] = previous_chrome
  271. result["passed"] = (result["exitCode"] == 0 and result["cleanupOk"] and
  272. result["listUnchanged"] and result["auditVerified"])
  273. result["existingReservationConfirmed"] = result["passed"] and result["confirmedDetailMatched"]
  274. print("ITA_RECEIPT_GATE_RESULT=" + json.dumps(result, sort_keys=True), flush=True)
  275. return result["exitCode"]
  276. def main(argv=None) -> int:
  277. parser = argparse.ArgumentParser(description=__doc__)
  278. mode = parser.add_mutually_exclusive_group()
  279. mode.add_argument("--preflight", action="store_true", help="Local checks only (default)")
  280. mode.add_argument("--run", action="store_true", help="Log in and read an existing cancelled sample")
  281. parser.add_argument("--non-interactive", action="store_true", help="Require ITA_BOOK_USERNAME/PASSWORD")
  282. parser.add_argument("--expect-confirmed", action="store_true", help="Read one existing confirmed receipt matching all three expectations; never submit")
  283. parser.add_argument("--expected-date", help="Existing receipt date, YYYY-MM-DD")
  284. parser.add_argument("--expected-time", help="Assigned receipt time, HH:mm (not a slot range)")
  285. parser.add_argument("--expected-service", help="Exact displayed service name, not a service ID")
  286. args = parser.parse_args(argv)
  287. return run_receipt_gate(os.environ, execute=args.run, non_interactive=args.non_interactive,
  288. expect_confirmed=args.expect_confirmed, expected_date=args.expected_date,
  289. expected_time=args.expected_time, expected_service=args.expected_service)
  290. if __name__ == "__main__":
  291. raise SystemExit(main())