ita_otp.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """Italy-only OTP adapter.
  2. The adapter deliberately reuses ``VSCloudApi.fetch_mail_content`` instead of
  3. creating another mail provider. It adds the Italy contract around that call:
  4. one sent-time window, a fixed Prenot@Mi sender filter, deterministic body
  5. parsing, and fail-closed errors that never carry the raw mail body.
  6. The provider returns body only: its header/time filtering is a dependency, not
  7. independent sender authentication or freshness proof by this adapter.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import re
  12. from datetime import datetime, timezone
  13. import vs_log_macros
  14. from plugins.ita_calendar_query import CalendarGateError
  15. from plugins.ita_protocol import (
  16. ItaProtocolError,
  17. OtpMailConfig,
  18. PRENOTAMI_OTP_SENDER,
  19. parse_otp_body,
  20. )
  21. from toolkit.vs_cloud_api import VSCloudApi
  22. from vs_types import (
  23. BizLogicError,
  24. PermissionDeniedError,
  25. RateLimiteddError,
  26. SessionExpiredOrInvalidError,
  27. )
  28. _EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
  29. _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
  30. def utc_sent_at() -> str:
  31. """Return the exact UTC format required by the existing cloud endpoint."""
  32. return datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
  33. def validate_cloud_otp_logging() -> None:
  34. """Validate before any shared SDK call; never change logging state.
  35. Existing SDK DEBUG output includes raw mail. Automatic Italy OTP therefore
  36. requires a stable INFO-or-higher logger throughout the call. Runtime log
  37. reconfiguration and backend logging are outside this local guarantee.
  38. """
  39. logger = getattr(vs_log_macros, "_active_logger", None)
  40. if not isinstance(logger, logging.Logger) or logger.isEnabledFor(logging.DEBUG):
  41. raise CalendarGateError("Italy automatic OTP requires DEBUG payload logging to be disabled")
  42. def validate_cloud_otp_environment(mail_config: OtpMailConfig, recipient: str) -> None:
  43. """Validate the configured mailbox policy and actual account before OTP."""
  44. if not isinstance(mail_config, OtpMailConfig):
  45. raise CalendarGateError("Italy OTP mail configuration is missing")
  46. recipient_value = _validate_recipient(recipient)
  47. mail_config.mailbox_for(recipient_value)
  48. validate_cloud_otp_logging()
  49. def _validate_recipient(recipient: str) -> str:
  50. if not isinstance(recipient, str):
  51. raise CalendarGateError("Italy OTP recipient must be an email address")
  52. value = recipient.strip()
  53. if not _EMAIL_PATTERN.fullmatch(value):
  54. raise CalendarGateError("Italy OTP recipient must be an email address")
  55. return value
  56. def _validate_sent_at(sent_at: str) -> str:
  57. if not isinstance(sent_at, str):
  58. raise CalendarGateError("Italy OTP sent time is invalid")
  59. value = sent_at.strip()
  60. try:
  61. datetime.strptime(value, _SENT_AT_FORMAT)
  62. except ValueError:
  63. raise CalendarGateError("Italy OTP sent time is invalid") from None
  64. return value
  65. def fetch_otp_from_cloud(
  66. mail_config: OtpMailConfig,
  67. *,
  68. recipient: str,
  69. sent_at: str,
  70. api: VSCloudApi | None = None,
  71. ) -> str:
  72. """Read and parse one new Italy OTP through the existing cloud API.
  73. The call is intentionally one-shot. ``fetch-top`` is not a fallback and
  74. no retry or second OTP request is issued after a read/parse failure.
  75. """
  76. validate_cloud_otp_environment(mail_config, recipient)
  77. recipient_value = _validate_recipient(recipient)
  78. sent_at_value = _validate_sent_at(sent_at)
  79. try:
  80. client = api if api is not None else VSCloudApi.Instance()
  81. # Keep the body inside this scope; callers receive only the parsed
  82. # digits and must not log either the body or the code.
  83. body = client.fetch_mail_content(
  84. email=mail_config.mailbox_for(recipient_value),
  85. sender=PRENOTAMI_OTP_SENDER,
  86. recipient=recipient_value,
  87. subject_keywords=mail_config.subject_keywords,
  88. body_keywords=mail_config.body_keywords,
  89. sent_date=sent_at_value,
  90. expiry=mail_config.expiry_seconds,
  91. only_text=True,
  92. )
  93. except SessionExpiredOrInvalidError:
  94. # Mail API authentication is NOT the appointment site's Session.
  95. raise CalendarGateError("Italy OTP mailbox API authentication failed") from None
  96. except PermissionDeniedError:
  97. raise CalendarGateError(
  98. "Italy OTP mailbox authorization is not permitted"
  99. ) from None
  100. except RateLimiteddError:
  101. raise CalendarGateError("Italy OTP mailbox read was rate limited") from None
  102. except BizLogicError:
  103. # The shared SDK may include a provider response body in this error.
  104. raise CalendarGateError("Italy OTP mailbox read failed") from None
  105. except Exception:
  106. # Suppress provider exception context in standard traceback rendering.
  107. raise CalendarGateError("Italy OTP mailbox read failed") from None
  108. try:
  109. return parse_otp_body(body)
  110. except ItaProtocolError as exc:
  111. raise CalendarGateError(
  112. f"Italy OTP mail rejected ({exc.code})"
  113. ) from None
  114. __all__ = ["fetch_otp_from_cloud", "utc_sent_at", "validate_cloud_otp_environment", "validate_cloud_otp_logging"]