ita_local_handoff.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. """Private, one-shot local handoff from Italy Query discovery to Book recheck.
  2. This is a debug-only adapter. Production continues to use the existing
  3. Sentinel -> Redis -> Booker path. The file contains metadata only and is
  4. atomically claimed so a weak signal cannot trigger two local Book attempts.
  5. """
  6. from __future__ import annotations
  7. import json
  8. import math
  9. import os
  10. import stat
  11. import time
  12. import uuid
  13. from dataclasses import dataclass
  14. from pathlib import Path
  15. PROJECT_ROOT = Path(__file__).resolve().parents[1]
  16. ITA_LOCAL_HANDOFF_ROOT = PROJECT_ROOT / "data" / "ita_local_handoff"
  17. ITA_LOCAL_SIGNAL_NAME = "query-weak-signal.json"
  18. ITA_LOCAL_SIGNAL_SCHEMA = 1
  19. ITA_LOCAL_SIGNAL_KIND = "italy-query-weak-signal"
  20. ITA_LOCAL_SIGNAL_EVIDENCE = "booking-form"
  21. ITA_LOCAL_SIGNAL_TTL_SECONDS = 30
  22. ITA_LOCAL_SIGNAL_MAX_BYTES = 4096
  23. ITA_LOCAL_SIGNAL_FUTURE_SKEW_SECONDS = 5
  24. class ItaLocalHandoffError(ValueError):
  25. """Raised when the local handoff artifact is unsafe or invalid."""
  26. class ItaLocalSignalStaleError(ItaLocalHandoffError):
  27. """Raised after an expired signal has been atomically consumed."""
  28. @dataclass(frozen=True)
  29. class ItaLocalWeakSignal:
  30. service_id: int
  31. routing_key: str
  32. evidence: str
  33. issued_at: float
  34. def _ensure_private_directory(path: Path) -> Path:
  35. if path.is_symlink():
  36. raise ItaLocalHandoffError("local handoff directory must not be a symlink")
  37. try:
  38. path.mkdir(mode=0o700, parents=True, exist_ok=True)
  39. except OSError as exc:
  40. raise ItaLocalHandoffError(
  41. f"cannot create local handoff directory ({type(exc).__name__})"
  42. ) from exc
  43. if path.is_symlink() or not path.is_dir():
  44. raise ItaLocalHandoffError(
  45. "local handoff path must be a private directory"
  46. )
  47. if os.name == "posix":
  48. try:
  49. path.chmod(0o700)
  50. mode = stat.S_IMODE(path.stat().st_mode)
  51. except OSError as exc:
  52. raise ItaLocalHandoffError(
  53. f"cannot secure local handoff directory ({type(exc).__name__})"
  54. ) from exc
  55. if mode != 0o700:
  56. raise ItaLocalHandoffError(
  57. "local handoff directory permissions must be 700"
  58. )
  59. return path.resolve()
  60. def _resolved_root(handoff_root: str | Path | None) -> Path:
  61. root = Path(handoff_root or ITA_LOCAL_HANDOFF_ROOT).expanduser()
  62. if not root.is_absolute():
  63. root = PROJECT_ROOT / root
  64. return _ensure_private_directory(root)
  65. def _write_private_file(path: Path, content: bytes) -> None:
  66. temp_path = path.parent / f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
  67. flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
  68. flags |= getattr(os, "O_NOFOLLOW", 0)
  69. descriptor: int | None = None
  70. try:
  71. descriptor = os.open(temp_path, flags, 0o600)
  72. if os.name == "posix":
  73. os.fchmod(descriptor, 0o600)
  74. with os.fdopen(descriptor, "wb") as handle:
  75. descriptor = None
  76. handle.write(content)
  77. handle.flush()
  78. os.fsync(handle.fileno())
  79. os.replace(temp_path, path)
  80. if os.name == "posix":
  81. path.chmod(0o600)
  82. if stat.S_IMODE(path.stat().st_mode) != 0o600:
  83. raise ItaLocalHandoffError(
  84. "local handoff signal permissions must be 600"
  85. )
  86. except ItaLocalHandoffError:
  87. raise
  88. except OSError as exc:
  89. raise ItaLocalHandoffError(
  90. f"cannot publish local handoff signal ({type(exc).__name__})"
  91. ) from exc
  92. finally:
  93. if descriptor is not None:
  94. os.close(descriptor)
  95. try:
  96. temp_path.unlink()
  97. except FileNotFoundError:
  98. pass
  99. except OSError:
  100. pass
  101. def publish_local_weak_signal(
  102. *,
  103. service_id: int,
  104. routing_key: str,
  105. issued_at: float | None = None,
  106. handoff_root: str | Path | None = None,
  107. ) -> Path:
  108. """Atomically publish one short-lived, metadata-only weak signal."""
  109. if (
  110. isinstance(service_id, bool)
  111. or not isinstance(service_id, int)
  112. or service_id <= 0
  113. ):
  114. raise ItaLocalHandoffError("local handoff service_id must be positive")
  115. normalized_routing_key = str(routing_key or "").strip()
  116. if not normalized_routing_key:
  117. raise ItaLocalHandoffError("local handoff routing_key is required")
  118. timestamp = time.time() if issued_at is None else float(issued_at)
  119. if not math.isfinite(timestamp):
  120. raise ItaLocalHandoffError("local handoff issued_at must be finite")
  121. payload = {
  122. "schema": ITA_LOCAL_SIGNAL_SCHEMA,
  123. "kind": ITA_LOCAL_SIGNAL_KIND,
  124. "service_id": service_id,
  125. "routing_key": normalized_routing_key,
  126. "evidence": ITA_LOCAL_SIGNAL_EVIDENCE,
  127. "issued_at": timestamp,
  128. }
  129. encoded = json.dumps(
  130. payload,
  131. ensure_ascii=True,
  132. sort_keys=True,
  133. separators=(",", ":"),
  134. ).encode("utf-8")
  135. root = _resolved_root(handoff_root)
  136. signal_path = root / ITA_LOCAL_SIGNAL_NAME
  137. _write_private_file(signal_path, encoded)
  138. return signal_path
  139. def _read_claimed_payload(path: Path) -> dict:
  140. flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
  141. descriptor: int | None = None
  142. try:
  143. descriptor = os.open(path, flags)
  144. file_stat = os.fstat(descriptor)
  145. if not stat.S_ISREG(file_stat.st_mode):
  146. raise ItaLocalHandoffError(
  147. "local handoff signal must be a regular file"
  148. )
  149. if os.name == "posix" and stat.S_IMODE(file_stat.st_mode) != 0o600:
  150. raise ItaLocalHandoffError(
  151. "local handoff signal permissions must be 600"
  152. )
  153. content = os.read(descriptor, ITA_LOCAL_SIGNAL_MAX_BYTES + 1)
  154. except ItaLocalHandoffError:
  155. raise
  156. except OSError as exc:
  157. raise ItaLocalHandoffError(
  158. f"cannot read local handoff signal ({type(exc).__name__})"
  159. ) from exc
  160. finally:
  161. if descriptor is not None:
  162. os.close(descriptor)
  163. if len(content) > ITA_LOCAL_SIGNAL_MAX_BYTES:
  164. raise ItaLocalHandoffError("local handoff signal is too large")
  165. try:
  166. payload = json.loads(content.decode("utf-8"))
  167. except (UnicodeDecodeError, json.JSONDecodeError) as exc:
  168. raise ItaLocalHandoffError("local handoff signal is invalid JSON") from exc
  169. if not isinstance(payload, dict):
  170. raise ItaLocalHandoffError("local handoff signal must be a JSON object")
  171. return payload
  172. def claim_local_weak_signal(
  173. *,
  174. expected_service_id: int,
  175. expected_routing_key: str,
  176. ttl_seconds: int = ITA_LOCAL_SIGNAL_TTL_SECONDS,
  177. now: float | None = None,
  178. handoff_root: str | Path | None = None,
  179. ) -> ItaLocalWeakSignal | None:
  180. """Atomically consume and validate one weak signal, or return ``None``."""
  181. if ttl_seconds <= 0:
  182. raise ItaLocalHandoffError("local handoff ttl_seconds must be positive")
  183. root = _resolved_root(handoff_root)
  184. signal_path = root / ITA_LOCAL_SIGNAL_NAME
  185. try:
  186. signal_stat = signal_path.lstat()
  187. except FileNotFoundError:
  188. return None
  189. except OSError as exc:
  190. raise ItaLocalHandoffError(
  191. f"cannot inspect local handoff signal ({type(exc).__name__})"
  192. ) from exc
  193. if not stat.S_ISREG(signal_stat.st_mode):
  194. raise ItaLocalHandoffError("local handoff signal must be a regular file")
  195. claim_path = root / (
  196. f".{ITA_LOCAL_SIGNAL_NAME}.{os.getpid()}.{uuid.uuid4().hex}.claim"
  197. )
  198. try:
  199. try:
  200. os.replace(signal_path, claim_path)
  201. except FileNotFoundError:
  202. return None
  203. payload = _read_claimed_payload(claim_path)
  204. expected_keys = {
  205. "schema",
  206. "kind",
  207. "service_id",
  208. "routing_key",
  209. "evidence",
  210. "issued_at",
  211. }
  212. if set(payload) != expected_keys:
  213. raise ItaLocalHandoffError(
  214. "local handoff signal has an unsupported schema"
  215. )
  216. if payload["schema"] != ITA_LOCAL_SIGNAL_SCHEMA:
  217. raise ItaLocalHandoffError(
  218. "local handoff signal schema version is unsupported"
  219. )
  220. if payload["kind"] != ITA_LOCAL_SIGNAL_KIND:
  221. raise ItaLocalHandoffError("local handoff signal kind is invalid")
  222. if payload["evidence"] != ITA_LOCAL_SIGNAL_EVIDENCE:
  223. raise ItaLocalHandoffError("local handoff signal evidence is invalid")
  224. if payload["service_id"] != expected_service_id:
  225. raise ItaLocalHandoffError(
  226. "local handoff signal service_id does not match"
  227. )
  228. if payload["routing_key"] != expected_routing_key:
  229. raise ItaLocalHandoffError(
  230. "local handoff signal routing_key does not match"
  231. )
  232. issued_at_raw = payload["issued_at"]
  233. if isinstance(issued_at_raw, bool) or not isinstance(
  234. issued_at_raw, (int, float)
  235. ):
  236. raise ItaLocalHandoffError(
  237. "local handoff signal issued_at is invalid"
  238. )
  239. issued_at = float(issued_at_raw)
  240. current_time = time.time() if now is None else float(now)
  241. if not math.isfinite(issued_at) or not math.isfinite(current_time):
  242. raise ItaLocalHandoffError(
  243. "local handoff signal timestamp is invalid"
  244. )
  245. if issued_at - current_time > ITA_LOCAL_SIGNAL_FUTURE_SKEW_SECONDS:
  246. raise ItaLocalHandoffError(
  247. "local handoff signal timestamp is in the future"
  248. )
  249. if current_time - issued_at > ttl_seconds:
  250. raise ItaLocalSignalStaleError("local handoff signal has expired")
  251. return ItaLocalWeakSignal(
  252. service_id=expected_service_id,
  253. routing_key=expected_routing_key,
  254. evidence=ITA_LOCAL_SIGNAL_EVIDENCE,
  255. issued_at=issued_at,
  256. )
  257. finally:
  258. try:
  259. claim_path.unlink()
  260. except FileNotFoundError:
  261. pass
  262. except OSError:
  263. pass