Skip to content

Automate browser based workflows with AI

SKY-13243 Generalize 2FA email scanning into a source registry with Outlook support (#7901)

Suchintan80f2dcba872e
diff --git a/docs/snippets/core-concepts-content.mdx b/docs/snippets/core-concepts-content.mdx
index 50de32382..abae38c7d 100644
--- a/docs/snippets/core-concepts-content.mdx
+++ b/docs/snippets/core-concepts-content.mdx
@@ -243,7 +243,7 @@ flowchart LR
B -- "restore" --> A
```
-**Browser Sessions** are live browser instances that maintain state across multiple operations. Cookies, storage, and page context persist for the duration of the session (up to 4 hours). They're useful for chaining operations in real-time or allowing human intervention between steps.
+**Browser Sessions** are live browser instances that maintain state across multiple operations. Cookies, storage, and page context persist for the duration of the session (up to 24 hours). They're useful for chaining operations in real-time or allowing human intervention between steps.
```python
browser = await skyvern.launch_cloud_browser()
diff --git a/docs/snippets/introduction-content.mdx b/docs/snippets/introduction-content.mdx
index d1ee485f5..18c0a8b31 100644
--- a/docs/snippets/introduction-content.mdx
+++ b/docs/snippets/introduction-content.mdx
@@ -48,7 +48,7 @@ Most browser automation breaks down at authentication, CAPTCHAs, or dynamic cont
**Proxy and geolocation.** Residential proxies route through real IPs in 30+ countries. Set `proxy_location` per task when you need to appear from a specific region.
-**Browser state persistence.** Sessions keep a live browser open across multiple tasks for up to 4 hours, useful when you need to chain tasks that share login state. Profiles snapshot cookies, auth tokens, and local storage into a reusable package you can restore on future runs, so you don't re-authenticate every time.
+**Browser state persistence.** Sessions keep a live browser open across multiple tasks for up to 24 hours, useful when you need to chain tasks that share login state. Profiles snapshot cookies, auth tokens, and local storage into a reusable package you can restore on future runs, so you don't re-authenticate every time.
**Multi-step agents.** When a single task isn't enough, Agents let you chain blocks together: navigate, login, loop through a list, extract data, branch on conditions, send emails. Agents are parameterized and version-controlled. You can build them visually in the dashboard or define them through the API.
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx b/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx
index 399be6b84..073a2ddbf 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsTotpTab.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useState } from "react";
+import { useContext, useMemo, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Link } from "react-router-dom";
import { ArrowRightIcon } from "@radix-ui/react-icons";
@@ -32,6 +32,8 @@ import {
import { Skeleton } from "@/components/ui/skeleton";
import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";
import { GmailIcon } from "@/components/icons/GmailIcon";
+import { OutlookIcon } from "@/components/icons/OutlookIcon";
+import CloudContext from "@/store/CloudContext";
type OtpTypeFilter = "all" | OtpTypeValue;
@@ -87,6 +89,7 @@ function renderCodeContent(code: TotpCode) {
}
function CredentialsTotpTab() {
+ const isCloud = useContext(CloudContext);
const [identifierFilter, setIdentifierFilter] = useState("");
const [otpTypeFilter, setOtpTypeFilter] = useState<OtpTypeFilter>("all");
const [limit, setLimit] = useState<(typeof LIMIT_OPTIONS)[number]>(50);
@@ -121,22 +124,24 @@ function CredentialsTotpTab() {
<div className="rounded-lg border border-slate-700 bg-slate-elevation1 p-5">
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<div className="flex items-start gap-3">
- <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border border-neutral-200 bg-white dark:border-slate-700">
- <GmailIcon className="size-7" />
+ <div className="flex h-10 shrink-0 items-center justify-center gap-0.5 rounded-md border border-neutral-200 bg-white px-1.5 dark:border-slate-700">
+ <GmailIcon className={isCloud ? "size-6" : "size-7"} />
+ {isCloud && <OutlookIcon className="size-6" />}
</div>
<div>
<h2 className="text-base font-semibold">
- Connect Gmail for automatic 2FA
+ Automatic 2FA from your inbox
</h2>
<p className="mt-1 max-w-2xl text-sm text-neutral-600 dark:text-slate-400">
- Skyvern can find verification codes and magic links in a
- connected Gmail inbox without manual forwarding.
+ {isCloud
+ ? "Skyvern can find verification codes and magic links in a connected Gmail or Outlook inbox without manual forwarding."
+ : "Skyvern can find verification codes and magic links in a connected Gmail inbox without manual forwarding."}
</p>
</div>
</div>
<Button asChild size="sm" className="shrink-0">
- <Link to="/integrations?query=gmail">
- Connect Gmail <ArrowRightIcon className="ml-1.5 size-4" />
+ <Link to="/integrations">
+ Connect an inbox <ArrowRightIcon className="ml-1.5 size-4" />
</Link>
</Button>
</div>
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 98c02360f..c872a3178 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -53,7 +53,6 @@ from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
from skyvern.forge.sdk.services import (
google_drive_service,
- google_gmail_service,
google_oauth_service,
google_sheets_service,
microsoft_oauth_service,
@@ -63,7 +62,7 @@ from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResult
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVar
from skyvern.schemas.workflows import BlockResult, FileStorageType, FileUploadDestination
-from skyvern.services.otp_gmail import GmailOTPVerificationContext
+from skyvern.services.otp_email import EmailOTPSearchError, EmailOTPVerificationContext, build_email_otp_sources
from skyvern.utils.url_validators import pinned_ip_client
from skyvern.webeye.actions.actions import Action
from skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelection, resolve_engine_selection_for_task
@@ -87,9 +86,9 @@ LOG = structlog.get_logger()
# Playwright's always-on ffmpeg VP8 encoder scales CPU with pixel count; 720p is the
# legibility / CPU tradeoff point that the BROWSER_RECORDING_720P flag opts a run into.
RECORDING_VIDEO_SIZE_720P: dict[str, int] = {"width": 1280, "height": 720}
-GMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS = 30
-GMAIL_OTP_MAX_RESULTS = 5
-GMAIL_OTP_SEARCH_INTERVAL_SECONDS = 30
+EMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS = 30
+EMAIL_OTP_MAX_RESULTS = 5
+EMAIL_OTP_SEARCH_INTERVAL_SECONDS = 30
_LLM_CALL_TIMEOUT_SECONDS = 30 # 30s
@@ -1659,7 +1658,7 @@ class AgentFunction:
)
return None
- async def get_otp_value_from_gmail(
+ async def get_otp_value_from_email(
self,
*,
organization_id: str,
@@ -1667,109 +1666,112 @@ class AgentFunction:
workflow_id: str | None = None,
workflow_run_id: str | None = None,
created_after: datetime | None = None,
- context: GmailOTPVerificationContext | None = None,
+ context: EmailOTPVerificationContext | None = None,
) -> OTPValue | None:
- """Find an OTP in connected Gmail inboxes for a single polling window."""
+ """Find an OTP in connected email inboxes (all configured sources) for a single polling window."""
if "@" not in totp_identifier:
return None
from skyvern.services.otp_service import InsufficientCreditsForOTPParse, parse_otp_login
- lookup_context = context or GmailOTPVerificationContext()
- now = datetime.now(timezone.utc)
- required_scopes = list(google_oauth_service.GOOGLE_GMAIL_SCOPES)
- credential_cache_age = (
- (now - lookup_context.credential_ids_loaded_at).total_seconds()
- if lookup_context.credential_ids_loaded_at
- else None
- )
- if (
- lookup_context.credential_ids is None
- or credential_cache_age is None
- or credential_cache_age >= GMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS
- ):
- try:
- lookup_context.credential_ids = [
- credential.id
- for credential in await google_oauth_service.get_credentials_for_org(organization_id)
- if google_oauth_service.has_required_scopes(credential.scopes_granted, required_scopes)
- ]
- lookup_context.credential_ids_loaded_at = now
- except Exception:
- LOG.warning("Failed to list Google OAuth credentials for Gmail OTP lookup", exc_info=True)
- return None
-
- async with httpx.AsyncClient(timeout=20.0) as gmail_client:
- for credential_id in lookup_context.credential_ids or []:
- last_searched_at = lookup_context.last_searched_at_by_credential.get(credential_id)
- if last_searched_at and (now - last_searched_at).total_seconds() < GMAIL_OTP_SEARCH_INTERVAL_SECONDS:
- continue
- lookup_context.last_searched_at_by_credential[credential_id] = now
- try:
- google_credentials = await self.get_google_workspace_credentials(
- organization_id=organization_id,
- credential_id=credential_id,
- required_scopes=required_scopes,
- )
- if not google_credentials or not google_credentials.token:
+ lookup_context = context or EmailOTPVerificationContext()
+ sources = build_email_otp_sources(self)
+ async with httpx.AsyncClient(timeout=20.0) as client:
+ for source in sources:
+ source_context = lookup_context.for_source(source.name)
+ now = datetime.now(timezone.utc)
+ credential_cache_age = (
+ (now - source_context.credential_ids_loaded_at).total_seconds()
+ if source_context.credential_ids_loaded_at
+ else None
+ )
+ if (
+ source_context.credential_ids is None
+ or credential_cache_age is None
+ or credential_cache_age >= EMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS
+ ):
+ try:
+ source_context.credential_ids = await source.list_credential_ids(organization_id)
+ source_context.credential_ids_loaded_at = now
+ except Exception:
+ LOG.warning("Failed to list email OTP credentials", source=source.name, exc_info=True)
continue
- candidates = await google_gmail_service.search_recent_otp_messages(
- access_token=google_credentials.token,
- totp_identifier=totp_identifier,
- created_after=created_after,
- max_results=GMAIL_OTP_MAX_RESULTS,
- client=gmail_client,
- )
- except google_gmail_service.GmailAPIError as exc:
- LOG.warning(
- "Gmail OTP lookup failed",
- credential_id=credential_id,
- status=exc.status,
- code=exc.code,
- )
- continue
- except Exception:
- LOG.warning(
- "Unexpected Gmail OTP lookup failure",
- credential_id=credential_id,
- exc_info=True,
- )
- continue
- for candidate in candidates:
- if lookup_context.has_seen_message_id(candidate.message_id):
+ for credential_id in source_context.credential_ids or []:
+ last_searched_at = source_context.last_searched_at_by_credential.get(credential_id)
+ if (
+ last_searched_at
+ and (now - last_searched_at).total_seconds() < EMAIL_OTP_SEARCH_INTERVAL_SECONDS
+ ):
continue
+ source_context.last_searched_at_by_credential[credential_id] = now
try:
- otp_value = await parse_otp_login(candidate.content, organization_id)
- except InsufficientCreditsForOTPParse:
- # Credit eligibility is organization-wide, so stop this scan.
- # Remember the candidate so later polls do not retry the same material.
- lookup_context.remember_message_id(candidate.message_id)
- return None
+ candidates = await source.search_recent_otp_messages(
+ organization_id=organization_id,
+ credential_id=credential_id,
+ totp_identifier=totp_identifier,
+ created_after=created_after,
+ max_results=EMAIL_OTP_MAX_RESULTS,
+ context=source_context,
+ client=client,
+ )
+ except EmailOTPSearchError as exc:
+ LOG.warning(
+ "Email OTP lookup failed",
+ source=source.name,
+ credential_id=credential_id,
+ status=exc.status,
+ code=exc.code,
+ )
+ continue
except Exception:
LOG.warning(
- "Failed to parse Gmail OTP candidate",
+ "Unexpected email OTP lookup failure",
+ source=source.name,
credential_id=credential_id,
- message_id=candidate.message_id,
exc_info=True,
)
continue
- lookup_context.remember_message_id(candidate.message_id)
- if otp_value:
+
+ for candidate in candidates:
+ if source_context.has_seen_message(credential_id, candidate.message_id):
+ continue
try:
- await app.DATABASE.otp.create_otp_code(
- organization_id,
- totp_identifier,
- otp_value.value,
- otp_value.value,
- otp_value.get_otp_type(),
- workflow_id=workflow_id,
- workflow_run_id=workflow_run_id,
- source="gmail",
- )
+ otp_value = await parse_otp_login(candidate.content, organization_id)
+ except InsufficientCreditsForOTPParse:
+ source_context.remember_message(credential_id, candidate.message_id)
+ return None
except Exception:
- LOG.warning("Failed to persist Gmail OTP code", credential_id=credential_id, exc_info=True)
- return otp_value
+ LOG.warning(
+ "Failed to parse email OTP candidate",
+ source=source.name,
+ credential_id=credential_id,
+ message_id=candidate.message_id,
+ exc_info=True,
+ )
+ continue
+ source_context.remember_message(credential_id, candidate.message_id)
+ if otp_value:
+ try:
+ # Persist only the resolved OTP value to avoid retaining raw email bodies.
+ await app.DATABASE.otp.create_otp_code(
+ organization_id,
+ totp_identifier,
+ otp_value.value,
+ otp_value.value,
+ otp_value.get_otp_type(),
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ source=source.name,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to persist email OTP code",
+ source=source.name,
+ credential_id=credential_id,
+ exc_info=True,
+ )
+ return otp_value
return None
diff --git a/skyvern/services/email/outlook.py b/skyvern/services/email/outlook.py
index e82427362..d814c2bed 100644
--- a/skyvern/services/email/outlook.py
+++ b/skyvern/services/email/outlook.py
@@ -1,6 +1,9 @@
import asyncio
+import re
+from collections.abc import Collection
+from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from email.utils import parsedate_to_datetime
+from email.utils import getaddresses, parsedate_to_datetime
from typing import Any
from urllib.parse import quote, urlparse
@@ -27,6 +30,28 @@ _RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
_MAX_ATTEMPTS = 3
_MAX_BACKOFF_SECONDS = 5.0
_WELL_KNOWN_FOLDERS = {"inbox", "drafts", "sentitems", "deleteditems", "junkemail", "archive", "clutter", "outbox"}
+_MAX_OTP_SEARCH_PAGES = 4
+_MAX_OTP_SEARCH_FETCHED = 100
+_OTP_EXCLUDED_FOLDER_IDS_STATE_KEY = "otp_excluded_folder_ids"
+_OTP_MAILBOX_IDENTITIES_STATE_KEY = "otp_mailbox_identities"
+_SAFE_EMAIL_IDENTIFIER = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+$")
+_OTP_KEYWORD_PATTERN = re.compile(
+ r"(?<![A-Za-z0-9])(?:verification|verify|code|passcode|otp|2fa|one(?:[\s-]+)time|password)(?![A-Za-z0-9])",
+ re.IGNORECASE,
+)
+# Only EOP-stripped headers are trusted for recipient matching.
+_DELIVERY_HEADER_NAMES = {
+ "x-ms-exchange-organization-originalenveloperecipient",
+ "x-ms-exchange-organization-originalenveloperecipients",
+ "x-ms-exchange-organization-originalto",
+}
+
+
+@dataclass(frozen=True)
+class OutlookMessageCandidate:
+ message_id: str
+ content: str
+ received_datetime: datetime
class OutlookAPIError(RuntimeError):
@@ -62,14 +87,18 @@ async def _get_json(
*,
access_token: str,
params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
) -> dict[str, Any]:
response: httpx.Response | None = None
for attempt in range(1, _MAX_ATTEMPTS + 1):
try:
+ headers = {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
+ if prefer:
+ headers["Prefer"] = ", ".join(prefer)
response = await client.get(
url,
params=params,
- headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"},
+ headers=headers,
)
except (httpx.TransportError, httpx.TimeoutException) as exc:
if attempt == _MAX_ATTEMPTS:
@@ -252,6 +281,394 @@ def _recipient_addresses(recipients: list[Any] | None) -> list[str]:
return addresses
+def _as_utc(value: datetime) -> datetime:
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+
+
+def _graph_datetime(value: object) -> datetime | None:
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ return _as_utc(parsed)
+
+
+def _graph_datetime_parameter(value: datetime) -> str:
+ return _as_utc(value).isoformat().replace("+00:00", "Z")
+
+
+def _normalize_email_address(value: str) -> str:
+ normalized = value.strip()
+ if normalized[:5].casefold() == "smtp:":
+ normalized = normalized[5:].strip()
+ return normalized.casefold()
+
+
+def _message_recipient_addresses(message: dict[str, Any]) -> set[str]:
+ addresses: set[str] = set()
+ for field in ("toRecipients", "ccRecipients", "bccRecipients"):
+ raw_recipients = message.get(field)
+ recipients = raw_recipients if isinstance(raw_recipients, list) else []
+ addresses.update(
+ normalized
+ for address in _recipient_addresses(recipients)
+ if (normalized := _normalize_email_address(address))
+ )
+
+ raw_headers = message.get("internetMessageHeaders")
+ headers = raw_headers if isinstance(raw_headers, list) else []
+ for header in headers:
+ if not isinstance(header, dict):
+ continue
+ name = header.get("name")
+ value = header.get("value")
+ if not isinstance(name, str) or name.casefold() not in _DELIVERY_HEADER_NAMES or not isinstance(value, str):
+ continue
+ addresses.update(
+ normalized for _, address in getaddresses([value]) if (normalized := _normalize_email_address(address))
+ )
+ return addresses
+
+
+def _mailbox_identity_set(payload: dict[str, Any]) -> set[str]:
+ raw_values: list[str] = []
+ for field in ("mail", "userPrincipalName"):
+ value = payload.get(field)
+ if isinstance(value, str):
+ raw_values.append(value)
+ for field in ("proxyAddresses",):
+ values = payload.get(field)
+ if isinstance(values, list):
+ raw_values.extend(value for value in values if isinstance(value, str))
+ return {normalized for value in raw_values if (normalized := _normalize_email_address(value))}
+
+
+async def _load_mailbox_identities(client: httpx.AsyncClient, access_token: str) -> tuple[set[str], bool]:
+ try:
+ payload = await _get_json(
+ client,
+ f"{GRAPH_API_BASE}/me",
+ access_token=access_token,
+ params={"$select": "mail,userPrincipalName,proxyAddresses"},
+ )
+ except (OutlookAPIError, ValueError) as exc:
+ if isinstance(exc, OutlookAPIError) and exc.code == "reconnect_required":
+ raise
+ LOG.warning(
+ "Failed to resolve Outlook mailbox identities for OTP search",
+ status=exc.status if isinstance(exc, OutlookAPIError) else None,
+ code=exc.code if isinstance(exc, OutlookAPIError) else None,
+ )
+ return set(), False
+ return _mailbox_identity_set(payload), True
+
+
+async def _load_well_known_folder_id(
+ client: httpx.AsyncClient,
+ access_token: str,
+ folder: str,
+) -> tuple[str | None, bool]:
+ try:
+ payload = await _get_json(
+ client,
+ f"{GRAPH_API_BASE}/me/mailFolders/{folder}",
+ access_token=access_token,
+ params={"$select": "id"},
+ )
+ except (OutlookAPIError, ValueError) as exc:
+ if isinstance(exc, OutlookAPIError) and exc.code == "reconnect_required":
+ raise
+ LOG.warning(
+ "Failed to resolve excluded Outlook folder for OTP search",
+ folder=folder,
+ status=exc.status if isinstance(exc, OutlookAPIError) else None,
+ code=exc.code if isinstance(exc, OutlookAPIError) else None,
+ )
+ return None, False
+ folder_id = payload.get("id")
+ resolved_folder_id = folder_id if isinstance(folder_id, str) and folder_id else None
+ return resolved_folder_id, resolved_folder_id is not None
+
+
+async def _load_excluded_folder_ids(client: httpx.AsyncClient, access_token: str) -> tuple[set[str], bool]:
+ folder_results = await asyncio.gather(
+ _load_well_known_folder_id(client, access_token, "junkemail"),
+ _load_well_known_folder_id(client, access_token, "deleteditems"),
+ _load_well_known_folder_id(client, access_token, "sentitems"),
+ )
+ return (
+ {folder_id for folder_id, _ in folder_results if folder_id},
+ all(succeeded for _, succeeded in folder_results),
+ )
+
+
+def _cached_string_set(state: dict, key: str) -> set[str] | None:
+ if key not in state:
+ return None
+ value = state[key]
+ if not isinstance(value, (list, set, tuple)):
+ return set()
+ return {item for item in value if isinstance(item, str)}
+
+
+async def _otp_search_state(
+ client: httpx.AsyncClient,
+ access_token: str,
+ state: dict,
+) -> tuple[set[str], set[str], bool]:
+ excluded_folder_ids = _cached_string_set(state, _OTP_EXCLUDED_FOLDER_IDS_STATE_KEY)
+ mailbox_identities = _cached_string_set(state, _OTP_MAILBOX_IDENTITIES_STATE_KEY)
+ exclusions_resolved = excluded_folder_ids is not None
+ if excluded_folder_ids is None:
+ excluded_folder_ids, exclusions_resolved = await _load_excluded_folder_ids(client, access_token)
+ if exclusions_resolved:
+ state[_OTP_EXCLUDED_FOLDER_IDS_STATE_KEY] = excluded_folder_ids
+ if mailbox_identities is None:
+ mailbox_identities, succeeded = await _load_mailbox_identities(client, access_token)
+ if succeeded:
+ state[_OTP_MAILBOX_IDENTITIES_STATE_KEY] = mailbox_identities
+ return excluded_folder_ids, mailbox_identities, exclusions_resolved
+
+
+def _otp_scan_metadata(
+ message: dict[str, Any],
+ *,
+ cutoff: datetime,
+ excluded_folder_ids: set[str],
+) -> tuple[str, datetime] | None:
+ message_id = message.get("id")
+ if not isinstance(message_id, str) or not message_id:
+ return None
+ received_datetime = _graph_datetime(message.get("receivedDateTime"))
+ if received_datetime is None or received_datetime < cutoff or message.get("isDraft") is True:
+ return None
+ parent_folder_id = message.get("parentFolderId")
+ if isinstance(parent_folder_id, str) and parent_folder_id in excluded_folder_ids:
+ return None
+ return message_id, received_datetime
+
+
+def _otp_candidate(
+ message: dict[str, Any],
+ *,
+ message_id: str,
+ received_datetime: datetime,
+) -> tuple[OutlookMessageCandidate, set[str]] | None:
+ raw_subject = message.get("subject")
+ subject = raw_subject if isinstance(raw_subject, str) else ""
+ raw_preview = message.get("bodyPreview")
+ preview = raw_preview if isinstance(raw_preview, str) else ""
+ raw_body = message.get("body")
+ body = raw_body.get("content") if isinstance(raw_body, dict) else ""
+ body_content = body if isinstance(body, str) else ""
+ if not _OTP_KEYWORD_PATTERN.search("\n".join((subject, preview, body_content))):
+ return None
+ content = "\n".join(
+ part
+ for part in (
+ f"Subject: {subject}" if subject else "",
+ f"Snippet: {preview}" if preview else "",
+ f"Body:\n{body_content}" if body_content else "",
+ )
+ if part
+ ).strip()
+ if not content:
+ return None
+ return (
+ OutlookMessageCandidate(
+ message_id=message_id,
+ content=content,
+ received_datetime=received_datetime,
+ ),
+ _message_recipient_addresses(message),
+ )
+
+
+def _otp_message_has_body_content(message: dict[str, Any]) -> bool:
+ body = message.get("body")
+ if not isinstance(body, dict):
+ return False
+ content = body.get("content")
+ return isinstance(content, str) and bool(content)
+
+
+async def _hydrate_otp_message_body(
+ client: httpx.AsyncClient,
+ *,
+ access_token: str,
+ message: dict[str, Any],
+ prefer: tuple[str, ...],
+) -> dict[str, Any] | None:
+ if _otp_message_has_body_content(message):
+ return message
+ message_id = message.get("id")
+ if not isinstance(message_id, str) or not message_id:
+ return message
+ payload = await _get_json(
+ client,
+ f"{GRAPH_API_BASE}/me/messages/{quote(message_id, safe='')}",
+ access_token=access_token,
+ params={"$select": "id,subject,bodyPreview,body,receivedDateTime"},
+ prefer=prefer,
+ )
+ if not isinstance(payload.get("body"), dict):
+ return None
+ hydrated = dict(message)
+ for field in ("subject", "bodyPreview", "body", "receivedDateTime"):
+ if field in payload:
+ hydrated[field] = payload[field]
+ return hydrated
+
+
+async def search_recent_otp_messages(
+ *,
+ access_token: str,
+ totp_identifier: str,
+ created_after: datetime | None = None,
+ max_results: int = 10,
+ client: httpx.AsyncClient | None = None,
+ state: dict | None = None,
+ excluded_message_ids: Collection[str] | None = None,
+) -> list[OutlookMessageCandidate]:
+ identifier = totp_identifier.strip()
+ if not _SAFE_EMAIL_IDENTIFIER.fullmatch(identifier):
+ return []
+ cutoff = _as_utc(created_after) if created_after else datetime.now(UTC) - timedelta(hours=24)
+ excluded_ids = set(excluded_message_ids or ())
+ max_results_clamped = max(1, min(max_results, 20))
+ page_size = max(25, min(50, max_results_clamped * 5))
+ params: dict[str, Any] = {
+ "$filter": f"receivedDateTime ge {_graph_datetime_parameter(cutoff - timedelta(seconds=1))}",
+ "$orderby": "receivedDateTime desc",
+ "$select": (
+ "id,parentFolderId,isDraft,subject,bodyPreview,receivedDateTime,"
+ "toRecipients,ccRecipients,bccRecipients,internetMessageHeaders"
+ ),
+ "$top": page_size,
+ }
+ prefer = ('IdType="ImmutableId"', 'outlook.body-content-type="html"')
+
+ async def _search(client_: httpx.AsyncClient) -> list[OutlookMessageCandidate]:
+ lookup_state = state if state is not None else {}
+ excluded_folder_ids, mailbox_identities, exclusions_resolved = await _otp_search_state(
+ client_, access_token, lookup_state
+ )
+ if not exclusions_resolved:
+ # Scanning without exclusions would parse attacker-influenceable junk mail.
+ LOG.warning("Skipping Outlook OTP scan; folder exclusions unresolved")
+ return []
+ normalized_identifier = _normalize_email_address(identifier)
+ strong_candidates: list[OutlookMessageCandidate] = []
+ fallback_candidates: list[OutlookMessageCandidate] = []
+ request_url: str | None = f"{GRAPH_API_BASE}/me/messages"
+ request_params: dict[str, Any] | None = params
+ page_count = 0
+ fetched_count = 0
+ truncated = False
+
+ while request_url and len(strong_candidates) < max_results_clamped:
+ payload = await _get_json(
+ client_,
+ request_url,
+ access_token=access_token,
+ params=request_params,
+ prefer=prefer,
+ )
+ page_count += 1
+ raw_items = payload.get("value")
+ items = raw_items if isinstance(raw_items, list) else []
+ for index, item in enumerate(items):
+ if fetched_count >= _MAX_OTP_SEARCH_FETCHED:
+ truncated = True
+ break
+ fetched_count += 1
+ if not isinstance(item, dict):
+ continue
+ scan_metadata = _otp_scan_metadata(
+ item,
+ cutoff=cutoff,
+ excluded_folder_ids=excluded_folder_ids,
+ )
+ if scan_metadata is None:
+ continue
+ message_id, received_datetime = scan_metadata
+ if message_id in excluded_ids:
+ continue
+ observable_recipients = _message_recipient_addresses(item)
+ could_match = normalized_identifier in observable_recipients or (
+ normalized_identifier in mailbox_identities and not observable_recipients
+ )
+ if could_match and not _otp_message_has_body_content(item):
+ try:
+ hydrated_item = await _hydrate_otp_message_body(
+ client_,
+ access_token=access_token,
+ message=item,
+ prefer=prefer,
+ )
+ except (OutlookAPIError, ValueError) as exc:
+ if isinstance(exc, OutlookAPIError) and exc.code == "reconnect_required":
+ raise
+ LOG.warning(
+ "Failed to hydrate Outlook OTP message body",
+ status=exc.status if isinstance(exc, OutlookAPIError) else None,
+ code=exc.code if isinstance(exc, OutlookAPIError) else None,
+ )
+ # Skipping avoids burning the candidate's one-shot seen-key on a bodyless parse.
+ continue
+ if hydrated_item is None:
+ LOG.warning("Failed to hydrate Outlook OTP message body")
+ # Skipping avoids burning the candidate's one-shot seen-key on a bodyless parse.
+ continue
+ item = hydrated_item
+ candidate_match = _otp_candidate(
+ item,
+ message_id=message_id,
+ received_datetime=received_datetime,
+ )
+ if candidate_match is None:
+ continue
+ candidate, observable_recipients = candidate_match
+ if normalized_identifier in observable_recipients:
+ strong_candidates.append(candidate)
+ if len(strong_candidates) >= max_results_clamped:
+ break
+ elif normalized_identifier in mailbox_identities and not observable_recipients:
+ fallback_candidates.append(candidate)
+ if index + 1 < len(items) and fetched_count >= _MAX_OTP_SEARCH_FETCHED:
+ truncated = True
+ break
+ if len(strong_candidates) >= max_results_clamped:
+ break
+ next_link = _validated_next_link(payload.get("@odata.nextLink"))
+ if next_link is None:
+ break
+ if page_count >= _MAX_OTP_SEARCH_PAGES or fetched_count >= _MAX_OTP_SEARCH_FETCHED:
+ truncated = True
+ break
+ request_url = next_link
+ request_params = None
+
+ if truncated:
+ LOG.debug(
+ "Truncated Outlook OTP pagination",
+ pages=page_count,
+ fetched=fetched_count,
+ max_pages=_MAX_OTP_SEARCH_PAGES,
+ max_fetched=_MAX_OTP_SEARCH_FETCHED,
+ )
+ strong_candidates.sort(key=lambda item: item.received_datetime, reverse=True)
+ fallback_candidates.sort(key=lambda item: item.received_datetime, reverse=True)
+ return (strong_candidates + fallback_candidates)[:max_results_clamped]
+
+ if client is None:
+ async with httpx.AsyncClient(timeout=20.0) as owned_client:
+ return await _search(owned_client)
+ return await _search(client)
+
+
async def _attachments(
client: httpx.AsyncClient,
*,
diff --git a/skyvern/services/otp_email.py b/skyvern/services/otp_email.py
new file mode 100644
index 000000000..ecf9d3079
--- /dev/null
+++ b/skyvern/services/otp_email.py
@@ -0,0 +1,240 @@
+from __future__ import annotations
+
+from collections import deque
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import TYPE_CHECKING, Protocol
+
+import httpx
+from google.oauth2.credentials import Credentials
+
+from skyvern.forge.sdk.services import google_gmail_service, google_oauth_service, microsoft_oauth_service
+from skyvern.services.email import outlook
+
+if TYPE_CHECKING:
+ from skyvern.forge.agent_functions import AgentFunction
+
+MAX_SEEN_EMAIL_MESSAGE_IDS = 500
+
+
+@dataclass(frozen=True)
+class EmailOTPCandidate:
+ message_id: str
+ content: str
+
+
+class EmailOTPSearchError(Exception):
+ def __init__(
+ self,
+ message: str,
+ *,
+ source: str,
+ status: int | None = None,
+ code: str | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.source = source
+ self.status = status
+ self.code = code
+
+
+@dataclass
+class EmailOTPSourceContext:
+ """Per-source polling cache passed through the AgentFunction hook."""
+
+ credential_ids: list[str] | None = None
+ credential_ids_loaded_at: datetime | None = None
+ last_searched_at_by_credential: dict[str, datetime] = field(default_factory=dict)
+ seen_message_keys: set[tuple[str, str]] = field(default_factory=set)
+ seen_message_key_order: deque[tuple[str, str]] = field(default_factory=deque)
+ provider_state: dict[str, dict] = field(default_factory=dict)
+
+ def has_seen_message(self, credential_id: str, message_id: str) -> bool:
+ return (credential_id, message_id) in self.seen_message_keys
+
+ def seen_message_ids_for_credential(self, credential_id: str) -> set[str]:
+ return {
+ message_id
+ for candidate_credential_id, message_id in self.seen_message_keys
+ if candidate_credential_id == credential_id
+ }
+
+ def remember_message(self, credential_id: str, message_id: str) -> None:
+ key = (credential_id, message_id)
+ if key in self.seen_message_keys:
+ return
+ self.seen_message_keys.add(key)
+ self.seen_message_key_order.append(key)
+ while len(self.seen_message_key_order) > MAX_SEEN_EMAIL_MESSAGE_IDS:
+ self.seen_message_keys.discard(self.seen_message_key_order.popleft())
+
+
+@dataclass
+class EmailOTPVerificationContext:
+ """Whole-poll cache: one EmailOTPSourceContext per source name."""
+
+ per_source: dict[str, EmailOTPSourceContext] = field(default_factory=dict)
+
+ def for_source(self, source_name: str) -> EmailOTPSourceContext:
+ return self.per_source.setdefault(source_name, EmailOTPSourceContext())
+
+
+class EmailOTPSource(Protocol):
+ name: str
+
+ async def list_credential_ids(self, organization_id: str) -> list[str]: ...
+
+ async def search_recent_otp_messages(
+ self,
+ *,
+ organization_id: str,
+ credential_id: str,
+ totp_identifier: str,
+ created_after: datetime | None,
+ max_results: int,
+ context: EmailOTPSourceContext,
+ client: httpx.AsyncClient,
+ ) -> list[EmailOTPCandidate]: ...
+
+
+class _GoogleCredentialGetter(Protocol):
+ async def __call__(
+ self,
+ organization_id: str,
+ credential_id: str,
+ required_scopes: list[str] | None = None,
+ ) -> Credentials | None: ...
+
+
+class _MicrosoftCredentialGetter(Protocol):
+ async def __call__(
+ self,
+ organization_id: str,
+ credential_id: str,
+ required_scopes: list[str] | None = None,
+ ) -> str | None: ...
+
+
+class GmailOTPSource:
+ name = "gmail"
+
+ def __init__(self, get_credentials: _GoogleCredentialGetter) -> None:
+ self._get_credentials = get_credentials
+
+ async def list_credential_ids(self, organization_id: str) -> list[str]:
+ return [
+ credential.id
+ for credential in await google_oauth_service.get_credentials_for_org(organization_id)
+ if google_oauth_service.has_required_scopes(
+ credential.scopes_granted,
+ google_oauth_service.GOOGLE_GMAIL_SCOPES,
+ )
+ ]
+
+ async def search_recent_otp_messages(
+ self,
+ *,
+ organization_id: str,
+ credential_id: str,
+ totp_identifier: str,
+ created_after: datetime | None,
+ max_results: int,
+ context: EmailOTPSourceContext,
+ client: httpx.AsyncClient,
+ ) -> list[EmailOTPCandidate]:
+ excluded_message_ids = context.seen_message_ids_for_credential(credential_id)
+ credentials = await self._get_credentials(
+ organization_id=organization_id,
+ credential_id=credential_id,
+ required_scopes=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
+ )
+ if not credentials or not credentials.token:
+ return []
+ try:
+ candidates = await google_gmail_service.search_recent_otp_messages(
+ access_token=credentials.token,
+ totp_identifier=totp_identifier,
+ created_after=created_after,
+ max_results=max_results,
+ client=client,
+ )
+ except google_gmail_service.GmailAPIError as exc:
+ raise EmailOTPSearchError(
+ str(exc),
+ source=self.name,
+ status=exc.status,
+ code=exc.code,
+ ) from exc
+ return [
+ EmailOTPCandidate(
+ message_id=candidate.message_id,
+ content=candidate.content,
+ )
+ for candidate in candidates
+ if candidate.message_id not in excluded_message_ids
+ ]
+
+
+class OutlookOTPSource:
+ name = "outlook"
+
+ def __init__(self, get_credentials: _MicrosoftCredentialGetter) -> None:
+ self._get_credentials = get_credentials
+
+ async def list_credential_ids(self, organization_id: str) -> list[str]:
+ return [
+ credential.id
+ for credential in await microsoft_oauth_service.get_credentials_for_org(organization_id)
+ if microsoft_oauth_service.has_required_scopes(credential.scopes_granted, ["Mail.Read"])
+ ]
+
+ async def search_recent_otp_messages(
+ self,
+ *,
+ organization_id: str,
+ credential_id: str,
+ totp_identifier: str,
+ created_after: datetime | None,
+ max_results: int,
+ context: EmailOTPSourceContext,
+ client: httpx.AsyncClient,
+ ) -> list[EmailOTPCandidate]:
+ access_token = await self._get_credentials(
+ organization_id=organization_id,
+ credential_id=credential_id,
+ required_scopes=["Mail.Read"],
+ )
+ if not access_token:
+ return []
+ excluded_message_ids = context.seen_message_ids_for_credential(credential_id)
+ try:
+ candidates = await outlook.search_recent_otp_messages(
+ access_token=access_token,
+ totp_identifier=totp_identifier,
+ created_after=created_after,
+ max_results=max_results,
+ client=client,
+ state=context.provider_state.setdefault(credential_id, {}),
+ excluded_message_ids=excluded_message_ids,
+ )
+ except outlook.OutlookAPIError as exc:
+ raise EmailOTPSearchError(
+ str(exc),
+ source=self.name,
+ status=exc.status,
+ code=exc.code,
+ ) from exc
+ return [
+ EmailOTPCandidate(
+ message_id=candidate.message_id,
+ content=candidate.content,
+ )
+ for candidate in candidates
+ ]
+
+
+def build_email_otp_sources(agent_function: AgentFunction) -> list[EmailOTPSource]:
+ return [
+ GmailOTPSource(agent_function.get_google_workspace_credentials),
+ OutlookOTPSource(agent_function.get_microsoft_credentials),
+ ]
diff --git a/skyvern/services/otp_gmail.py b/skyvern/services/otp_gmail.py
deleted file mode 100644
index f39ce5044..000000000
--- a/skyvern/services/otp_gmail.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from collections import deque
-from dataclasses import dataclass, field
-from datetime import datetime
-
-MAX_SEEN_GMAIL_MESSAGE_IDS = 500
-
-
-@dataclass
-class GmailOTPVerificationContext:
- """Per-poll Gmail OTP lookup cache passed through the AgentFunction hook."""
-
- credential_ids: list[str] | None = None
- credential_ids_loaded_at: datetime | None = None
- last_searched_at_by_credential: dict[str, datetime] = field(default_factory=dict)
- seen_message_ids: set[str] = field(default_factory=set)
- seen_message_id_order: deque[str] = field(default_factory=deque)
-
- def has_seen_message_id(self, message_id: str) -> bool:
- return message_id in self.seen_message_ids
-
- def remember_message_id(self, message_id: str) -> None:
- if message_id in self.seen_message_ids:
- return
- self.seen_message_ids.add(message_id)
- self.seen_message_id_order.append(message_id)
- while len(self.seen_message_id_order) > MAX_SEEN_GMAIL_MESSAGE_IDS:
- self.seen_message_ids.discard(self.seen_message_id_order.popleft())
diff --git a/skyvern/services/otp_service.py b/skyvern/services/otp_service.py
index a3a6594c1..5575ab59b 100644
--- a/skyvern/services/otp_service.py
+++ b/skyvern/services/otp_service.py
@@ -23,7 +23,7 @@ from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.schemas.organizations import OrganizationAuthToken
from skyvern.forge.sdk.schemas.totp_codes import OTPType, RawTOTPCode, TOTPCode
from skyvern.forge.sdk.services.credentials import generate_totp_code, is_unresolved_totp_placeholder
-from skyvern.services.otp_gmail import GmailOTPVerificationContext
+from skyvern.services.otp_email import EmailOTPVerificationContext
LOG = structlog.get_logger()
@@ -463,7 +463,7 @@ async def poll_otp_value(
timeout = timedelta(minutes=settings.VERIFICATION_CODE_POLLING_TIMEOUT_MINS)
start_datetime = datetime.utcnow()
timeout_datetime = start_datetime + timeout
- gmail_created_after = created_after or start_datetime
+ email_created_after = created_after or start_datetime
db_created_after = created_after
LOG.info(
"Polling otp value",
@@ -474,7 +474,7 @@ async def poll_otp_value(
consecutive_failures = 0
last_error_reason: str | None = None
org_token: OrganizationAuthToken | None = None
- gmail_otp_context = GmailOTPVerificationContext()
+ email_otp_context = EmailOTPVerificationContext()
raw_otp_context = RawOTPVerificationContext()
while True:
await asyncio.sleep(10)
@@ -499,11 +499,11 @@ async def poll_otp_value(
)
otp_value: OTPValue | None = None
try:
- # Keep an explicit webhook as the primary source. Gmail and DB are
- # intentional backstops only when the webhook has no code yet.
+ # Keep an explicit webhook as the primary source. Email sources and
+ # DB are intentional backstops only when the webhook has no code yet.
if totp_verification_url:
if org_token is None:
- # The org token is only needed for webhook polling. Gmail
+ # The org token is only needed for webhook polling. Email
# and DB-only polling should not fail on missing webhook auth.
org_token = await app.DATABASE.organizations.get_valid_org_auth_token(
organization_id, OrganizationAuthTokenType.api.value
@@ -520,13 +520,13 @@ async def poll_otp_value(
workflow_permanent_id=workflow_permanent_id,
)
if otp_value is None and totp_identifier:
- otp_value = await _get_otp_value_from_gmail(
+ otp_value = await _get_otp_value_from_email(
organization_id=organization_id,
totp_identifier=totp_identifier,
workflow_id=workflow_permanent_id,
workflow_run_id=workflow_run_id,
- created_after=gmail_created_after,
- context=gmail_otp_context,
+ created_after=email_created_after,
+ context=email_otp_context,
)
if otp_value is None and totp_identifier:
# Preserve the historical DB behavior: callers that omit
@@ -678,15 +678,15 @@ async def _get_otp_value_from_url(
return otp_value
-async def _get_otp_value_from_gmail(
+async def _get_otp_value_from_email(
organization_id: str,
totp_identifier: str,
workflow_id: str | None = None,
workflow_run_id: str | None = None,
created_after: datetime | None = None,
- context: GmailOTPVerificationContext | None = None,
+ context: EmailOTPVerificationContext | None = None,
) -> OTPValue | None:
- return await app.AGENT_FUNCTION.get_otp_value_from_gmail(
+ return await app.AGENT_FUNCTION.get_otp_value_from_email(
organization_id=organization_id,
totp_identifier=totp_identifier,
workflow_id=workflow_id,
diff --git a/tests/unit/google/test_otp_service_gmail.py b/tests/unit/google/test_otp_service_gmail.py
index ab56209ed..99c597920 100644
--- a/tests/unit/google/test_otp_service_gmail.py
+++ b/tests/unit/google/test_otp_service_gmail.py
@@ -2,6 +2,7 @@ from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock
+import httpx
import pytest
import structlog.testing
@@ -9,30 +10,65 @@ from skyvern.forge import agent_functions
from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.schemas.totp_codes import OTPType
from skyvern.forge.sdk.services import google_gmail_service, google_oauth_service
-from skyvern.services import otp_service
-from skyvern.services.otp_gmail import MAX_SEEN_GMAIL_MESSAGE_IDS, GmailOTPVerificationContext
+from skyvern.services import otp_email, otp_service
+from skyvern.services.otp_email import MAX_SEEN_EMAIL_MESSAGE_IDS, EmailOTPVerificationContext
-def test_gmail_otp_context_caps_seen_message_ids() -> None:
- context = GmailOTPVerificationContext()
+def test_email_otp_source_context_caps_seen_message_ids() -> None:
+ context = EmailOTPVerificationContext().for_source("gmail")
- for index in range(MAX_SEEN_GMAIL_MESSAGE_IDS + 5):
- context.remember_message_id(f"msg_{index}")
+ for index in range(MAX_SEEN_EMAIL_MESSAGE_IDS + 5):
+ context.remember_message("goac_1", f"msg_{index}")
- assert len(context.seen_message_ids) == MAX_SEEN_GMAIL_MESSAGE_IDS
- assert not context.has_seen_message_id("msg_0")
- assert context.has_seen_message_id(f"msg_{MAX_SEEN_GMAIL_MESSAGE_IDS + 4}")
+ assert len(context.seen_message_keys) == MAX_SEEN_EMAIL_MESSAGE_IDS
+ assert not context.has_seen_message("goac_1", "msg_0")
+ assert context.has_seen_message("goac_1", f"msg_{MAX_SEEN_EMAIL_MESSAGE_IDS + 4}")
@pytest.mark.asyncio
-async def test_get_otp_value_from_gmail_uses_gmail_scoped_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_gmail_source_filters_seen_candidates_for_current_credential(monkeypatch: pytest.MonkeyPatch) -> None:
+ source = otp_email.GmailOTPSource(AsyncMock(return_value=SimpleNamespace(token="AT")))
+ candidates = [
+ google_gmail_service.GmailMessageCandidate(
+ message_id="seen",
+ content="Verification code 111111",
+ internal_date=datetime.now(timezone.utc),
+ ),
+ google_gmail_service.GmailMessageCandidate(
+ message_id="unseen",
+ content="Verification code 222222",
+ internal_date=datetime.now(timezone.utc),
+ ),
+ ]
+ search_messages = AsyncMock(return_value=candidates)
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", search_messages)
+ context = EmailOTPVerificationContext().for_source("gmail")
+ context.remember_message("goac_1", "seen")
+ context.remember_message("different_credential", "unseen")
+
+ async with httpx.AsyncClient() as client:
+ results = await source.search_recent_otp_messages(
+ organization_id="org_1",
+ credential_id="goac_1",
+ totp_identifier="[email protected]",
+ created_after=None,
+ max_results=5,
+ context=context,
+ client=client,
+ )
+
+ assert [candidate.message_id for candidate in results] == ["unseen"]
+
+
+async def test_get_otp_value_from_email_uses_gmail_scoped_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
agent = AgentFunction()
credential = SimpleNamespace(
id="goac_1",
scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
list_credentials = AsyncMock(return_value=[credential])
- monkeypatch.setattr(agent_functions.google_oauth_service, "get_credentials_for_org", list_credentials)
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", list_credentials)
get_credentials = AsyncMock(return_value=SimpleNamespace(token="AT"))
monkeypatch.setattr(agent, "get_google_workspace_credentials", get_credentials)
@@ -47,11 +83,11 @@ async def test_get_otp_value_from_gmail_uses_gmail_scoped_credentials(monkeypatc
internal_date=datetime.now(timezone.utc),
)
search_messages = AsyncMock(return_value=[candidate])
- monkeypatch.setattr(agent_functions.google_gmail_service, "search_recent_otp_messages", search_messages)
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", search_messages)
parse = AsyncMock(return_value=otp_service.OTPValue(value="123456", type=OTPType.TOTP))
monkeypatch.setattr(otp_service, "parse_otp_login", parse)
- result = await agent.get_otp_value_from_gmail(
+ result = await agent.get_otp_value_from_email(
organization_id="org_1",
totp_identifier="[email protected]",
workflow_id="wpid_1",
@@ -65,10 +101,9 @@ async def test_get_otp_value_from_gmail_uses_gmail_scoped_credentials(monkeypatc
credential_id="goac_1",
required_scopes=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
- search_messages.assert_awaited_once()
search_messages_args = search_messages.await_args
assert search_messages_args is not None
- assert search_messages_args.kwargs["max_results"] == agent_functions.GMAIL_OTP_MAX_RESULTS
+ assert search_messages_args.kwargs["max_results"] == agent_functions.EMAIL_OTP_MAX_RESULTS
assert search_messages_args.kwargs["client"] is not None
parse.assert_awaited_once_with("Your verification code is 123456", "org_1")
create_otp_code.assert_awaited_once_with(
@@ -84,14 +119,16 @@ async def test_get_otp_value_from_gmail_uses_gmail_scoped_credentials(monkeypatc
@pytest.mark.asyncio
-async def test_get_otp_value_from_gmail_uses_first_parseable_candidate(monkeypatch: pytest.MonkeyPatch) -> None:
+async def test_get_otp_value_from_email_uses_first_parseable_gmail_candidate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
agent = AgentFunction()
credential = SimpleNamespace(
id="goac_1",
scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
monkeypatch.setattr(
- agent_functions.google_oauth_service,
+ otp_email.google_oauth_service,
"get_credentials_for_org",
AsyncMock(return_value=[credential]),
)
@@ -114,14 +151,14 @@ async def test_get_otp_value_from_gmail_uses_first_parseable_candidate(monkeypat
),
]
monkeypatch.setattr(
- agent_functions.google_gmail_service,
+ otp_email.google_gmail_service,
"search_recent_otp_messages",
AsyncMock(return_value=candidates),
)
parse = AsyncMock(side_effect=[None, otp_service.OTPValue(value="654321", type=OTPType.TOTP)])
monkeypatch.setattr(otp_service, "parse_otp_login", parse)
- result = await agent.get_otp_value_from_gmail(
+ result = await agent.get_otp_value_from_email(
organization_id="org_1",
totp_identifier="[email protected]",
workflow_id="wpid_1",
@@ -129,7 +166,10 @@ async def test_get_otp_value_from_gmail_uses_first_parseable_candidate(monkeypat
)
assert result == otp_service.OTPValue(value="654321", type=OTPType.TOTP)
- assert parse.await_count == 2
+ assert [call.args[0] for call in parse.await_args_list] == [
+ "Security alert with no code",
+ "Your verification code is 654321",
+ ]
create_otp_code.assert_awaited_once_with(
"org_1",
@@ -143,7 +183,7 @@ async def test_get_otp_value_from_gmail_uses_first_parseable_candidate(monkeypat
@pytest.mark.asyncio
-async def test_get_otp_value_from_gmail_retries_candidate_after_parser_error(
+async def test_get_otp_value_from_email_retries_gmail_candidate_after_parser_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = AgentFunction()
@@ -152,7 +192,7 @@ async def test_get_otp_value_from_gmail_retries_candidate_after_parser_error(
scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
monkeypatch.setattr(
- agent_functions.google_oauth_service,
+ otp_email.google_oauth_service,
"get_credentials_for_org",
AsyncMock(return_value=[credential]),
)
@@ -168,37 +208,42 @@ async def test_get_otp_value_from_gmail_retries_candidate_after_parser_error(
internal_date=datetime.now(timezone.utc),
)
search_messages = AsyncMock(return_value=[candidate])
- monkeypatch.setattr(agent_functions.google_gmail_service, "search_recent_otp_messages", search_messages)
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", search_messages)
parse = AsyncMock(
side_effect=[RuntimeError("temporary parser outage"), otp_service.OTPValue(value="112233", type=OTPType.TOTP)]
)
monkeypatch.setattr(otp_service, "parse_otp_login", parse)
- context = GmailOTPVerificationContext()
- first_result = await agent.get_otp_value_from_gmail(
- organization_id="org_1",
- totp_identifier="[email protected]",
- workflow_id="wpid_1",
- workflow_run_id="wr_1",
- context=context,
- )
- context.last_searched_at_by_credential["goac_1"] = datetime(2025, 1, 1, tzinfo=timezone.utc)
- second_result = await agent.get_otp_value_from_gmail(
- organization_id="org_1",
- totp_identifier="[email protected]",
- workflow_id="wpid_1",
- workflow_run_id="wr_1",
- context=context,
- )
+ context = EmailOTPVerificationContext()
+ with structlog.testing.capture_logs() as logs:
+ first_result = await agent.get_otp_value_from_email(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ context=context,
+ )
+ context.for_source("gmail").last_searched_at_by_credential["goac_1"] = datetime(2025, 1, 1, tzinfo=timezone.utc)
+ second_result = await agent.get_otp_value_from_email(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ workflow_id="wpid_1",
+ workflow_run_id="wr_1",
+ context=context,
+ )
assert first_result is None
assert second_result == otp_service.OTPValue(value="112233", type=OTPType.TOTP)
- assert parse.await_count == 2
+ assert [call.args[0] for call in parse.await_args_list] == [candidate.content, candidate.content]
create_otp_code.assert_awaited_once()
+ assert any(
+ record.get("event") == "Failed to parse email OTP candidate" and record.get("source") == "gmail"
+ for record in logs
+ )
@pytest.mark.asyncio
-async def test_get_otp_value_from_gmail_rechecks_unseen_candidate_after_credit_skip(
+async def test_get_otp_value_from_email_rechecks_unseen_gmail_candidate_after_credit_skip(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = AgentFunction()
@@ -207,7 +252,7 @@ async def test_get_otp_value_from_gmail_rechecks_unseen_candidate_after_credit_s
scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
monkeypatch.setattr(
- agent_functions.google_oauth_service,
+ otp_email.google_oauth_service,
"get_credentials_for_org",
AsyncMock(return_value=[credential]),
)
@@ -229,23 +274,23 @@ async def test_get_otp_value_from_gmail_rechecks_unseen_candidate_after_credit_s
for index in range(2)
]
monkeypatch.setattr(
- agent_functions.google_gmail_service,
+ otp_email.google_gmail_service,
"search_recent_otp_messages",
AsyncMock(return_value=candidates),
)
parsed = otp_service.OTPValue(value="placeholder", type=OTPType.TOTP)
parse = AsyncMock(side_effect=[otp_service.InsufficientCreditsForOTPParse, parsed])
monkeypatch.setattr(otp_service, "parse_otp_login", parse)
- context = GmailOTPVerificationContext()
+ context = EmailOTPVerificationContext()
with structlog.testing.capture_logs() as logs:
- first_result = await agent.get_otp_value_from_gmail(
+ first_result = await agent.get_otp_value_from_email(
organization_id="org_1",
totp_identifier="[email protected]",
context=context,
)
- context.last_searched_at_by_credential["goac_1"] = datetime(2025, 1, 1, tzinfo=timezone.utc)
- second_result = await agent.get_otp_value_from_gmail(
+ context.for_source("gmail").last_searched_at_by_credential["goac_1"] = datetime(2025, 1, 1, tzinfo=timezone.utc)
+ second_result = await agent.get_otp_value_from_email(
organization_id="org_1",
totp_identifier="[email protected]",
context=context,
@@ -253,17 +298,20 @@ async def test_get_otp_value_from_gmail_rechecks_unseen_candidate_after_credit_s
assert first_result is None
assert second_result == parsed
- assert parse.await_count == 2
assert parse.await_args_list[0].args[0] == candidates[0].content
assert parse.await_args_list[1].args[0] == candidates[1].content
create_otp_code.assert_awaited_once()
- assert context.has_seen_message_id(candidates[0].message_id)
- assert context.has_seen_message_id(candidates[1].message_id)
- assert all(record.get("event") != "Failed to parse Gmail OTP candidate" for record in logs)
+ gmail_context = context.for_source("gmail")
+ assert gmail_context.has_seen_message("goac_1", candidates[0].message_id)
+ assert gmail_context.has_seen_message("goac_1", candidates[1].message_id)
+ assert all(
+ record.get("event") != "Failed to parse email OTP candidate" or record.get("source") != "gmail"
+ for record in logs
+ )
@pytest.mark.asyncio
-async def test_get_otp_value_from_gmail_skips_credentials_without_gmail_scope(
+async def test_get_otp_value_from_email_skips_credentials_without_gmail_scope(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = AgentFunction()
@@ -272,14 +320,14 @@ async def test_get_otp_value_from_gmail_skips_credentials_without_gmail_scope(
scopes_granted=list(google_oauth_service.GOOGLE_SHEETS_SCOPES),
)
monkeypatch.setattr(
- agent_functions.google_oauth_service,
+ otp_email.google_oauth_service,
"get_credentials_for_org",
AsyncMock(return_value=[credential]),
)
get_credentials = AsyncMock(return_value=SimpleNamespace(token="AT"))
monkeypatch.setattr(agent, "get_google_workspace_credentials", get_credentials)
- result = await agent.get_otp_value_from_gmail(
+ result = await agent.get_otp_value_from_email(
organization_id="org_1",
totp_identifier="[email protected]",
)
@@ -289,7 +337,7 @@ async def test_get_otp_value_from_gmail_skips_credentials_without_gmail_scope(
@pytest.mark.asyncio
-async def test_get_otp_value_from_gmail_throttles_credential_searches_within_polling_context(
+async def test_get_otp_value_from_email_throttles_gmail_searches_within_polling_context(
monkeypatch: pytest.MonkeyPatch,
) -> None:
agent = AgentFunction()
@@ -298,22 +346,29 @@ async def test_get_otp_value_from_gmail_throttles_credential_searches_within_pol
scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),
)
list_credentials = AsyncMock(return_value=[credential])
- monkeypatch.setattr(agent_functions.google_oauth_service, "get_credentials_for_org", list_credentials)
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", list_credentials)
get_credentials = AsyncMock(return_value=SimpleNamespace(token="AT"))
monkeypatch.setattr(agent, "get_google_workspace_credentials", get_credentials)
search_messages = AsyncMock(return_value=[])
- monkeypatch.setattr(agent_functions.google_gmail_service, "search_recent_otp_messages", search_messages)
+ monkeypatch.setattr(otp_email.google_gmail_service, "search_recent_otp_messages", search_messages)
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda current_agent: [otp_email.GmailOTPSource(current_agent.get_google_workspace_credentials)],
+ )
- context = GmailOTPVerificationContext()
+ context = EmailOTPVerificationContext()
- for _ in range(2):
- result = await agent.get_otp_value_from_gmail(
- organization_id="org_1",
- totp_identifier="[email protected]",
- context=context,
- )
- assert result is None
+ with structlog.testing.capture_logs() as logs:
+ for _ in range(2):
+ result = await agent.get_otp_value_from_email(
+ organization_id="org_1",
+ totp_identifier="[email protected]",
+ context=context,
+ )
+ assert result is None
list_credentials.assert_awaited_once_with("org_1")
get_credentials.assert_awaited_once()
search_messages.assert_awaited_once()
+ assert all(log.get("event") != "Unexpected email OTP lookup failure" for log in logs)
diff --git a/tests/unit/microsoft/__init__.py b/tests/unit/microsoft/__init__.py
new file mode 100644
index 000000000..92464842f
--- /dev/null
+++ b/tests/unit/microsoft/__init__.py
@@ -0,0 +1 @@
+"""Microsoft unit tests."""
diff --git a/tests/unit/microsoft/test_otp_service_outlook.py b/tests/unit/microsoft/test_otp_service_outlook.py
new file mode 100644
index 000000000..fa08b30f0
--- /dev/null
+++ b/tests/unit/microsoft/test_otp_service_outlook.py
@@ -0,0 +1,130 @@
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+import structlog.testing
+
+from skyvern.forge import agent_functions
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.schemas.totp_codes import OTPType
+from skyvern.services import otp_email, otp_service
+from skyvern.services.email import outlook
+
+
+def _agent(monkeypatch: pytest.MonkeyPatch, credentials: list[SimpleNamespace]) -> AgentFunction:
+ monkeypatch.setattr(otp_email.google_oauth_service, "get_credentials_for_org", AsyncMock(return_value=[]))
+ monkeypatch.setattr(
+ otp_email.microsoft_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=credentials),
+ )
+ return AgentFunction()
+
+
+async def test_outlook_source_uses_mail_read_credential_and_persists_candidate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = _agent(
+ monkeypatch,
+ [
+ SimpleNamespace(id="without_mail", scopes_granted=["User.Read"]),
+ SimpleNamespace(id="with_mail", scopes_granted=["User.Read", "Mail.Read"]),
+ ],
+ )
+ mint = AsyncMock(return_value="AT")
+ search = AsyncMock(
+ return_value=[
+ outlook.OutlookMessageCandidate(
+ "message",
+ "Your verification code is 123456",
+ datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc),
+ )
+ ]
+ )
+ monkeypatch.setattr(agent, "get_microsoft_credentials", mint)
+ monkeypatch.setattr(otp_email.outlook, "search_recent_otp_messages", search)
+ parsed = otp_service.OTPValue(value="123456", type=OTPType.TOTP)
+ monkeypatch.setattr(otp_service, "parse_otp_login", AsyncMock(return_value=parsed))
+ create = AsyncMock()
+ monkeypatch.setattr(
+ agent_functions.app,
+ "DATABASE",
+ SimpleNamespace(otp=SimpleNamespace(create_otp_code=create)),
+ )
+ context = otp_email.EmailOTPVerificationContext()
+ context.for_source("outlook").remember_message("with_mail", "seen_message")
+
+ result = await agent.get_otp_value_from_email(
+ organization_id="org",
+ totp_identifier="[email protected]",
+ workflow_id="wpid",
+ workflow_run_id="wr",
+ context=context,
+ )
+
+ assert result == parsed
+ mint.assert_awaited_once_with(
+ organization_id="org",
+ credential_id="with_mail",
+ required_scopes=["Mail.Read"],
+ )
+ search_args = search.await_args
+ assert search_args is not None
+ assert search_args.kwargs["access_token"] == "AT"
+ assert search_args.kwargs["max_results"] == agent_functions.EMAIL_OTP_MAX_RESULTS
+ assert search_args.kwargs["state"] == {}
+ assert search_args.kwargs["excluded_message_ids"] == {"seen_message"}
+ create.assert_awaited_once()
+ create_args = create.await_args
+ assert create_args is not None
+ assert create_args.kwargs == {"workflow_id": "wpid", "workflow_run_id": "wr", "source": "outlook"}
+ tokenless = _agent(monkeypatch, [SimpleNamespace(id="without_token", scopes_granted=["Mail.Read"])])
+ monkeypatch.setattr(tokenless, "get_microsoft_credentials", AsyncMock(return_value=None))
+ search.reset_mock()
+ assert await tokenless.get_otp_value_from_email(organization_id="org", totp_identifier="[email protected]") is None
+ search.assert_not_awaited()
+
+
+async def test_outlook_source_logs_api_error_and_scans_other_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ agent = _agent(
+ monkeypatch,
+ [
+ SimpleNamespace(id="failing", scopes_granted=["Mail.Read"]),
+ SimpleNamespace(id="healthy", scopes_granted=["Mail.Read"]),
+ ],
+ )
+
+ async def mint(organization_id: str, credential_id: str, required_scopes: list[str] | None = None) -> str:
+ del organization_id, required_scopes
+ return credential_id
+
+ searched: list[str] = []
+
+ async def search(**kwargs: object) -> list[outlook.OutlookMessageCandidate]:
+ token = str(kwargs["access_token"])
+ searched.append(token)
+ if token == "failing":
+ raise outlook.OutlookAPIError(status=503, code="ServiceUnavailable", message="unavailable")
+ return []
+
+ monkeypatch.setattr(agent, "get_microsoft_credentials", mint)
+ monkeypatch.setattr(otp_email.outlook, "search_recent_otp_messages", search)
+
+ with structlog.testing.capture_logs() as logs:
+ result = await agent.get_otp_value_from_email(organization_id="org", totp_identifier="[email protected]")
+
+ assert result is None
+ assert searched == ["failing", "healthy"]
+ assert any(
+ log.get("event") == "Email OTP lookup failed"
+ and log.get("source") == "outlook"
+ and log.get("credential_id") == "failing"
+ and log.get("status") == 503
+ and log.get("code") == "ServiceUnavailable"
+ for log in logs
+ )
diff --git a/tests/unit/test_email_service.py b/tests/unit/test_email_service.py
index a44d3f33e..8e0cb6907 100644
--- a/tests/unit/test_email_service.py
+++ b/tests/unit/test_email_service.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from datetime import datetime, timedelta, timezone
from typing import Any
import httpx
@@ -44,6 +45,82 @@ def _mock_response(status_code: int, *, json: dict[str, Any] | None = None) -> h
return httpx.Response(status_code, json=json or {})
+def _outlook_recipient(address: str) -> dict[str, dict[str, str]]:
+ return {"emailAddress": {"address": address}}
+
+
+def _outlook_otp_message(
+ message_id: str,
+ *,
+ received_datetime: str = "2026-07-30T12:00:00Z",
+ recipient: str | None = "[email protected]",
+ subject: str = "Verification code",
+ preview: str = "",
+ body: str = "Your code is 123456",
+ **overrides: Any,
+) -> dict[str, Any]:
+ message: dict[str, Any] = {
+ "id": message_id,
+ "parentFolderId": "inbox_id",
+ "isDraft": False,
+ "subject": subject,
+ "bodyPreview": preview,
+ "body": {"contentType": "html", "content": body},
+ "receivedDateTime": received_datetime,
+ "toRecipients": [_outlook_recipient(recipient)] if recipient else [],
+ "ccRecipients": [],
+ "bccRecipients": [],
+ "internetMessageHeaders": [],
+ }
+ message.update(overrides)
+ return message
+
+
+def _outlook_otp_list_rows(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [{key: value for key, value in message.items() if key != "body"} for message in messages]
+
+
+def _outlook_otp_hydration(messages: list[dict[str, Any]], message_id: str) -> dict[str, Any]:
+ return next(message for message in messages if message.get("id") == message_id)
+
+
+def _patch_outlook_otp_graph(
+ monkeypatch: pytest.MonkeyPatch,
+ messages: list[dict[str, Any]],
+ *,
+ mailbox_payload: dict[str, Any] | None = None,
+) -> list[tuple[str, dict[str, Any] | None, tuple[str, ...] | None]]:
+ calls: list[tuple[str, dict[str, Any] | None, tuple[str, ...] | None]] = []
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token
+ calls.append((url, params, prefer))
+ if url.endswith("/me"):
+ return mailbox_payload or {"mail": "[email protected]"}
+ if url.endswith("/mailFolders/junkemail"):
+ return {"id": "junk_id"}
+ if url.endswith("/mailFolders/deleteditems"):
+ return {"id": "deleted_id"}
+ if url.endswith("/mailFolders/sentitems"):
+ return {"id": "sent_id"}
+ if url.endswith("/me/messages"):
+ return {"value": _outlook_otp_list_rows(messages)}
+ if "/me/messages/" in url:
+ message_id = url.rsplit("/", 1)[-1]
+ return _outlook_otp_hydration(messages, message_id)
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+ return calls
+
+
def test_gmail_build_folder_query_quotes_untrusted_values() -> None:
query = email.gmail._build_folder_query("x OR label:SENT newer_than:10y", 'a" OR b', 3)
@@ -250,6 +327,731 @@ async def test_outlook_get_json_reconnect_required_mapping(
assert exc_info.value.code == expected_code
+async def test_outlook_otp_search_request_and_identifier_security(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = _patch_outlook_otp_graph(monkeypatch, [])
+ cutoff = datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc)
+ state: dict = {}
+
+ assert (
+ await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ state=state,
+ )
+ == []
+ )
+ _, params, prefer = next(call for call in calls if call[0].endswith("/me/messages"))
+ assert params is not None
+ assert params["$filter"] == "receivedDateTime ge 2026-07-30T11:59:59Z"
+ assert params["$orderby"] == "receivedDateTime desc"
+ assert {"bodyPreview", "toRecipients", "ccRecipients", "bccRecipients", "internetMessageHeaders"} <= set(
+ params["$select"].split(",")
+ )
+ assert "body" not in params["$select"].split(",")
+ assert prefer == ('IdType="ImmutableId"', 'outlook.body-content-type="html"')
+ _, mailbox_params, _ = next(call for call in calls if call[0].endswith("/me"))
+ assert mailbox_params == {"$select": "mail,userPrincipalName,proxyAddresses"}
+ assert (
+ await email.outlook.search_recent_otp_messages(
+ access_token="AT", totp_identifier="[email protected]", state=state
+ )
+ == []
+ )
+ assert len([call for call in calls if call[0].endswith("/me")]) == 1
+ assert len([call for call in calls if "/mailFolders/" in call[0]]) == 3
+ calls.clear()
+ assert await email.outlook.search_recent_otp_messages(access_token="AT", totp_identifier="a@b) OR (x") == []
+ assert calls == []
+
+
+def test_outlook_otp_recipient_security_uses_only_trusted_delivery_headers() -> None:
+ assert email.outlook._DELIVERY_HEADER_NAMES == {
+ "x-ms-exchange-organization-originalenveloperecipient",
+ "x-ms-exchange-organization-originalenveloperecipients",
+ "x-ms-exchange-organization-originalto",
+ }
+ message = _outlook_otp_message(
+ "forged",
+ recipient=None,
+ internetMessageHeaders=[{"name": "Delivered-To", "value": "[email protected]"}],
+ )
+
+ assert email.outlook._message_recipient_addresses(message) == set()
+
+
+def test_outlook_mailbox_identity_set_excludes_external_contact_addresses() -> None:
+ assert email.outlook._mailbox_identity_set(
+ {
+ "mail": "[email protected]",
+ "userPrincipalName": "[email protected]",
+ "otherMails": ["[email protected]"],
+ "proxyAddresses": ["SMTP:[email protected]"],
+ }
+
+
+async def test_outlook_otp_search_default_cutoff_accepts_recent_message(monkeypatch: pytest.MonkeyPatch) -> None:
+ received_datetime = datetime.now(timezone.utc) - timedelta(minutes=5)
+ _patch_outlook_otp_graph(
+ monkeypatch,
+ [_outlook_otp_message("recent", received_datetime=received_datetime.isoformat().replace("+00:00", "Z"))],
+ )
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["recent"]
+
+
+async def test_outlook_otp_search_retries_excluded_folder_lookup_without_id(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ folder_calls: list[str] = []
+ message_calls = 0
+ state: dict = {}
+ messages = [
+ _outlook_otp_message("valid"),
+ _outlook_otp_message("deleted", parentFolderId="deleted_id"),
+ ]
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ nonlocal message_calls
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if url.endswith("/mailFolders/junkemail"):
+ folder_calls.append("junkemail")
+ if folder_calls.count("junkemail") == 1:
+ raise ValueError("malformed JSON")
+ return {"id": "junk_id"}
+ if url.endswith("/mailFolders/deleteditems"):
+ folder_calls.append("deleteditems")
+ return {"id": "deleted_id"}
+ if url.endswith("/mailFolders/sentitems"):
+ folder_calls.append("sentitems")
+ return {"id": "sent_id"}
+ if url.endswith("/me/messages"):
+ message_calls += 1
+ return {"value": _outlook_otp_list_rows(messages)}
+ if "/me/messages/" in url:
+ return _outlook_otp_hydration(messages, url.rsplit("/", 1)[-1])
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+ cutoff = datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc)
+
+ first = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ state=state,
+ )
+
+ assert first == []
+ assert message_calls == 0
+ assert email.outlook._OTP_EXCLUDED_FOLDER_IDS_STATE_KEY not in state
+
+ second = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ state=state,
+ )
+
+ assert [candidate.message_id for candidate in second] == ["valid"]
+ assert message_calls == 1
+ assert folder_calls == [
+ "junkemail",
+ "deleteditems",
+ "sentitems",
+ "junkemail",
+ "deleteditems",
+ "sentitems",
+ ]
+ assert state[email.outlook._OTP_EXCLUDED_FOLDER_IDS_STATE_KEY] == {"junk_id", "deleted_id", "sent_id"}
+
+
+async def test_outlook_otp_search_retries_mailbox_identity_lookup_after_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ me_calls = 0
+ message_calls = 0
+ state: dict = {}
+ strong = _outlook_otp_message("strong")
+ fallback = _outlook_otp_message("fallback", recipient=None)
+ messages = [strong, fallback]
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ nonlocal me_calls, message_calls
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ me_calls += 1
+ if me_calls == 1:
+ raise email.OutlookAPIError(status=503, code="ServiceUnavailable", message="temporarily unavailable")
+ return {"mail": "[email protected]"}
+ if url.endswith("/mailFolders/junkemail"):
+ return {"id": "junk_id"}
+ if url.endswith("/mailFolders/deleteditems"):
+ return {"id": "deleted_id"}
+ if url.endswith("/mailFolders/sentitems"):
+ return {"id": "sent_id"}
+ if url.endswith("/me/messages"):
+ message_calls += 1
+ if message_calls == 1:
+ return {"value": _outlook_otp_list_rows(messages)}
+ return {"value": _outlook_otp_list_rows([fallback])}
+ if "/me/messages/" in url:
+ return _outlook_otp_hydration(messages, url.rsplit("/", 1)[-1])
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+ cutoff = datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc)
+
+ first = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ state=state,
+ )
+
+ assert [candidate.message_id for candidate in first] == ["strong"]
+ assert email.outlook._OTP_MAILBOX_IDENTITIES_STATE_KEY not in state
+
+ second = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ state=state,
+ )
+
+ assert [candidate.message_id for candidate in second] == ["fallback"]
+ assert me_calls == 2
+ assert state[email.outlook._OTP_MAILBOX_IDENTITIES_STATE_KEY] == {"[email protected]"}
+
+
+async def test_outlook_otp_search_malformed_mailbox_metadata_uses_strict_matching(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ messages = [
+ _outlook_otp_message("strong"),
+ _outlook_otp_message("hidden", recipient=None),
+ ]
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ raise ValueError("malformed JSON")
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages"):
+ return {"value": _outlook_otp_list_rows(messages)}
+ if "/me/messages/" in url:
+ return _outlook_otp_hydration(messages, url.rsplit("/", 1)[-1])
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["strong"]
+
+
+async def test_outlook_otp_search_alias_fallback_requires_no_observable_recipients(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ different_alias = _outlook_otp_message(
+ "different_alias",
+ recipient="[email protected]",
+ body="",
+ )
+ different_alias.pop("body")
+ hidden_recipient = _outlook_otp_message("hidden_recipient", recipient=None)
+ hydration_calls: list[str] = []
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {
+ "mail": "[email protected]",
+ "proxyAddresses": ["smtp:[email protected]"],
+ }
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages"):
+ return {"value": _outlook_otp_list_rows([different_alias, hidden_recipient])}
+ if "/me/messages/" in url:
+ hydration_calls.append(url.rsplit("/", 1)[-1])
+ return {"body": {"contentType": "html", "content": "Verification code 123456"}}
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["hidden_recipient"]
+ assert hydration_calls == ["hidden_recipient"]
+
+
+async def test_outlook_otp_search_excludes_seen_messages_before_candidate_budget_and_hydration(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls = _patch_outlook_otp_graph(
+ monkeypatch,
+ [
+ _outlook_otp_message("seen", received_datetime="2026-07-30T12:02:00Z"),
+ _outlook_otp_message("unseen", received_datetime="2026-07-30T12:01:00Z"),
+ ],
+ )
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc),
+ max_results=1,
+ excluded_message_ids={"seen"},
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["unseen"]
+ assert [call[0].rsplit("/", 1)[-1] for call in calls if "/me/messages/" in call[0]] == ["unseen"]
+
+
+async def test_outlook_otp_search_returns_strong_then_hidden_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ messages = [
+ _outlook_otp_message(
+ "fallback",
+ received_datetime="2026-07-30T12:02:00Z",
+ recipient=None,
+ ),
+ _outlook_otp_message(
+ "strong",
+ received_datetime="2026-07-30T12:01:00Z",
+ ),
+ ]
+ _patch_outlook_otp_graph(
+ monkeypatch,
+ messages,
+ mailbox_payload={"mail": "[email protected]"},
+ )
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc),
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["strong", "fallback"]
+
+
+async def test_outlook_otp_search_distinguishes_empty_body_from_missing_hydration_body(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ subject_only = _outlook_otp_message("subject_only", subject="Verification code 654321", body="")
+ subject_only.pop("body")
+ incomplete = _outlook_otp_message("incomplete", subject="Verification code", body="")
+ incomplete.pop("body")
+ hydration_calls: list[str] = []
+ incomplete_hydrations = 0
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages"):
+ return {"value": [subject_only, incomplete]}
+ if "/me/messages/" in url:
+ nonlocal incomplete_hydrations
+ message_id = url.rsplit("/", 1)[-1]
+ hydration_calls.append(message_id)
+ if message_id == "subject_only":
+ return {"body": {"contentType": "html", "content": ""}}
+ incomplete_hydrations += 1
+ if incomplete_hydrations == 1:
+ return {}
+ return {"body": {"contentType": "html", "content": "Your verification code is 123456"}}
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ first = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ second = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert [candidate.message_id for candidate in first] == ["subject_only"]
+ assert "Verification code 654321" in first[0].content
+ assert [candidate.message_id for candidate in second] == ["subject_only", "incomplete"]
+ assert hydration_calls == ["subject_only", "incomplete", "subject_only", "incomplete"]
+
+
+async def test_outlook_otp_search_continues_after_non_auth_hydration_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ bodyless = _outlook_otp_message("bodyless", subject="Verification code", preview="", body="")
+ bodyless.pop("body")
+ hydration_calls = 0
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ nonlocal hydration_calls
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages"):
+ return {"value": [bodyless]}
+ if url.endswith("/me/messages/bodyless"):
+ hydration_calls += 1
+ if hydration_calls == 1:
+ raise email.OutlookAPIError(status=404, code="ErrorItemNotFound", message="message not found")
+ return {"body": {"contentType": "html", "content": "Your verification code is 123456"}}
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ first = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert first == []
+
+ second = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert [candidate.message_id for candidate in second] == ["bodyless"]
+ assert hydration_calls == 2
+
+
+async def test_outlook_otp_search_continues_after_malformed_hydration_response(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ bodyless = _outlook_otp_message("bodyless", subject="Verification code", preview="", body="")
+ bodyless.pop("body")
+ valid = _outlook_otp_message("valid")
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages"):
+ return {"value": _outlook_otp_list_rows([bodyless, valid])}
+ if url.endswith("/me/messages/bodyless"):
+ raise ValueError("malformed JSON")
+ if url.endswith("/me/messages/valid"):
+ return valid
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["valid"]
+
+
+async def test_outlook_otp_search_propagates_reconnect_required_hydration_failure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ bodyless = _outlook_otp_message("bodyless", subject="Sign in", preview="", body="")
+ bodyless.pop("body")
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages"):
+ return {"value": [bodyless]}
+ if url.endswith("/me/messages/bodyless"):
+ raise email.OutlookAPIError(status=401, code="reconnect_required", message="token expired")
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ with pytest.raises(email.OutlookAPIError) as exc_info:
+ await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 11, 59, tzinfo=timezone.utc),
+ )
+
+ assert exc_info.value.code == "reconnect_required"
+
+
+async def test_outlook_otp_search_rejects_old_draft_and_junk_before_hydration(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ messages = [
+ _outlook_otp_message("old", received_datetime="2026-07-30T11:59:59Z", body=""),
+ _outlook_otp_message("draft", isDraft=True, body=""),
+ _outlook_otp_message("junk", parentFolderId="junk_id", body=""),
+ ]
+ for message in messages:
+ message.pop("body")
+ hydration_calls = 0
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ nonlocal hydration_calls
+ del client, access_token, params, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if url.endswith("/mailFolders/junkemail"):
+ return {"id": "junk_id"}
+ if url.endswith("/mailFolders/deleteditems"):
+ return {"id": "deleted_id"}
+ if url.endswith("/mailFolders/sentitems"):
+ return {"id": "sent_id"}
+ if url.endswith("/me/messages"):
+ return {"value": messages}
+ if "/me/messages/" in url:
+ hydration_calls += 1
+ return {"body": {"contentType": "html", "content": "Verification code 123456"}}
+ raise AssertionError(f"Unexpected Graph request: {url}")
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc),
+ )
+
+ assert candidates == []
+ assert hydration_calls == 0
+
+
+async def test_outlook_otp_search_filters_and_orders_candidates(monkeypatch: pytest.MonkeyPatch) -> None:
+ href = "https://login.example/verify?token=a%2Bb&next=%2Fhome"
+ messages = [
+ _outlook_otp_message(
+ "to",
+ received_datetime="2026-07-30T12:04:00Z",
+ recipient=" [email protected] ",
+ preview="Use code 123456",
+ body=f'<a href="{href}">verify</a>',
+ ),
+ _outlook_otp_message(
+ "cc",
+ received_datetime="2026-07-30T12:03:00Z",
+ recipient=None,
+ subject="Sign in",
+ body="one time credential",
+ ccRecipients=[_outlook_recipient("[email protected]")],
+ ),
+ _outlook_otp_message(
+ "bcc",
+ received_datetime="2026-07-30T12:02:00Z",
+ recipient=None,
+ subject="Sign in",
+ body="one-time credential",
+ bccRecipients=[_outlook_recipient("[email protected]")],
+ ),
+ _outlook_otp_message(
+ "header",
+ received_datetime="2026-07-30T12:01:00Z",
+ recipient=None,
+ internetMessageHeaders=[{"name": "Delivered-To", "value": "[email protected]"}],
+ ),
+ _outlook_otp_message("old", received_datetime="2026-07-30T11:59:59Z"),
+ _outlook_otp_message("mismatch", recipient="[email protected]"),
+ _outlook_otp_message("no_keyword", subject="Sign-in alert", body="A new sign-in was detected."),
+ _outlook_otp_message("junk", parentFolderId="junk_id"),
+ _outlook_otp_message("deleted", parentFolderId="deleted_id"),
+ _outlook_otp_message("sent", parentFolderId="sent_id"),
+ _outlook_otp_message("draft", isDraft=True),
+ _outlook_otp_message("missing_date", receivedDateTime=None),
+ _outlook_otp_message("invalid_date", received_datetime="invalid"),
+ _outlook_otp_message("empty", subject="", preview="", body=""),
+ ]
+ _patch_outlook_otp_graph(monkeypatch, messages)
+
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc),
+ max_results=20,
+ )
+
+ assert [candidate.message_id for candidate in candidates] == ["to", "cc", "bcc"]
+ assert "Subject: Verification code" in candidates[0].content
+ assert "Snippet: Use code 123456" in candidates[0].content
+ assert f'<a href="{href}">verify</a>' in candidates[0].content
+ _patch_outlook_otp_graph(
+ monkeypatch,
+ [_outlook_otp_message("fallback", recipient=None)],
+ mailbox_payload={"mail": "[email protected]"},
+ )
+ cutoff = datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc)
+ fallback = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ )
+ rejected = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=cutoff,
+ )
+ assert [candidate.message_id for candidate in fallback] == ["fallback"]
+ assert rejected == []
+
+
[email protected](("case", "expected", "requests"), [("valid", ["page_2"], 2), ("evil", [], 1), ("cap", [], 1)])
+async def test_outlook_otp_search_pagination_guards(
+ monkeypatch: pytest.MonkeyPatch,
+ case: str,
+ expected: list[str],
+ requests: int,
+) -> None:
+ next_link = f"{email.outlook.GRAPH_API_BASE}/me/messages?$skip=1"
+ message_calls: list[tuple[str, dict[str, Any] | None]] = []
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ prefer: tuple[str, ...] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token, prefer
+ if url.endswith("/me"):
+ return {"mail": "[email protected]"}
+ if "/mailFolders/" in url:
+ return {"id": url.rsplit("/", 1)[-1]}
+ if url.endswith("/me/messages/page_2"):
+ return _outlook_otp_message("page_2")
+ message_calls.append((url, params))
+ if len(message_calls) == 2:
+ return {"value": _outlook_otp_list_rows([_outlook_otp_message("page_2")])}
+ items = [_outlook_otp_message(f"raw_{i}", recipient="[email protected]") for i in range(101)]
+ return {
+ "value": _outlook_otp_list_rows(items) if case == "cap" else [],
+ "@odata.nextLink": "https://evil.example/messages" if case == "evil" else next_link,
+ }
+
+ monkeypatch.setattr(email.outlook, "_get_json", fake_get_json)
+ candidates = await email.outlook.search_recent_otp_messages(
+ access_token="AT",
+ totp_identifier="[email protected]",
+ created_after=datetime(2026, 7, 30, 12, 0, tzinfo=timezone.utc),
+ )
+ assert [candidate.message_id for candidate in candidates] == expected
+ assert len(message_calls) == requests
+ if case == "valid":
+ assert message_calls[1] == (next_link, None)
+
+
@pytest.mark.asyncio
async def test_outlook_list_folder_messages_omits_body_when_include_body_false(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_otp_email_registry.py b/tests/unit/test_otp_email_registry.py
new file mode 100644
index 000000000..a0b5eb7fa
--- /dev/null
+++ b/tests/unit/test_otp_email_registry.py
@@ -0,0 +1,146 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+import structlog.testing
+
+from skyvern.forge import agent_functions
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.schemas.totp_codes import OTPType
+from skyvern.services import otp_service
+from skyvern.services.otp_email import EmailOTPCandidate, EmailOTPVerificationContext
+
+
+class StubSource:
+ def __init__(
+ self,
+ name: str,
+ credentials: list[str] | None = None,
+ candidates: list[EmailOTPCandidate] | None = None,
+ events: list[str] | None = None,
+ list_error: Exception | None = None,
+ ) -> None:
+ self.name, self.credentials, self.candidates = name, credentials or [], candidates or []
+ self.events, self.list_error = events if events is not None else [], list_error
+
+ async def list_credential_ids(self, organization_id: str) -> list[str]:
+ self.events.append(f"list:{self.name}")
+ if self.list_error:
+ raise self.list_error
+ return self.credentials
+
+ async def search_recent_otp_messages(
+ self,
+ *,
+ credential_id: str,
+ **_kwargs: object,
+ ) -> list[EmailOTPCandidate]:
+ self.events.append(f"search:{self.name}:{credential_id}")
+ return self.candidates
+
+
+def _agent(monkeypatch: pytest.MonkeyPatch, sources: list[StubSource]) -> tuple[AgentFunction, AsyncMock]:
+ monkeypatch.setattr(agent_functions, "build_email_otp_sources", lambda _agent: sources)
+ create = AsyncMock()
+ monkeypatch.setattr(
+ agent_functions.app,
+ "DATABASE",
+ SimpleNamespace(otp=SimpleNamespace(create_otp_code=create)),
+ )
+ return AgentFunction(), create
+
+
+async def test_registry_scans_gmail_first_short_circuits_and_persists_source(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ agent_functions,
+ "build_email_otp_sources",
+ lambda _agent: (_ for _ in ()).throw(AssertionError("sources must not be built")),
+ )
+ assert await AgentFunction().get_otp_value_from_email(organization_id="org", totp_identifier="+15555550123") is None
+ events: list[str] = []
+ gmail = StubSource("gmail", ["g1"], [EmailOTPCandidate("gm", "gmail code")], events)
+ outlook = StubSource("outlook", ["o1"], [EmailOTPCandidate("om", "outlook code")], events)
+ agent, create = _agent(monkeypatch, [gmail, outlook])
+ expected = otp_service.OTPValue(value="123456", type=OTPType.TOTP)
+ monkeypatch.setattr(otp_service, "parse_otp_login", AsyncMock(return_value=expected))
+
+ result = await agent.get_otp_value_from_email(
+ organization_id="org",
+ totp_identifier="[email protected]",
+ workflow_id="wpid",
+ workflow_run_id="wr",
+ )
+
+ assert result == expected
+ assert events == ["list:gmail", "search:gmail:g1"]
+ assert create.await_args.kwargs == {"workflow_id": "wpid", "workflow_run_id": "wr", "source": "gmail"}
+
+
+async def test_registry_isolates_empty_and_failing_sources(monkeypatch: pytest.MonkeyPatch) -> None:
+ events: list[str] = []
+ sources = [
+ StubSource("gmail", events=events, list_error=RuntimeError("down")),
+ StubSource("outlook", events=events),
+ StubSource("backup", ["b1"], [EmailOTPCandidate("bm", "backup code")], events),
+ ]
+ agent, _ = _agent(monkeypatch, sources)
+ monkeypatch.setattr(
+ otp_service,
+ "parse_otp_login",
+ AsyncMock(return_value=otp_service.OTPValue(value="654321", type=OTPType.TOTP)),
+ )
+
+ with structlog.testing.capture_logs() as logs:
+ result = await agent.get_otp_value_from_email(organization_id="org", totp_identifier="[email protected]")
+
+ assert result is not None
+ assert events == ["list:gmail", "list:outlook", "list:backup", "search:backup:b1"]
+ assert any(
+ log.get("event") == "Failed to list email OTP credentials" and log.get("source") == "gmail" for log in logs
+ )
+
+
+async def test_registry_credit_skip_remembers_candidate_and_stops(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ events: list[str] = []
+ candidate = EmailOTPCandidate("gm", "gmail code")
+ agent, create = _agent(
+ monkeypatch,
+ [
+ StubSource("gmail", ["g1"], [candidate], events),
+ StubSource("outlook", ["o1"], [EmailOTPCandidate("om", "outlook code")], events),
+ ],
+ )
+ monkeypatch.setattr(
+ otp_service,
+ "parse_otp_login",
+ AsyncMock(side_effect=otp_service.InsufficientCreditsForOTPParse),
+ )
+ context = EmailOTPVerificationContext()
+
+ result = await agent.get_otp_value_from_email(
+ organization_id="org", totp_identifier="[email protected]", context=context
+ )
+
+ assert result is None
+ assert events == ["list:gmail", "search:gmail:g1"]
+ assert context.for_source("gmail").has_seen_message("g1", "gm")
+ create.assert_not_awaited()
+
+
+def test_registry_seen_keys_do_not_collide_across_sources_or_credentials() -> None:
+ shared_id = "shared"
+ context = EmailOTPVerificationContext()
+
+ context.for_source("gmail").remember_message("g1", shared_id)
+ assert context.for_source("gmail").has_seen_message("g1", shared_id)
+ assert not context.for_source("gmail").has_seen_message("o1", shared_id)
+ assert not context.for_source("outlook").has_seen_message("g1", shared_id)
+ assert context.for_source("gmail").seen_message_ids_for_credential("g1") == {shared_id}
+ assert context.for_source("gmail").seen_message_ids_for_credential("o1") == set()
diff --git a/tests/unit/test_otp_service.py b/tests/unit/test_otp_service.py
index 46cab4993..acdbf4e17 100644
--- a/tests/unit/test_otp_service.py
+++ b/tests/unit/test_otp_service.py
@@ -745,17 +745,17 @@ class TestPollOtpValueRetry:
@pytest.mark.asyncio
@patch("skyvern.services.otp_service.asyncio.sleep", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_db", new_callable=AsyncMock)
- @patch("skyvern.services.otp_service._get_otp_value_from_gmail", new_callable=AsyncMock)
+ @patch("skyvern.services.otp_service._get_otp_value_from_email", new_callable=AsyncMock)
@patch("skyvern.services.otp_service.settings")
- async def test_falls_back_to_db_when_gmail_has_no_code(
+ async def test_falls_back_to_db_when_email_has_no_code(
self,
mock_settings: MagicMock,
- mock_gmail: AsyncMock,
+ mock_email: AsyncMock,
mock_db: AsyncMock,
mock_sleep: AsyncMock,
) -> None:
mock_settings.VERIFICATION_CODE_POLLING_TIMEOUT_MINS = 15
- mock_gmail.return_value = None
+ mock_email.return_value = None
otp = OTPValue(value="123456", type=OTPType.TOTP)
mock_db.return_value = otp
@@ -768,21 +768,21 @@ class TestPollOtpValueRetry:
)
assert result == otp
- mock_gmail.assert_awaited_once()
+ mock_email.assert_awaited_once()
mock_db.assert_awaited_once()
@pytest.mark.asyncio
@patch("skyvern.services.otp_service.asyncio.sleep", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_db", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_url", new_callable=AsyncMock)
- @patch("skyvern.services.otp_service._get_otp_value_from_gmail", new_callable=AsyncMock)
+ @patch("skyvern.services.otp_service._get_otp_value_from_email", new_callable=AsyncMock)
@patch("skyvern.services.otp_service.app")
@patch("skyvern.services.otp_service.settings")
- async def test_prefers_url_before_gmail_and_db_when_url_has_code(
+ async def test_prefers_url_before_email_and_db_when_url_has_code(
self,
mock_settings: MagicMock,
mock_app: MagicMock,
- mock_gmail: AsyncMock,
+ mock_email: AsyncMock,
mock_url: AsyncMock,
mock_db: AsyncMock,
mock_sleep: AsyncMock,
@@ -791,7 +791,7 @@ class TestPollOtpValueRetry:
mock_app.DATABASE.organizations.get_valid_org_auth_token = AsyncMock(return_value=_mock_org_token())
otp = OTPValue(value="123456", type=OTPType.TOTP)
mock_url.return_value = otp
- mock_gmail.return_value = OTPValue(value="654321", type=OTPType.TOTP)
+ mock_email.return_value = OTPValue(value="654321", type=OTPType.TOTP)
result = await poll_otp_value(
organization_id="o_test",
@@ -804,21 +804,21 @@ class TestPollOtpValueRetry:
assert result == otp
mock_url.assert_awaited_once()
- mock_gmail.assert_not_awaited()
+ mock_email.assert_not_awaited()
mock_db.assert_not_awaited()
@pytest.mark.asyncio
@patch("skyvern.services.otp_service.asyncio.sleep", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_db", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_url", new_callable=AsyncMock)
- @patch("skyvern.services.otp_service._get_otp_value_from_gmail", new_callable=AsyncMock)
+ @patch("skyvern.services.otp_service._get_otp_value_from_email", new_callable=AsyncMock)
@patch("skyvern.services.otp_service.app")
@patch("skyvern.services.otp_service.settings")
- async def test_falls_back_to_gmail_before_db_when_url_has_no_code(
+ async def test_falls_back_to_email_before_db_when_url_has_no_code(
self,
mock_settings: MagicMock,
mock_app: MagicMock,
- mock_gmail: AsyncMock,
+ mock_email: AsyncMock,
mock_url: AsyncMock,
mock_db: AsyncMock,
mock_sleep: AsyncMock,
@@ -827,7 +827,7 @@ class TestPollOtpValueRetry:
mock_app.DATABASE.organizations.get_valid_org_auth_token = AsyncMock(return_value=_mock_org_token())
mock_url.return_value = None
otp = OTPValue(value="123456", type=OTPType.TOTP)
- mock_gmail.return_value = otp
+ mock_email.return_value = otp
result = await poll_otp_value(
organization_id="o_test",
@@ -840,23 +840,23 @@ class TestPollOtpValueRetry:
assert result == otp
mock_url.assert_awaited_once()
- mock_gmail.assert_awaited_once()
+ mock_email.assert_awaited_once()
mock_db.assert_not_awaited()
@pytest.mark.asyncio
@patch("skyvern.services.otp_service.asyncio.sleep", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_db", new_callable=AsyncMock)
@patch("skyvern.services.otp_service._get_otp_value_from_url", new_callable=AsyncMock)
- @patch("skyvern.services.otp_service._get_otp_value_from_gmail", new_callable=AsyncMock)
+ @patch("skyvern.services.otp_service._get_otp_value_from_email", new_callable=AsyncMock)
@patch("skyvern.services.otp_service.app")
@patch("skyvern.services.otp_service.settings")
@patch("skyvern.services.otp_service.datetime")
- async def test_falls_back_to_db_after_url_and_gmail_preserves_db_cutoff_default(
+ async def test_falls_back_to_db_after_url_and_email_preserves_db_cutoff_default(
self,
mock_datetime: MagicMock,
mock_settings: MagicMock,
mock_app: MagicMock,
- mock_gmail: AsyncMock,
+ mock_email: AsyncMock,
mock_url: AsyncMock,
mock_db: AsyncMock,
mock_sleep: AsyncMock,
@@ -866,7 +866,7 @@ class TestPollOtpValueRetry:
mock_settings.VERIFICATION_CODE_POLLING_TIMEOUT_MINS = 15
mock_app.DATABASE.organizations.get_valid_org_auth_token = AsyncMock(return_value=_mock_org_token())
mock_url.return_value = None
- mock_gmail.return_value = None
+ mock_email.return_value = None
otp = OTPValue(value="123456", type=OTPType.TOTP)
mock_db.return_value = otp
@@ -881,9 +881,9 @@ class TestPollOtpValueRetry:
assert result == otp
mock_url.assert_awaited_once()
- mock_gmail.assert_awaited_once()
+ mock_email.assert_awaited_once()
mock_db.assert_awaited_once()
- assert mock_gmail.await_args.kwargs["created_after"] == start
+ assert mock_email.await_args.kwargs["created_after"] == start
assert mock_db.await_args.kwargs["created_after"] is None
@pytest.mark.asyncio