| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- """Italy-only OTP adapter.
- The adapter deliberately reuses ``VSCloudApi.fetch_mail_content`` instead of
- creating another mail provider. It adds the Italy contract around that call:
- one sent-time window, a fixed Prenot@Mi sender filter, deterministic body
- parsing, and fail-closed errors that never carry the raw mail body.
- The provider returns body only: its header/time filtering is a dependency, not
- independent sender authentication or freshness proof by this adapter.
- """
- from __future__ import annotations
- import logging
- import re
- from datetime import datetime, timezone
- import vs_log_macros
- from plugins.ita_calendar_query import CalendarGateError
- from plugins.ita_protocol import (
- ItaProtocolError,
- OtpMailConfig,
- PRENOTAMI_OTP_SENDER,
- parse_otp_body,
- )
- from toolkit.vs_cloud_api import VSCloudApi
- from vs_types import (
- BizLogicError,
- PermissionDeniedError,
- RateLimiteddError,
- SessionExpiredOrInvalidError,
- )
- _EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
- _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
- def utc_sent_at() -> str:
- """Return the exact UTC format required by the existing cloud endpoint."""
- return datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
- def validate_cloud_otp_logging() -> None:
- """Validate before any shared SDK call; never change logging state.
- Existing SDK DEBUG output includes raw mail. Automatic Italy OTP therefore
- requires a stable INFO-or-higher logger throughout the call. Runtime log
- reconfiguration and backend logging are outside this local guarantee.
- """
- logger = getattr(vs_log_macros, "_active_logger", None)
- if not isinstance(logger, logging.Logger) or logger.isEnabledFor(logging.DEBUG):
- raise CalendarGateError("Italy automatic OTP requires DEBUG payload logging to be disabled")
- def validate_cloud_otp_environment(mail_config: OtpMailConfig, recipient: str) -> None:
- """Validate the configured mailbox policy and actual account before OTP."""
- if not isinstance(mail_config, OtpMailConfig):
- raise CalendarGateError("Italy OTP mail configuration is missing")
- recipient_value = _validate_recipient(recipient)
- mail_config.mailbox_for(recipient_value)
- validate_cloud_otp_logging()
- def _validate_recipient(recipient: str) -> str:
- if not isinstance(recipient, str):
- raise CalendarGateError("Italy OTP recipient must be an email address")
- value = recipient.strip()
- if not _EMAIL_PATTERN.fullmatch(value):
- raise CalendarGateError("Italy OTP recipient must be an email address")
- return value
- def _validate_sent_at(sent_at: str) -> str:
- if not isinstance(sent_at, str):
- raise CalendarGateError("Italy OTP sent time is invalid")
- value = sent_at.strip()
- try:
- datetime.strptime(value, _SENT_AT_FORMAT)
- except ValueError:
- raise CalendarGateError("Italy OTP sent time is invalid") from None
- return value
- def fetch_otp_from_cloud(
- mail_config: OtpMailConfig,
- *,
- recipient: str,
- sent_at: str,
- api: VSCloudApi | None = None,
- ) -> str:
- """Read and parse one new Italy OTP through the existing cloud API.
- The call is intentionally one-shot. ``fetch-top`` is not a fallback and
- no retry or second OTP request is issued after a read/parse failure.
- """
- validate_cloud_otp_environment(mail_config, recipient)
- recipient_value = _validate_recipient(recipient)
- sent_at_value = _validate_sent_at(sent_at)
- try:
- client = api if api is not None else VSCloudApi.Instance()
- # Keep the body inside this scope; callers receive only the parsed
- # digits and must not log either the body or the code.
- body = client.fetch_mail_content(
- email=mail_config.mailbox_for(recipient_value),
- sender=PRENOTAMI_OTP_SENDER,
- recipient=recipient_value,
- subject_keywords=mail_config.subject_keywords,
- body_keywords=mail_config.body_keywords,
- sent_date=sent_at_value,
- expiry=mail_config.expiry_seconds,
- only_text=True,
- )
- except SessionExpiredOrInvalidError:
- # Mail API authentication is NOT the appointment site's Session.
- raise CalendarGateError("Italy OTP mailbox API authentication failed") from None
- except PermissionDeniedError:
- raise CalendarGateError(
- "Italy OTP mailbox authorization is not permitted"
- ) from None
- except RateLimiteddError:
- raise CalendarGateError("Italy OTP mailbox read was rate limited") from None
- except BizLogicError:
- # The shared SDK may include a provider response body in this error.
- raise CalendarGateError("Italy OTP mailbox read failed") from None
- except Exception:
- # Suppress provider exception context in standard traceback rendering.
- raise CalendarGateError("Italy OTP mailbox read failed") from None
- try:
- return parse_otp_body(body)
- except ItaProtocolError as exc:
- raise CalendarGateError(
- f"Italy OTP mail rejected ({exc.code})"
- ) from None
- __all__ = ["fetch_otp_from_cloud", "utc_sent_at", "validate_cloud_otp_environment", "validate_cloud_otp_logging"]
|