Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Fix email OTP code persistence, expected-type enforcement, and sign-in link recall (#8028)
Celal Zamanoğluec51e280498c
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 519e9d226..78c928cb8 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -79,6 +79,7 @@ if TYPE_CHECKING:from playwright.async_api import BrowserContextfrom skyvern.forge.sdk.db.enums import WorkflowRunTriggerType+ from skyvern.forge.sdk.schemas.totp_codes import OTPTypefrom skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultServicefrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContextfrom skyvern.forge.sdk.workflow.models.code_block_recorder import RecordingPage@@ -1719,6 +1720,7 @@ class AgentFunction:workflow_id: str | None = None,workflow_run_id: str | None = None,created_after: datetime | None = None,+ expected_otp_type: OTPType | None = None,context: EmailOTPVerificationContext | None = None,) -> OTPValue | None:"""Find an OTP in connected email inboxes (all configured sources) for a single polling window."""@@ -1790,7 +1792,11 @@ class AgentFunction:if source_context.has_seen_message(credential_id, candidate.message_id):continuetry:- otp_value = await parse_otp_login(candidate.content, organization_id)+ otp_value = await parse_otp_login(+ candidate.content,+ organization_id,+ enforced_otp_type=expected_otp_type,+ )except InsufficientCreditsForOTPParse:source_context.remember_message(credential_id, candidate.message_id)return None@@ -1804,6 +1810,12 @@ class AgentFunction:)continuesource_context.remember_message(credential_id, candidate.message_id)+ if (+ otp_value+ and expected_otp_type is not None+ and otp_value.get_otp_type() != expected_otp_type+ ):+ continueif otp_value:try:# Persist only the resolved OTP value to avoid retaining raw email bodies.diff --git a/skyvern/forge/sdk/services/google_gmail_service.py b/skyvern/forge/sdk/services/google_gmail_service.pyindex b418f6d82..b208a5924 100644--- a/skyvern/forge/sdk/services/google_gmail_service.py+++ b/skyvern/forge/sdk/services/google_gmail_service.py@@ -14,7 +14,10 @@ GMAIL_API_BASE = gmail_client.GMAIL_API_BASEGmailAPIError = gmail_client.GmailAPIErrorLOG = structlog.get_logger()-_OTP_QUERY_TERMS = "(verification OR verify OR code OR passcode OR otp OR 2fa OR one-time OR password)"+_OTP_QUERY_TERMS = (+ '(verification OR verify OR code OR passcode OR otp OR 2fa OR one-time OR password OR "sign in" OR "sign-in" '+ 'OR signin OR "log in" OR "log-in" OR login OR "magic link" OR "access link")'+)_SAFE_EMAIL_QUERY_IDENTIFIER = SAFE_EMAIL_ADDRESS_PATTERN_decode = gmail_client.decode_get_json = gmail_client.get_jsondiff --git a/skyvern/services/email/outlook.py b/skyvern/services/email/outlook.pyindex 9c37b392c..c1d0bfb7d 100644--- a/skyvern/services/email/outlook.py+++ b/skyvern/services/email/outlook.py@@ -37,7 +37,8 @@ _OTP_EXCLUDED_FOLDER_IDS_STATE_KEY = "otp_excluded_folder_ids"_OTP_MAILBOX_IDENTITIES_STATE_KEY = "otp_mailbox_identities"_SAFE_EMAIL_IDENTIFIER = SAFE_EMAIL_ADDRESS_PATTERN_OTP_KEYWORD_PATTERN = re.compile(- r"(?<![A-Za-z0-9])(?:verification|verify|code|passcode|otp|2fa|one(?:[\s-]+)time|password)(?![A-Za-z0-9])",+ r"(?<![A-Za-z0-9])(?:verification|verify|code|passcode|otp|2fa|one(?:[\s-]+)time|password|"+ r"sign(?:[\s-]+)in|signin|log(?:[\s-]+)in|login|(?:magic|access)(?:[\s-]+)link)(?![A-Za-z0-9])",re.IGNORECASE,)# Only EOP-stripped headers are trusted for recipient matching.diff --git a/skyvern/services/otp_service.py b/skyvern/services/otp_service.pyindex 5b00e8919..01b406b4d 100644--- a/skyvern/services/otp_service.py+++ b/skyvern/services/otp_service.py@@ -533,9 +533,10 @@ async def poll_otp_value(otp_value = await _get_otp_value_from_email(organization_id=organization_id,totp_identifier=totp_identifier,- workflow_id=workflow_permanent_id,+ workflow_id=workflow_id,workflow_run_id=workflow_run_id,created_after=email_created_after,+ expected_otp_type=expected_otp_type,context=email_otp_context,)if otp_value is None and totp_identifier:@@ -545,7 +546,7 @@ async def poll_otp_value(organization_id,totp_identifier,task_id=task_id,- workflow_id=workflow_permanent_id,+ workflow_id=workflow_id,workflow_run_id=workflow_run_id,created_after=db_created_after,expected_otp_type=expected_otp_type,@@ -694,6 +695,7 @@ async def _get_otp_value_from_email(workflow_id: str | None = None,workflow_run_id: str | None = None,created_after: datetime | None = None,+ expected_otp_type: OTPType | None = None,context: EmailOTPVerificationContext | None = None,) -> OTPValue | None:return await app.AGENT_FUNCTION.get_otp_value_from_email(@@ -702,6 +704,7 @@ async def _get_otp_value_from_email(workflow_id=workflow_id,workflow_run_id=workflow_run_id,created_after=created_after,+ expected_otp_type=expected_otp_type,context=context,)diff --git a/tests/unit/google/test_otp_service_gmail.py b/tests/unit/google/test_otp_service_gmail.pyindex 99c597920..1e96d6a1c 100644--- a/tests/unit/google/test_otp_service_gmail.py+++ b/tests/unit/google/test_otp_service_gmail.py@@ -89,10 +89,11 @@ async def test_get_otp_value_from_email_uses_gmail_scoped_credentials(monkeypatcresult = await agent.get_otp_value_from_email(organization_id="org_1",- totp_identifier="[email protected]",- workflow_id="wpid_1",+ totp_identifier="[email protected]",+ workflow_id="w_1",workflow_run_id="wr_1",created_after=datetime(2025, 1, 1, tzinfo=timezone.utc),+ expected_otp_type=OTPType.TOTP,)assert result == otp_service.OTPValue(value="123456", type=OTPType.TOTP)@@ -105,19 +106,130 @@ async def test_get_otp_value_from_email_uses_gmail_scoped_credentials(monkeypatcassert search_messages_args is not Noneassert search_messages_args.kwargs["max_results"] == agent_functions.EMAIL_OTP_MAX_RESULTSassert search_messages_args.kwargs["client"] is not None- parse.assert_awaited_once_with("Your verification code is 123456", "org_1")+ parse.assert_awaited_once_with(+ "Your verification code is 123456",+ "org_1",+ enforced_otp_type=OTPType.TOTP,+ )create_otp_code.assert_awaited_once_with("org_1",- "[email protected]",+ "[email protected]","123456","123456",OTPType.TOTP,- workflow_id="wpid_1",+ workflow_id="w_1",workflow_run_id="wr_1",source="gmail",)+async def test_get_otp_value_from_email_skips_mismatched_expected_type(monkeypatch: pytest.MonkeyPatch) -> None:+ agent = AgentFunction()+ credential = SimpleNamespace(+ id="goac_1",+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ )+ monkeypatch.setattr(+ otp_email.google_oauth_service,+ "get_credentials_for_org",+ AsyncMock(return_value=[credential]),+ )+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))+ create_otp_code = AsyncMock()+ monkeypatch.setattr(+ agent_functions.app, "DATABASE", SimpleNamespace(otp=SimpleNamespace(create_otp_code=create_otp_code))+ )+ candidate = google_gmail_service.GmailMessageCandidate(+ message_id="msg_code",+ content="Your sign-in code is 123456",+ internal_date=datetime.now(timezone.utc),+ )+ monkeypatch.setattr(+ otp_email.google_gmail_service,+ "search_recent_otp_messages",+ AsyncMock(return_value=[candidate]),+ )+ parse = AsyncMock(return_value=otp_service.OTPValue(value="123456", type=OTPType.TOTP))+ monkeypatch.setattr(otp_service, "parse_otp_login", parse)+ context = EmailOTPVerificationContext()++ result = await agent.get_otp_value_from_email(+ organization_id="org_1",+ totp_identifier="[email protected]",+ expected_otp_type=OTPType.MAGIC_LINK,+ context=context,+ )++ assert result is None+ parse.assert_awaited_once_with(+ "Your sign-in code is 123456",+ "org_1",+ enforced_otp_type=OTPType.MAGIC_LINK,+ )+ create_otp_code.assert_not_awaited()+ assert context.for_source("gmail").has_seen_message("goac_1", "msg_code")+++async def test_get_otp_value_from_email_keeps_scanning_after_mismatched_candidate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ agent = AgentFunction()+ credential = SimpleNamespace(+ id="goac_1",+ scopes_granted=list(google_oauth_service.GOOGLE_GMAIL_SCOPES),+ )+ monkeypatch.setattr(+ otp_email.google_oauth_service,+ "get_credentials_for_org",+ AsyncMock(return_value=[credential]),+ )+ monkeypatch.setattr(agent, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT")))+ create_otp_code = AsyncMock()+ monkeypatch.setattr(+ agent_functions.app, "DATABASE", SimpleNamespace(otp=SimpleNamespace(create_otp_code=create_otp_code))+ )+ now = datetime.now(timezone.utc)+ candidates = [+ google_gmail_service.GmailMessageCandidate(+ message_id="msg_code",+ content="Your sign-in code is 123456",+ internal_date=now,+ ),+ google_gmail_service.GmailMessageCandidate(+ message_id="msg_link",+ content="Use this link to sign in: https://auth.example.test/magic",+ internal_date=now,+ ),+ ]+ monkeypatch.setattr(+ otp_email.google_gmail_service,+ "search_recent_otp_messages",+ AsyncMock(return_value=candidates),+ )+ magic_link = otp_service.OTPValue(value="https://auth.example.test/magic", type=OTPType.MAGIC_LINK)+ parse = AsyncMock(side_effect=[otp_service.OTPValue(value="123456", type=OTPType.TOTP), magic_link])+ monkeypatch.setattr(otp_service, "parse_otp_login", parse)+ context = EmailOTPVerificationContext()++ result = await agent.get_otp_value_from_email(+ organization_id="org_1",+ totp_identifier="[email protected]",+ expected_otp_type=OTPType.MAGIC_LINK,+ context=context,+ )++ assert result == magic_link+ assert parse.await_count == 2+ assert parse.await_args_list[0].args == ("Your sign-in code is 123456", "org_1")+ assert parse.await_args_list[0].kwargs == {"enforced_otp_type": OTPType.MAGIC_LINK}+ create_otp_code.assert_awaited_once()+ assert create_otp_code.await_args is not None+ assert create_otp_code.await_args.args[2] == magic_link.value+ assert context.for_source("gmail").has_seen_message("goac_1", "msg_code")++@pytest.mark.asyncioasync def test_get_otp_value_from_email_uses_first_parseable_gmail_candidate(monkeypatch: pytest.MonkeyPatch,@@ -161,7 +273,7 @@ async def test_get_otp_value_from_email_uses_first_parseable_gmail_candidate(result = await agent.get_otp_value_from_email(organization_id="org_1",totp_identifier="[email protected]",- workflow_id="wpid_1",+ workflow_id="w_1",workflow_run_id="wr_1",)@@ -176,7 +288,7 @@ async def test_get_otp_value_from_email_uses_first_parseable_gmail_candidate("654321","654321",OTPType.TOTP,- workflow_id="wpid_1",+ workflow_id="w_1",workflow_run_id="wr_1",source="gmail",)@@ -219,7 +331,7 @@ async def test_get_otp_value_from_email_retries_gmail_candidate_after_parser_errfirst_result = await agent.get_otp_value_from_email(organization_id="org_1",totp_identifier="[email protected]",- workflow_id="wpid_1",+ workflow_id="w_1",workflow_run_id="wr_1",context=context,)@@ -227,7 +339,7 @@ async def test_get_otp_value_from_email_retries_gmail_candidate_after_parser_errsecond_result = await agent.get_otp_value_from_email(organization_id="org_1",totp_identifier="[email protected]",- workflow_id="wpid_1",+ workflow_id="w_1",workflow_run_id="wr_1",context=context,)diff --git a/tests/unit/microsoft/test_otp_service_outlook.py b/tests/unit/microsoft/test_otp_service_outlook.pyindex fa08b30f0..ab9f4269a 100644--- a/tests/unit/microsoft/test_otp_service_outlook.py+++ b/tests/unit/microsoft/test_otp_service_outlook.py@@ -22,6 +22,23 @@ def _agent(monkeypatch: pytest.MonkeyPatch, credentials: list[SimpleNamespace])return AgentFunction()+ ("subject", "body"),+ [+ ("Your sign-in link", "Use this link to access your account: https://auth.example.test/session"),+ ("Verification code", "Your verification code is 123456."),+ ],+)+def test_otp_candidate_accepts_authentication_messages(subject: str, body: str) -> None:+ candidate = outlook._otp_candidate(+ {"subject": subject, "body": {"content": body}},+ message_id="message",+ received_datetime=datetime(2026, 8, 4, tzinfo=timezone.utc),+ )++ assert candidate is not None++@pytest.mark.asyncioasync def test_outlook_source_uses_mail_read_credential_and_persists_candidate(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_email_service.py b/tests/unit/test_email_service.pyindex 8e0cb6907..b535b9f43 100644--- a/tests/unit/test_email_service.py+++ b/tests/unit/test_email_service.py@@ -963,7 +963,7 @@ async def test_outlook_otp_search_filters_and_orders_candidates(monkeypatch: pyt),_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("no_keyword", subject="Weekly digest", body="Here is what happened this week."),_outlook_otp_message("junk", parentFolderId="junk_id"),_outlook_otp_message("deleted", parentFolderId="deleted_id"),_outlook_otp_message("sent", parentFolderId="sent_id"),diff --git a/tests/unit/test_otp_service.py b/tests/unit/test_otp_service.pyindex acdbf4e17..573935eb6 100644--- a/tests/unit/test_otp_service.py+++ b/tests/unit/test_otp_service.py@@ -756,20 +756,27 @@ class TestPollOtpValueRetry:) -> None:mock_settings.VERIFICATION_CODE_POLLING_TIMEOUT_MINS = 15mock_email.return_value = None- otp = OTPValue(value="123456", type=OTPType.TOTP)+ otp = OTPValue(value="https://auth.example.test/magic", type=OTPType.MAGIC_LINK)mock_db.return_value = otpresult = await poll_otp_value(organization_id="o_test",task_id="tsk_test",+ workflow_id="w_test",workflow_run_id="wr_test",workflow_permanent_id="wpid_test",- totp_identifier="[email protected]",+ totp_identifier="[email protected]",+ expected_otp_type=OTPType.MAGIC_LINK,)assert result == otpmock_email.assert_awaited_once()mock_db.assert_awaited_once()+ assert mock_email.await_args is not None+ assert mock_db.await_args is not None+ assert mock_email.await_args.kwargs["workflow_id"] == "w_test"+ assert mock_email.await_args.kwargs["expected_otp_type"] == OTPType.MAGIC_LINK+ assert mock_db.await_args.kwargs["workflow_id"] == "w_test"@pytest.mark.asyncio@patch("skyvern.services.otp_service.asyncio.sleep", new_callable=AsyncMock)